From f7cbb45f55833e97f362b23aefc5fbef5b70bb78 Mon Sep 17 00:00:00 2001 From: Julian Ospald Date: Mon, 24 Aug 2026 18:43:19 +0800 Subject: [PATCH 01/23] Add libvirt backend --- Makefile | 30 +- cli/exec/exec.go | 4 +- cmd/agent/main.go | 2 + .../11-backends/35-libvirt.md | 199 ++++++ go.mod | 14 +- go.sum | 25 + pipeline/backend/libvirt/backend_options.go | 49 ++ pipeline/backend/libvirt/disk.go | 296 ++++++++ pipeline/backend/libvirt/domain.go | 447 ++++++++++++ pipeline/backend/libvirt/flags.go | 40 ++ pipeline/backend/libvirt/libvirt.go | 647 ++++++++++++++++++ pipeline/backend/libvirt/prelude.go | 88 +++ pipeline/backend/libvirt/script.go | 52 ++ pipeline/backend/libvirt/script_posix.go | 110 +++ pipeline/backend/libvirt/script_win.go | 100 +++ pipeline/backend/libvirt/ssh.go | 258 +++++++ 16 files changed, 2344 insertions(+), 17 deletions(-) create mode 100644 docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md create mode 100644 pipeline/backend/libvirt/backend_options.go create mode 100644 pipeline/backend/libvirt/disk.go create mode 100644 pipeline/backend/libvirt/domain.go create mode 100644 pipeline/backend/libvirt/flags.go create mode 100644 pipeline/backend/libvirt/libvirt.go create mode 100644 pipeline/backend/libvirt/prelude.go create mode 100644 pipeline/backend/libvirt/script.go create mode 100644 pipeline/backend/libvirt/script_posix.go create mode 100644 pipeline/backend/libvirt/script_win.go create mode 100644 pipeline/backend/libvirt/ssh.go diff --git a/Makefile b/Makefile index 59abcfd773f..63f375f5e6d 100644 --- a/Makefile +++ b/Makefile @@ -42,7 +42,7 @@ STATIC_BUILD ?= true ifeq ($(STATIC_BUILD),true) LDFLAGS := -s -w -extldflags "-static" $(LDFLAGS) endif -CGO_ENABLED ?= 1 # only used to compile server +CGO_ENABLED ?= 1 # only used to compile server and agent and cli HAS_GO = $(shell hash go > /dev/null 2>&1 && echo "GO" || echo "NOGO" ) ifeq ($(HAS_GO),GO) @@ -242,10 +242,10 @@ build-server: build-ui generate-openapi ## Build server CGO_ENABLED=${CGO_ENABLED} GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -tags '$(TAGS)' -ldflags '${LDFLAGS}' -o ${DIST_DIR}/woodpecker-server${BIN_SUFFIX} go.woodpecker-ci.org/woodpecker/v3/cmd/server build-agent: ## Build agent - CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -tags '$(TAGS)' -ldflags '${LDFLAGS}' -o ${DIST_DIR}/woodpecker-agent${BIN_SUFFIX} go.woodpecker-ci.org/woodpecker/v3/cmd/agent + CGO_ENABLED=${CGO_ENABLED} GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -tags '$(TAGS)' -ldflags '${LDFLAGS}' -o ${DIST_DIR}/woodpecker-agent${BIN_SUFFIX} go.woodpecker-ci.org/woodpecker/v3/cmd/agent build-cli: ## Build cli - CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -tags '$(TAGS)' -ldflags '${LDFLAGS}' -o ${DIST_DIR}/woodpecker-cli${BIN_SUFFIX} go.woodpecker-ci.org/woodpecker/v3/cmd/cli + CGO_ENABLED=${CGO_ENABLED} GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -tags '$(TAGS)' -ldflags '${LDFLAGS}' -o ${DIST_DIR}/woodpecker-cli${BIN_SUFFIX} go.woodpecker-ci.org/woodpecker/v3/cmd/cli build-tarball: ## Build tar archive mkdir -p ${DIST_DIR} && tar chzvf ${DIST_DIR}/woodpecker-src.tar.gz \ @@ -315,17 +315,17 @@ release-server: ## Create server binaries for release release-agent: ## Create agent binaries for release # 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 - GOOS=freebsd GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=freebsd GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - 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 + GOOS=linux GOARCH=amd64 CGO_ENABLED=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/darwin_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent + GOOS=freebsd GOARCH=amd64 CGO_ENABLED=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent + GOOS=freebsd GOARCH=arm64 CGO_ENABLED=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent + GOOS=openbsd GOARCH=amd64 CGO_ENABLED=${CGO_ENABLED} 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=${CGO_ENABLED} 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 @@ -409,7 +409,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=${CGO_ENABLED} 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 8d58fee20f8..cba23fe13a2 100644 --- a/cli/exec/exec.go +++ b/cli/exec/exec.go @@ -36,6 +36,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" @@ -54,13 +55,14 @@ var Command = &cli.Command{ Usage: "execute a local pipeline", ArgsUsage: "[path/to/.woodpecker.yaml]", Action: run, - Flags: slices.Concat(flags, docker.Flags, kubernetes.Flags, local.Flags), + Flags: slices.Concat(flags, docker.Flags, kubernetes.Flags, local.Flags, libvirt.Flags), } var backends = []backend_types.Backend{ kubernetes.New(), docker.New(), local.New(), + libvirt.New(), } func run(ctx context.Context, c *cli.Command) error { 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/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..51c4a261554 --- /dev/null +++ b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md @@ -0,0 +1,199 @@ +# Libvirt + +Woodpecker supports a new experimental backend 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 +- 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 + +## 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/go.mod b/go.mod index c11ca96f7b1..c229903ede7 100644 --- a/go.mod +++ b/go.mod @@ -9,12 +9,16 @@ require ( codeberg.org/6543/go-yaml2json/v2 v2.0.0 codeberg.org/6543/xyaml/v2 v2.0.1 codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v3 v3.0.0 + darvaza.org/x/sync v0.5.1 github.com/6543/logfile-open v1.2.1 github.com/adrg/xdg v0.5.3 + github.com/beevik/etree v1.7.0 github.com/bmatcuk/doublestar/v4 v4.10.0 github.com/cenkalti/backoff/v7 v7.0.0 github.com/containerd/errdefs v1.0.0 github.com/distribution/reference v0.6.0 + github.com/djherbis/buffer v1.2.0 + github.com/djherbis/nio/v3 v3.0.1 github.com/docker/cli v29.8.0+incompatible github.com/docker/go-connections v0.8.1 github.com/docker/go-units v0.5.0 @@ -31,11 +35,13 @@ require ( github.com/google/go-github/v91 v91.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.52 + github.com/melbahja/goph v1.5.1 github.com/migueleliasweb/go-github-mock v1.5.0 github.com/moby/moby/api v1.56.0 github.com/moby/moby/client v0.6.0 @@ -58,6 +64,7 @@ require ( gitlab.com/gitlab-org/api/client-go/v2 v2.64.0 go.uber.org/multierr v1.11.0 go.yaml.in/yaml/v4 v4.0.0-rc.6 + golang.org/x/crypto v0.57.0 golang.org/x/image v0.46.0 golang.org/x/net v0.59.0 golang.org/x/oauth2 v0.37.0 @@ -70,6 +77,8 @@ require ( k8s.io/api v0.37.0 k8s.io/apimachinery v0.37.0 k8s.io/client-go v0.37.0 + libvirt.org/go/libvirt v1.12006.0 + libvirt.org/go/libvirtxml v1.12007.0 sigs.k8s.io/yaml v1.6.0 src.techknowlogick.com/xormigrate v1.7.1 xorm.io/builder v0.3.13 @@ -81,6 +90,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.20.0 // indirect filippo.io/edwards25519 v1.2.0 // indirect github.com/42wim/httpsig v1.2.4 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect @@ -161,6 +171,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/blackmagic v1.0.4 // indirect @@ -193,6 +204,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.10 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.70.1 // indirect @@ -226,7 +239,6 @@ require ( go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.57.0 // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/sys v0.48.0 // indirect golang.org/x/time v0.15.0 // indirect diff --git a/go.sum b/go.sum index 0b3c6ca6fa4..5d1f548d886 100644 --- a/go.sum +++ b/go.sum @@ -18,6 +18,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/v3 v3.0.0 h1:s2fK+FBwvcYsmKDjNhmoe7B8q9zsgs0UrSlYe9r4XjM= codeberg.org/mvdkleijn/forgejo-sdk/forgejo/v3 v3.0.0/go.mod h1:Is2jTpS1dizeXm4skQv/ES3QVqnzcNhn2GzZXpiw9f8= +darvaza.org/core v0.20.0 h1:VDPAWvQTLKWRxh337oM4Oti73gGjI30bcywYV+wD2GA= +darvaza.org/core v0.20.0/go.mod h1:GJN97FU/397WUTtm+BLeSkieAhtDevVm/lsGyHmkp0Y= +darvaza.org/x/sync v0.5.1 h1:zKIINbjtKx8Su5qmthCQ8hS71iACTUnlhrofYGXlFd4= +darvaza.org/x/sync v0.5.1/go.mod h1:app0MAeFkfB4enN5cvY42d/R1hbKChj1pYYZXudo8Mc= 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= @@ -50,6 +54,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.7.0 h1:xjBk9O4p4x7D1YajePjfLzdaFC4/uYUENA7P0pv6gXA= +github.com/beevik/etree v1.7.0/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.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs= @@ -129,6 +135,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.0 h1:PH5Dd2ss0C7CRRhQCZ2u7MssF+No9ide8Ye71nPHcrQ= +github.com/djherbis/buffer v1.2.0/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/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= @@ -351,6 +362,8 @@ github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0f github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle v1.3.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +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= @@ -373,6 +386,8 @@ github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzh github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +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.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -435,6 +450,8 @@ github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U= github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= +github.com/melbahja/goph v1.5.1 h1:gdZyjn5nM6FO6mAZrv7XqE2gArQbb+V6FdIyH3Ru3vA= +github.com/melbahja/goph v1.5.1/go.mod h1:dDwo+44cmvfDLdiVpc6fJxexf5BA5yEDUeE5YgtuDO4= 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= @@ -495,6 +512,10 @@ github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0 github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +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.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU= +github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA= 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= @@ -825,6 +846,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.12006.0 h1:GdABzh62cBh/mlFp6HYfcyfHbCGohmGHXPj9kYBIp04= +libvirt.org/go/libvirt v1.12006.0/go.mod h1:1WiFE8EjZfq+FCVog+rvr1yatKbKZ9FaFMZgEqxEJqQ= +libvirt.org/go/libvirtxml v1.12007.0 h1:gdomG2dDDsPSydxjela/I87YHdGsnkHXPLOAQ6iCQBQ= +libvirt.org/go/libvirtxml v1.12007.0/go.mod h1:7Oq2BLDstLr/XtoQD8Fr3mfDNrzlI3utYKySXF2xkng= lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= diff --git a/pipeline/backend/libvirt/backend_options.go b/pipeline/backend/libvirt/backend_options.go new file mode 100644 index 00000000000..752103eda89 --- /dev/null +++ b/pipeline/backend/libvirt/backend_options.go @@ -0,0 +1,49 @@ +// 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. + +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..fe40ab1941a --- /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. + +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 string, domainType string, diskSize string, 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 "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + } + + // 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 "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + } + + } + + // 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 loop_dev []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 "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + } + } + + // mount loop device + { + var err error + loop_dev, 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(loop_dev)) + log.Debug().Msgf("Format device: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + } + } + + // Get disk UUID + { + var err error + diskUuid, err = GetBhyveDiskUUIDLoop(loop_dev) + if err != nil { + return "", "", err + } + } + + // detach loop device + { + err := UnmountLoopDev(loop_dev) + if err != nil { + return "", "", err + } + } + + return disk, diskUuid, nil + } +} + +func (e *libvirt) FromBaseImage(ctx context.Context, baseImage string, 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", string(err.(*exec.ExitError).Stderr)) + 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 "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + + r := csv.NewReader(strings.NewReader(string(bytes))) + header, err := r.Read() + if err != nil { + return "", fmt.Errorf("Failed parsing CVS output for UUID: %s", err.Error()) + } + 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: %s", err.Error()) + } + diskUuid = data[i] + + return diskUuid, nil +} + +func GetBhyveDiskUUIDLoop(loop_dev []byte) (diskUuid string, err error) { + cmd := CmdViaSudo("blkid", "-o", "value", "--match-tag", "UUID", string(loop_dev)) + log.Debug().Msgf("Get UUID: %s", cmd.Args) + bytes, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + + diskUuid = string(bytes) + + return diskUuid, nil +} + +func GetBhyveDiskUUID(disk string) (diskUuid string, err error) { + var loop_dev []byte + // mount loop device + { + var err error + loop_dev, err = MountLoopDev(disk) + if err != nil { + return "", err + } + } + + // Get disk UUID + { + var err error + diskUuid, err = GetBhyveDiskUUIDLoop(loop_dev) + if err != nil { + return "", err + } + } + + // detach loop device + { + err = UnmountLoopDev(loop_dev) + 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, fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + return out, nil +} + +func UnmountLoopDev(loop_dev []byte) error { + cmd := CmdViaSudo("losetup", "--detach", string(loop_dev)) + log.Debug().Msgf("Detach loop device: %s", cmd.Args) + _, err := cmd.Output() + if err != nil { + return fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + } + return nil +} + +func GetDiskUUID(disk string, 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..29047cdaac8 --- /dev/null +++ b/pipeline/backend/libvirt/domain.go @@ -0,0 +1,447 @@ +// 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. + +package libvirt + +import ( + "context" + "encoding/xml" + "fmt" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/beevik/etree" + "github.com/cenkalti/backoff/v7" + "github.com/rs/zerolog/log" + pipeline_errors "go.woodpecker-ci.org/woodpecker/v3/pipeline/errors" + virt "libvirt.org/go/libvirt" + "libvirt.org/go/libvirtxml" +) + +func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]string, persistent bool, sharedDisk SharedDisk, taskUUID string, stepUUID string) (outDomain *virt.Domain, newName string, guestOS string, uuid string, err error) { + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + domain, err := e.conn.LookupDomainByName(image) + + if err != nil { + return nil, "", "", "", err + } + + defer domain.Free() + + 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 := err.(virt.Error); 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..ec3e13c7ffe --- /dev/null +++ b/pipeline/backend/libvirt/flags.go @@ -0,0 +1,40 @@ +// 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. + +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..4fdcc257924 --- /dev/null +++ b/pipeline/backend/libvirt/libvirt.go @@ -0,0 +1,647 @@ +// 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. + +package libvirt + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sync" + "time" + + "darvaza.org/x/sync/mutex" + "github.com/jakobii/syncx" + + "github.com/cenkalti/backoff/v7" + "github.com/djherbis/buffer" + "github.com/djherbis/nio/v3" + "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" + + "github.com/melbahja/goph" + + "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" + 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" +) + +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") + + return virt.NewConnect(libvirtUri) + +} + +// 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) (ret_err error) { + switch step.Type { + case types.StepTypeClone: + return ErrUnsupportedCloning + case types.StepTypeCommands: + case 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 ret_err != nil { + mutex.SafeUnlock(&e.stepLock) + } + }() + + 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 fmt.Errorf("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: 22, + 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(1024 * 1024)) + 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(): + err := e.TerminateSshCommand(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) (b_state *backend_types.State, ret_err error) { + switch step.Type { + case types.StepTypeClone: + return nil, ErrUnsupportedCloning + case types.StepTypeCommands: + case types.StepTypePlugin: + return nil, ErrUnsupportedStepType + default: + return nil, ErrUnsupportedStepType + } + + defer func() { + mutex.SafeUnlock(&e.stepLock) + }() + + sshCmd, ok := e.commands.Load(step.UUID) + if !ok { + return nil, fmt.Errorf("Could not find key %s for commands", step.UUID) + } + + done, ok := e.doneChannel.Load(step.UUID) + if !ok { + return nil, fmt.Errorf("Could not find key %s for doneChannel", step.UUID) + } + + sshErr := sshCmd.(*goph.Cmd).Wait() + close(done.(chan struct{})) + + domain, ok := e.domains.Load(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.(*virt.Domain)) + if err != nil { + return nil, err + } + e.domains.Delete(step.UUID) + + switch e := sshErr.(type) { + case *ssh.ExitMissingError: + return &backend_types.State{ + Exited: true, + ExitCode: -1, + OOMKilled: false, + }, sshErr + case *ssh.ExitError: + return &backend_types.State{ + Exited: true, + ExitCode: e.ExitStatus(), + OOMKilled: false, + }, sshErr + case nil: + return &backend_types.State{ + Exited: true, + ExitCode: 0, + OOMKilled: false, + }, sshErr + default: + return nil, sshErr + } +} + +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 types.StepTypeClone: + return nil, ErrUnsupportedCloning + case types.StepTypeCommands: + case types.StepTypePlugin: + return nil, ErrUnsupportedStepType + default: + return nil, ErrUnsupportedStepType + } + + pOut, ok := e.pipesStdOut.Load(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.(*pipes).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 types.StepTypeClone: + // ignore cloning for now + return ErrUnsupportedCloning + case types.StepTypeCommands: + case types.StepTypePlugin: + return ErrUnsupportedStepType + default: + return ErrUnsupportedStepType + } + libvirtImgDir := e.c.String("backend-libvirt-image-dir") + + defer func() { + // release lock + err := mutex.SafeUnlock(&e.stepLock) + if err != nil { + log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) + } + + keep_tmp := e.c.Bool("backend-libvirt-keep-tmp") + + // clean up ephemeral image + if !keep_tmp { + 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 := e.commands.Load(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.(*goph.Cmd).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 { + err := mutex.SafeUnlock(&e.stepLock) + if err != nil { + log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) + } + + e.commands.Range(func(key, value any) bool { + value.(*goph.Cmd).Close() + e.commands.Delete(key) + return true + }) + e.domains.Range(func(key, value any) bool { + ShutdownVM(ctx, value.(*virt.Domain)) + e.domains.Delete(key) + return true + }) + + keep_tmp := e.c.Bool("backend-libvirt-keep-tmp") + + // clean up shared disk + if !keep_tmp { + 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 !keep_tmp { + { + 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/prelude.go b/pipeline/backend/libvirt/prelude.go new file mode 100644 index 00000000000..8a8f999d47e --- /dev/null +++ b/pipeline/backend/libvirt/prelude.go @@ -0,0 +1,88 @@ +// 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. + +package libvirt + +import ( + "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...) + } +} + +func hasCommand(cmd string) bool { + _, err := exec.LookPath(cmd) + return err == nil +} + +func CopyFile(from string, to string, overwrite bool) error { + fromFile, err := os.Open(from) + if err != nil { + return err + } + defer fromFile.Close() + + if overwrite == false { + _, 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())) + + var macBytes []byte + + macBytes = make([]byte, 6) + + for i := 0; i < len(macBytes); i++ { + macBytes[i] = byte(r.Intn(256)) + } + + // 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/script.go b/pipeline/backend/libvirt/script.go new file mode 100644 index 00000000000..bbd34eeb5a2 --- /dev/null +++ b/pipeline/backend/libvirt/script.go @@ -0,0 +1,52 @@ +// 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. + +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..3117c2c4b6d --- /dev/null +++ b/pipeline/backend/libvirt/script_posix.go @@ -0,0 +1,110 @@ +// 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. + +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 string, 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..c116fc80e2a --- /dev/null +++ b/pipeline/backend/libvirt/ssh.go @@ -0,0 +1,258 @@ +// 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. + +package libvirt + +import ( + "context" + "encoding/base64" + "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 string, 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 string, 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: %s", 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 doesn't do it +// 2. send SIGTERM... if that doesn't do it +// 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(options BackendOptions, client *goph.Client, sshCmd *goph.Cmd, guestOS string, taskUUID string, 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(pid, client, guestOS, stepUUID) + if err != nil { + return err + } + if running { + return fmt.Errorf("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(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(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(pid, client, guestOS, stepUUID) + if err != nil { + return err + } + if running { + return fmt.Errorf("All methods exhausted. Failed to stop SSH process!") + } + } + } + } + + return nil +} + +func GetWoodpeckerPid(client *goph.Client, guestOS string, 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(pid string, client *goph.Client, guestOS string, 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: %s", err)) + } + } else { + var err error + sshCmd, err = client.Command("kill", "-0", pid) + if err != nil { + return true, backoff.Permanent(fmt.Errorf("Error running command: %s", err)) + } + } + + // run with exponential backoff + b, _ := backoff.Retry(context.Background(), func() (bool, error) { + sshErr := sshCmd.Run() + // if we can't figure out if it's running... assume it is + switch sshErr.(type) { + case *ssh.ExitMissingError: + log.Debug().Msgf("ExitMissingError in CheckSshPid: %s", sshErr) + return true, nil + case *ssh.ExitError: + log.Debug().Msgf("ExitError in CheckSshPid: %s", sshErr) + return false, nil + case 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 +} From 2c015cd1db0f4d969578e5ed1a35885f56e77b43 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 18:15:50 +0100 Subject: [PATCH 02/23] format docs --- .../11-backends/35-libvirt.md | 105 +++++++++--------- 1 file changed, 52 insertions(+), 53 deletions(-) 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 index 51c4a261554..a2a41049d69 100644 --- a/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md +++ b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md @@ -120,35 +120,35 @@ New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\BitLocker" ` ## 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 +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`, @@ -167,33 +167,32 @@ labels: 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 + - 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`. - From 7e453739f65f1e29498159aaa13f5656c3fda5a6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 18:29:39 +0100 Subject: [PATCH 03/23] add libvirt_dlopen tag --- .golangci.yaml | 1 + Makefile | 1 + pipeline/backend/libvirt/libvirt.go | 7 +++++-- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index ef69e29a370..7c5627b5fc5 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -3,6 +3,7 @@ run: timeout: 15m build-tags: - test + - libvirt_dlopen linters: default: none enable: diff --git a/Makefile b/Makefile index 0d0c6bc9df6..6f4a9a7ef4b 100644 --- a/Makefile +++ b/Makefile @@ -37,6 +37,7 @@ else endif TAGS ?= +override TAGS += libvirt_dlopen LDFLAGS := -X go.woodpecker-ci.org/woodpecker/v3/version.Version=${VERSION} STATIC_BUILD ?= true ifeq ($(STATIC_BUILD),true) diff --git a/pipeline/backend/libvirt/libvirt.go b/pipeline/backend/libvirt/libvirt.go index 4fdcc257924..9c2c5e204d9 100644 --- a/pipeline/backend/libvirt/libvirt.go +++ b/pipeline/backend/libvirt/libvirt.go @@ -101,8 +101,11 @@ func ConnectToLibvirt(ctx context.Context) (*virt.Connect, error) { } libvirtUri := c.String("backend-libvirt-uri") - return virt.NewConnect(libvirtUri) - + 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 From a136ff49627968397857b531f5d0570962b5c3d6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 19:44:33 +0100 Subject: [PATCH 04/23] collect backend flags like agent --- cli/exec/exec.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cli/exec/exec.go b/cli/exec/exec.go index 4492582e7ae..9bf41935697 100644 --- a/cli/exec/exec.go +++ b/cli/exec/exec.go @@ -55,7 +55,7 @@ var Command = &cli.Command{ Usage: "execute a local pipeline", ArgsUsage: "[path/to/.woodpecker.yaml]", Action: run, - Flags: slices.Concat(flags, docker.Flags, kubernetes.Flags, local.Flags, libvirt.Flags), + Flags: slices.Concat(flags, backendFlags(backends)), } var backends = []backend_types.Backend{ @@ -65,6 +65,14 @@ var backends = []backend_types.Backend{ 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 run(ctx context.Context, c *cli.Command) error { return common.RunPipelineFunc(ctx, c, execFile, execDir) } From ab5dc83d42084d1721737fd299a4911c867274e7 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 21:26:19 +0100 Subject: [PATCH 05/23] make libvirt backend tag gated --- .../11-backends/35-libvirt.md | 1 + pipeline/backend/libvirt/backend_options.go | 2 + pipeline/backend/libvirt/disk.go | 2 + pipeline/backend/libvirt/domain.go | 2 + pipeline/backend/libvirt/flags.go | 2 + pipeline/backend/libvirt/libvirt.go | 2 + pipeline/backend/libvirt/nocgo.go | 52 +++++++++++++++++++ pipeline/backend/libvirt/prelude.go | 2 + pipeline/backend/libvirt/script.go | 2 + pipeline/backend/libvirt/script_posix.go | 2 + pipeline/backend/libvirt/script_win.go | 2 + pipeline/backend/libvirt/ssh.go | 2 + 12 files changed, 73 insertions(+) create mode 100644 pipeline/backend/libvirt/nocgo.go 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 index a2a41049d69..d5766f74955 100644 --- a/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md +++ b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md @@ -59,6 +59,7 @@ 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 diff --git a/pipeline/backend/libvirt/backend_options.go b/pipeline/backend/libvirt/backend_options.go index 752103eda89..36794bd17fa 100644 --- a/pipeline/backend/libvirt/backend_options.go +++ b/pipeline/backend/libvirt/backend_options.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/disk.go b/pipeline/backend/libvirt/disk.go index fe40ab1941a..8a534de9058 100644 --- a/pipeline/backend/libvirt/disk.go +++ b/pipeline/backend/libvirt/disk.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/domain.go b/pipeline/backend/libvirt/domain.go index 29047cdaac8..46e4ee8dd9d 100644 --- a/pipeline/backend/libvirt/domain.go +++ b/pipeline/backend/libvirt/domain.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/flags.go b/pipeline/backend/libvirt/flags.go index ec3e13c7ffe..352a5f88941 100644 --- a/pipeline/backend/libvirt/flags.go +++ b/pipeline/backend/libvirt/flags.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/libvirt.go b/pipeline/backend/libvirt/libvirt.go index 9c2c5e204d9..34254b38d47 100644 --- a/pipeline/backend/libvirt/libvirt.go +++ b/pipeline/backend/libvirt/libvirt.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/nocgo.go b/pipeline/backend/libvirt/nocgo.go new file mode 100644 index 00000000000..230b82ae438 --- /dev/null +++ b/pipeline/backend/libvirt/nocgo.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 []cli.Flag } + +func (*stub) Load(context.Context) (*backend_types.BackendInfo, error) { + return nil, fmt.Errorf("libvirt backend is not compiled in, build with LIBVIRT_ENABLED=1") +} diff --git a/pipeline/backend/libvirt/prelude.go b/pipeline/backend/libvirt/prelude.go index 8a8f999d47e..074c89f9047 100644 --- a/pipeline/backend/libvirt/prelude.go +++ b/pipeline/backend/libvirt/prelude.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/script.go b/pipeline/backend/libvirt/script.go index bbd34eeb5a2..7d75eab6348 100644 --- a/pipeline/backend/libvirt/script.go +++ b/pipeline/backend/libvirt/script.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/script_posix.go b/pipeline/backend/libvirt/script_posix.go index 3117c2c4b6d..eb315ba7c01 100644 --- a/pipeline/backend/libvirt/script_posix.go +++ b/pipeline/backend/libvirt/script_posix.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/script_win.go b/pipeline/backend/libvirt/script_win.go index b74a50aab6c..208a1fae624 100644 --- a/pipeline/backend/libvirt/script_win.go +++ b/pipeline/backend/libvirt/script_win.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( diff --git a/pipeline/backend/libvirt/ssh.go b/pipeline/backend/libvirt/ssh.go index c116fc80e2a..05858b9f7ba 100644 --- a/pipeline/backend/libvirt/ssh.go +++ b/pipeline/backend/libvirt/ssh.go @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build cgo && libvirt + package libvirt import ( From 14fb0c7f8cb6667a96cf861e06d469c53e14e94c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 21:27:27 +0100 Subject: [PATCH 06/23] gofumpt --- pipeline/backend/libvirt/disk.go | 8 ++++---- pipeline/backend/libvirt/domain.go | 3 --- pipeline/backend/libvirt/libvirt.go | 3 --- pipeline/backend/libvirt/script_win.go | 3 ++- pipeline/backend/libvirt/ssh.go | 2 -- 5 files changed, 6 insertions(+), 13 deletions(-) diff --git a/pipeline/backend/libvirt/disk.go b/pipeline/backend/libvirt/disk.go index 8a534de9058..8fd65b86089 100644 --- a/pipeline/backend/libvirt/disk.go +++ b/pipeline/backend/libvirt/disk.go @@ -64,18 +64,18 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy { var cmd *exec.Cmd if fstype == "ntfs" { - cmd = exec.Command("guestfish", "-a", disk, "--", "run", ":", + 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", ":", + cmd = exec.Command( + "guestfish", "-a", disk, "--", "run", ":", "mkfs", fstype, "/dev/sda", // format ) - } log.Debug().Msgf("Format disk: %s", cmd.Args) _, err := cmd.Output() diff --git a/pipeline/backend/libvirt/domain.go b/pipeline/backend/libvirt/domain.go index 46e4ee8dd9d..d14d9de7c01 100644 --- a/pipeline/backend/libvirt/domain.go +++ b/pipeline/backend/libvirt/domain.go @@ -36,7 +36,6 @@ import ( func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]string, persistent bool, sharedDisk SharedDisk, taskUUID string, stepUUID string) (outDomain *virt.Domain, newName string, guestOS string, uuid string, err error) { libvirtImgDir := e.c.String("backend-libvirt-image-dir") domain, err := e.conn.LookupDomainByName(image) - if err != nil { return nil, "", "", "", err } @@ -339,7 +338,6 @@ func ShutdownVM(ctx context.Context, domain *virt.Domain) error { 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() @@ -426,7 +424,6 @@ func getGuestOS(domain *virt.Domain) (string, error) { } } else { - // TODO: what does 'ID' return? return guestInfo.OS.ID, nil } diff --git a/pipeline/backend/libvirt/libvirt.go b/pipeline/backend/libvirt/libvirt.go index 34254b38d47..d20f26f5222 100644 --- a/pipeline/backend/libvirt/libvirt.go +++ b/pipeline/backend/libvirt/libvirt.go @@ -188,7 +188,6 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU e.guestOS.Store(step.UUID, guestOS) scriptIn, entry, err := GenerateSSHConf(step, guestOS) - if err != nil { return err } @@ -244,7 +243,6 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU Callback: ssh.InsecureIgnoreHostKey(), }) }, backoff.WithMaxElapsedTime(maxBackOff)) - if err != nil { return err } @@ -262,7 +260,6 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU args := []string{"-noprofile", "-noninteractive", "-encodedcommand", base64.StdEncoding.EncodeToString(utf16leBytes)} err = AdhocSSH(ctx, client, cmd, args, taskUUID, step.UUID) - if err != nil { return err } diff --git a/pipeline/backend/libvirt/script_win.go b/pipeline/backend/libvirt/script_win.go index 208a1fae624..0c5e272f49b 100644 --- a/pipeline/backend/libvirt/script_win.go +++ b/pipeline/backend/libvirt/script_win.go @@ -65,7 +65,8 @@ func generateScriptWindows(commands []string, env map[string]string, workDir str & { %s } - `, buf.String()) + `, buf.String(), + ) return wrapped } diff --git a/pipeline/backend/libvirt/ssh.go b/pipeline/backend/libvirt/ssh.go index 05858b9f7ba..2ea43470deb 100644 --- a/pipeline/backend/libvirt/ssh.go +++ b/pipeline/backend/libvirt/ssh.go @@ -87,7 +87,6 @@ func AdhocSSHElevated(ctx context.Context, client *goph.Client, cmd string, args // 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(options BackendOptions, client *goph.Client, sshCmd *goph.Cmd, guestOS string, taskUUID string, stepUUID string) error { - pid, err := GetWoodpeckerPid(client, guestOS, stepUUID) if err != nil { return err @@ -253,7 +252,6 @@ func CheckSshPid(pid string, client *goph.Client, guestOS string, stepUUID strin log.Debug().Msgf("Unexpected error in CheckSshPid: %s", sshErr) return true, nil } - }, backoff.WithMaxElapsedTime(maxBackOff)) return b, nil From eb64db4563a3200cbffefaa28f428bc92dd281fe Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 22:17:42 +0100 Subject: [PATCH 07/23] modernize build system part1 --- .golangci.yaml | 2 ++ .woodpecker/binaries.yaml | 7 +++--- .woodpecker/docker.yaml | 9 ++++--- Makefile | 40 ++++++++++++++++++++++++++---- pipeline/backend/libvirt/nocgo.go | 2 +- server/store/datastore/init.go | 2 +- server/store/datastore/init_cgo.go | 2 +- 7 files changed, 49 insertions(+), 15 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 7c5627b5fc5..d851a6c15d0 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -3,6 +3,8 @@ run: timeout: 15m build-tags: - test + - sqlite + - libvirt - libvirt_dlopen linters: default: none diff --git a/.woodpecker/binaries.yaml b/.woodpecker/binaries.yaml index 24af162997d..cc697906b3a 100644 --- a/.woodpecker/binaries.yaml +++ b/.woodpecker/binaries.yaml @@ -11,7 +11,7 @@ variables: - &node_image 'docker.io/node:26-alpine' - &xgo_image 'docker.io/techknowlogick/xgo:go-1.27.x' -# cspell:words bindata netgo +# cspell:words netgo steps: build-web: @@ -40,8 +40,9 @@ steps: - apt install -y tree - make cross-compile-server environment: - PLATFORMS: linux|arm64/v8;linux|amd64;linux|riscv64;windows|amd64;freebsd|amd64 - TAGS: bindata sqlite sqlite_unlock_notify netgo + PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;windows|amd64;freebsd|amd64' + SQLITE_ENABLED: 'true' + TAGS: 'netgo' ARCHIVE_IT: '1' build-tarball: diff --git a/.woodpecker/docker.yaml b/.woodpecker/docker.yaml index 1a4d7a6f8ed..5b76ded0baa 100644 --- a/.woodpecker/docker.yaml +++ b/.woodpecker/docker.yaml @@ -95,9 +95,10 @@ steps: - apt update - apt install -y tree - make cross-compile-server - environment: - PLATFORMS: linux|amd64 - TAGS: sqlite sqlite_unlock_notify netgo + environment: &server_env + PLATFORMS: 'linux|amd64' + SQLITE_ENABLED: 'true' + TAGS: 'netgo' when: - event: [pull_request, pull_request_metadata] evaluate: 'CI_COMMIT_PULL_REQUEST_LABELS contains "build_pr_images"' @@ -115,8 +116,8 @@ steps: - apt install -y tree - make cross-compile-server environment: + <<: *server_env PLATFORMS: linux|arm/v7;linux|arm64/v8;linux|amd64;linux|ppc64le;linux|riscv64;freebsd|amd64 - TAGS: sqlite sqlite_unlock_notify netgo when: branch: - ${CI_REPO_DEFAULT_BRANCH} diff --git a/Makefile b/Makefile index 6f4a9a7ef4b..11876bebef3 100644 --- a/Makefile +++ b/Makefile @@ -36,21 +36,50 @@ else endif endif +# feature flags (static, sqlite, libvirt, ...) TAGS ?= -override TAGS += libvirt_dlopen LDFLAGS := -X go.woodpecker-ci.org/woodpecker/v3/version.Version=${VERSION} + STATIC_BUILD ?= true ifeq ($(STATIC_BUILD),true) LDFLAGS := -s -w -extldflags "-static" $(LDFLAGS) endif -CGO_ENABLED ?= 1 # only used to compile server and agent and cli -HAS_GO = $(shell hash go > /dev/null 2>&1 && echo "GO" || echo "NOGO" ) -ifeq ($(HAS_GO),GO) - CGO_CFLAGS ?= $(shell go env CGO_CFLAGS) +# only forwarded on server and agent and cli compilation +CGO_ENABLED ?= 1 +ifeq ($(shell hash go > /dev/null 2>&1 && echo 1),$(CGO_ENABLED)) + CGO_CFLAGS ?= $(shell go env CGO_CFLAGS) endif CGO_CFLAGS ?= +# 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 +else + ifeq ($(SQLITE_ENABLED),true) + $(error wrong combination CGO_ENABLED must be '1' if SQLITE_ENABLED is 'true') + endif +endif +SQLITE_ENABLED ?= +ifeq ($(SQLITE_ENABLED),true) + override TAGS += sqlite sqlite_unlock_notify +endif # If the first argument is "in_docker"... ifeq (in_docker,$(firstword $(MAKECMDGOALS))) @@ -69,6 +98,7 @@ ifeq (in_docker,$(firstword $(MAKECMDGOALS))) -e TARGETOS="linux" \ -e TARGETARCH="$(TARGETARCH)" \ -e CGO_ENABLED="$(CGO_ENABLED)" \ + -e LIBVIRT_ENABLED="$(LIBVIRT_ENABLED)" \ -v $(PWD):/build --rm woodpecker/make:local make $(MAKE_ARGS) else diff --git a/pipeline/backend/libvirt/nocgo.go b/pipeline/backend/libvirt/nocgo.go index 230b82ae438..19a18400f31 100644 --- a/pipeline/backend/libvirt/nocgo.go +++ b/pipeline/backend/libvirt/nocgo.go @@ -48,5 +48,5 @@ func (*stub) IsAvailable(ctx context.Context) bool { func (*stub) Flags() []cli.Flag { return []cli.Flag } func (*stub) Load(context.Context) (*backend_types.BackendInfo, error) { - return nil, fmt.Errorf("libvirt backend is not compiled in, build with LIBVIRT_ENABLED=1") + return nil, fmt.Errorf("libvirt backend is not compiled in, build with LIBVIRT_ENABLED=true") } diff --git a/server/store/datastore/init.go b/server/store/datastore/init.go index 75ebea17026..4edbc94a600 100644 --- a/server/store/datastore/init.go +++ b/server/store/datastore/init.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build !cgo +//go:build !cgo || !sqlite package datastore diff --git a/server/store/datastore/init_cgo.go b/server/store/datastore/init_cgo.go index 65f20a5aaee..549f79d3f97 100644 --- a/server/store/datastore/init_cgo.go +++ b/server/store/datastore/init_cgo.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build cgo +//go:build cgo && sqlite package datastore From 7ffe17b7cf27e9e42054931dd4cac9b4c756f7a3 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 22:21:16 +0100 Subject: [PATCH 08/23] fix --- pipeline/backend/libvirt/nocgo.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pipeline/backend/libvirt/nocgo.go b/pipeline/backend/libvirt/nocgo.go index 19a18400f31..cd55768cd5d 100644 --- a/pipeline/backend/libvirt/nocgo.go +++ b/pipeline/backend/libvirt/nocgo.go @@ -45,8 +45,8 @@ func (*stub) IsAvailable(ctx context.Context) bool { return ok && c.String("backend-engine") == engineName } -func (*stub) Flags() []cli.Flag { return []cli.Flag } +func (*stub) Flags() []cli.Flag { return nil } func (*stub) Load(context.Context) (*backend_types.BackendInfo, error) { - return nil, fmt.Errorf("libvirt backend is not compiled in, build with LIBVIRT_ENABLED=true") + return nil, errors.New("libvirt backend is not compiled in, build with LIBVIRT_ENABLED=true") } From 0d41072722a6021cb32f8c10cd30eb52bc2c2893 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 22:24:29 +0100 Subject: [PATCH 09/23] better wording --- pipeline/backend/libvirt/nocgo.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pipeline/backend/libvirt/nocgo.go b/pipeline/backend/libvirt/nocgo.go index cd55768cd5d..2e0dc97855a 100644 --- a/pipeline/backend/libvirt/nocgo.go +++ b/pipeline/backend/libvirt/nocgo.go @@ -48,5 +48,5 @@ func (*stub) IsAvailable(ctx context.Context) bool { 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, build with LIBVIRT_ENABLED=true") + return nil, errors.New("libvirt backend is not compiled in, compile backend with LIBVIRT_ENABLED=true") } From fb5cb44c2c2967985a0398433bab626cac38bb0c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 23:21:09 +0100 Subject: [PATCH 10/23] cross compile linux binaries as they can have libvirt --- .woodpecker/binaries.yaml | 33 +++++++++++++++++++++ .woodpecker/docker.yaml | 1 + Makefile | 60 ++++++++++++++++----------------------- 3 files changed, 58 insertions(+), 36 deletions(-) diff --git a/.woodpecker/binaries.yaml b/.woodpecker/binaries.yaml index cc697906b3a..57dbc82496d 100644 --- a/.woodpecker/binaries.yaml +++ b/.woodpecker/binaries.yaml @@ -42,9 +42,38 @@ steps: environment: PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;windows|amd64;freebsd|amd64' SQLITE_ENABLED: 'true' + 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' + 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' + ARCHIVE_IT: '1' + build-tarball: depends_on: - vendor @@ -74,6 +103,8 @@ steps: build-deb-rpm: depends_on: - cross-compile-server + - cross-compile-agent + - cross-compile-cli - build-agent - build-cli image: *golang_image @@ -83,6 +114,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/Makefile b/Makefile index 11876bebef3..f87a8ca86ea 100644 --- a/Makefile +++ b/Makefile @@ -296,42 +296,46 @@ build: build-agent build-server build-cli ## Build all binaries release-frontend: build-ui ## Build frontend cross-compile-server: ## Cross compile the server +cross-compile-agent: ## Cross compile the agent +cross-compile-cli: ## Cross compile the cli +cross-compile-server cross-compile-agent cross-compile-cli: cross-compile-%: $(foreach platform,$(subst ;, ,$(PLATFORMS)),\ + COMPONENT=$* \ TARGETOS=$(firstword $(subst |, ,$(platform))) \ TARGETARCH_XGO=$(subst arm64/v8,arm64,$(subst arm/v7,arm-7,$(word 2,$(subst |, ,$(platform))))) \ TARGETARCH_BUILDX=$(subst arm64/v8,arm64,$(subst arm/v7,arm,$(word 2,$(subst |, ,$(platform))))) \ - make release-server-xgo || exit 1; \ + make release-xgo || exit 1; \ ) tree ${DIST_DIR} -release-server-xgo: check-xgo ## Create server binaries for release using xgo +release-xgo: check-xgo ## Create binaries of COMPONENT (server, agent or cli) for release using xgo @echo "Building for:" @echo "os:$(TARGETOS)" @echo "arch orgi:$(TARGETARCH)" @echo "arch (xgo):$(TARGETARCH_XGO)" @echo "arch (buildx):$(TARGETARCH_BUILDX)" # build via xgo - CGO_CFLAGS="$(CGO_CFLAGS)" xgo -go $(XGO_VERSION) -dest ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX) -tags 'netgo osusergo grpcnotrace $(TAGS)' -ldflags '-linkmode external $(LDFLAGS)' -targets '$(TARGETOS)/$(TARGETARCH_XGO)' -out woodpecker-server -pkg cmd/server . + CGO_CFLAGS="$(CGO_CFLAGS)" xgo -go $(XGO_VERSION) -dest ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX) -tags 'netgo osusergo grpcnotrace $(TAGS)' -ldflags '-linkmode external $(LDFLAGS)' -targets '$(TARGETOS)/$(TARGETARCH_XGO)' -out woodpecker-$(COMPONENT) -pkg cmd/$(COMPONENT) . # move binary into subfolder depending on target os and arch @if [ "$${XGO_IN_XGO:-0}" -eq "1" ]; then \ echo "inside xgo image"; \ - mkdir -p ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX); \ - mv -vf /build/woodpecker-server* ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-server$(BIN_SUFFIX); \ + mkdir -p ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX); \ + mv -vf /build/woodpecker-$(COMPONENT)* ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-$(COMPONENT)$(BIN_SUFFIX); \ else \ echo "outside xgo image"; \ - [ -f "${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-server$(BIN_SUFFIX)" ] && rm -v ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-server$(BIN_SUFFIX); \ - mv -v ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_XGO)/woodpecker-server* ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-server$(BIN_SUFFIX); \ + [ -f "${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-$(COMPONENT)$(BIN_SUFFIX)" ] && rm -v ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-$(COMPONENT)$(BIN_SUFFIX); \ + mv -v ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_XGO)/woodpecker-$(COMPONENT)* ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-$(COMPONENT)$(BIN_SUFFIX); \ fi # if enabled package it in an archive @if [ "$${ARCHIVE_IT:-0}" -eq "1" ]; then \ if [ "$(BIN_SUFFIX)" = ".exe" ]; then \ - rm -f ${DIST_DIR}/woodpecker-server_$(TARGETOS)_$(TARGETARCH_BUILDX).zip; \ - zip -j ${DIST_DIR}/woodpecker-server_$(TARGETOS)_$(TARGETARCH_BUILDX).zip ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-server.exe; \ + rm -f ${DIST_DIR}/woodpecker-$(COMPONENT)_$(TARGETOS)_$(TARGETARCH_BUILDX).zip; \ + zip -j ${DIST_DIR}/woodpecker-$(COMPONENT)_$(TARGETOS)_$(TARGETARCH_BUILDX).zip ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX)/woodpecker-$(COMPONENT).exe; \ else \ - tar -cvzf ${DIST_DIR}/woodpecker-server_$(TARGETOS)_$(TARGETARCH_BUILDX).tar.gz -C ${DIST_DIR}/server/$(TARGETOS)_$(TARGETARCH_BUILDX) woodpecker-server$(BIN_SUFFIX); \ + tar -cvzf ${DIST_DIR}/woodpecker-$(COMPONENT)_$(TARGETOS)_$(TARGETARCH_BUILDX).tar.gz -C ${DIST_DIR}/$(COMPONENT)/$(TARGETOS)_$(TARGETARCH_BUILDX) woodpecker-$(COMPONENT)$(BIN_SUFFIX); \ fi; \ else \ - echo "skip creating '${DIST_DIR}/woodpecker-server_$(TARGETOS)_$(TARGETARCH_BUILDX).tar.gz'"; \ + echo "skip creating '${DIST_DIR}/woodpecker-$(COMPONENT)_$(TARGETOS)_$(TARGETARCH_BUILDX).tar.gz'"; \ fi release-server: ## Create server binaries for release @@ -344,24 +348,16 @@ 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} 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=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/darwin_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=freebsd GOARCH=amd64 CGO_ENABLED=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=freebsd GOARCH=arm64 CGO_ENABLED=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent - GOOS=openbsd GOARCH=amd64 CGO_ENABLED=${CGO_ENABLED} 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=${CGO_ENABLED} go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/openbsd_arm64/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 + GOOS=freebsd GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_amd64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent + GOOS=freebsd GOARCH=arm64 CGO_ENABLED=0 go build -ldflags '${LDFLAGS}' -tags 'grpcnotrace $(TAGS)' -o ${DIST_DIR}/agent/freebsd_arm64/woodpecker-agent go.woodpecker-ci.org/woodpecker/v3/cmd/agent + 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 @@ -372,12 +368,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 @@ -386,10 +378,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 From e6c00e3876535745cf031c2a9e4489013cbc6645 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 23:24:23 +0100 Subject: [PATCH 11/23] disable libvirt in container images --- docker/Dockerfile.agent.alpine.multiarch | 2 +- docker/Dockerfile.agent.multiarch | 2 +- docker/Dockerfile.cli.alpine.multiarch.rootless | 2 +- docker/Dockerfile.cli.multiarch.rootless | 2 +- .../10-configuration/11-backends/35-libvirt.md | 5 +++++ 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docker/Dockerfile.agent.alpine.multiarch b/docker/Dockerfile.agent.alpine.multiarch index a6a4ddcd2aa..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 \ - 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 535aa4c6185..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 \ - 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 3ea63a33a28..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 \ - 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 c81eab4a22d..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 \ - 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 index d5766f74955..9581733808b 100644 --- a/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md +++ b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md @@ -64,6 +64,11 @@ These are the requirements for the host that runs the woodpecker agent: - 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/). From 095f64692d63e8fb1ec0ddd71fbf6aba46ca1117 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 23:27:44 +0100 Subject: [PATCH 12/23] fix cspell --- pipeline/backend/libvirt/{nocgo.go => libvirt_disabled.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename pipeline/backend/libvirt/{nocgo.go => libvirt_disabled.go} (100%) diff --git a/pipeline/backend/libvirt/nocgo.go b/pipeline/backend/libvirt/libvirt_disabled.go similarity index 100% rename from pipeline/backend/libvirt/nocgo.go rename to pipeline/backend/libvirt/libvirt_disabled.go From 02a57b66800f815db243647edddceb2ec721dff0 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 10 Nov 2026 23:59:41 +0100 Subject: [PATCH 13/23] update docs ... make experimental warning similar to other docs & link --- Makefile | 3 +++ .../10-configuration/11-backends/35-libvirt.md | 4 +++- docs/docs/30-administration/10-configuration/30-agent.md | 8 +++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index f87a8ca86ea..b0efc9446c0 100644 --- a/Makefile +++ b/Makefile @@ -295,8 +295,11 @@ build: build-agent build-server build-cli ## Build all binaries .PHONY: release-frontend release-frontend: build-ui ## Build frontend +.PHONY: cross-compile-server cross-compile-server: ## Cross compile the server +.PHONY: cross-compile-agent cross-compile-agent: ## Cross compile the agent +.PHONY: cross-compile-cli cross-compile-cli: ## Cross compile the cli cross-compile-server cross-compile-agent cross-compile-cli: cross-compile-%: $(foreach platform,$(subst ;, ,$(PLATFORMS)),\ 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 index 9581733808b..f58f53d057b 100644 --- a/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md +++ b/docs/docs/30-administration/10-configuration/11-backends/35-libvirt.md @@ -1,6 +1,8 @@ # Libvirt -Woodpecker supports a new experimental backend for executing steps within a virtual machine. +:::warning +Woodpecker comes with experimental support for executing steps within a virtual machine. +::: This is achieved by utilizing [libvirt](https://libvirt.org/). 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 From bc2ed4b286c9390f061c53f673492ea5fa1ef4da Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 00:28:53 +0100 Subject: [PATCH 14/23] first round of lint issues fixed --- Makefile | 4 ++-- pipeline/backend/libvirt/script_posix.go | 6 +++--- pipeline/backend/libvirt/script_win.go | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index b0efc9446c0..ea9bb03c86b 100644 --- a/Makefile +++ b/Makefile @@ -48,7 +48,7 @@ endif # only forwarded on server and agent and cli compilation CGO_ENABLED ?= 1 ifeq ($(shell hash go > /dev/null 2>&1 && echo 1),$(CGO_ENABLED)) - CGO_CFLAGS ?= $(shell go env CGO_CFLAGS) + CGO_CFLAGS ?= $(shell go env CGO_CFLAGS) endif CGO_CFLAGS ?= @@ -64,7 +64,7 @@ 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 + override TAGS += libvirt_dlopen endif endif diff --git a/pipeline/backend/libvirt/script_posix.go b/pipeline/backend/libvirt/script_posix.go index eb315ba7c01..e3b31086a13 100644 --- a/pipeline/backend/libvirt/script_posix.go +++ b/pipeline/backend/libvirt/script_posix.go @@ -71,11 +71,11 @@ set +m b64decode() { if echo "bG9sCg==" | base64 -d >/dev/null 2>&1 ; then - base64 -d + base64 -d elif echo "bG9sCg==" | base64 -D >/dev/null 2>&1 ; then - base64 -D + base64 -D else - openssl base64 -d -A + openssl base64 -d -A fi } diff --git a/pipeline/backend/libvirt/script_win.go b/pipeline/backend/libvirt/script_win.go index 0c5e272f49b..627e283df1c 100644 --- a/pipeline/backend/libvirt/script_win.go +++ b/pipeline/backend/libvirt/script_win.go @@ -64,8 +64,8 @@ func generateScriptWindows(commands []string, env map[string]string, workDir str ` & { %s - } - `, buf.String(), + } + `, buf.String(), ) return wrapped } @@ -96,8 +96,8 @@ Write-Output @' '@ & { - %s ; - if ($LASTEXITCODE) { exit $LASTEXITCODE } ; + %s ; + if ($LASTEXITCODE) { exit $LASTEXITCODE } ; } ; ` From ec67bb0eff6de0a755307c802bb25f70271d4d57 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 00:33:36 +0100 Subject: [PATCH 15/23] fix tests --- Makefile | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index ea9bb03c86b..b146c270e91 100644 --- a/Makefile +++ b/Makefile @@ -223,21 +223,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 libvirt libvirt_dlopen' 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 libvirt libvirt_dlopen' 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) From 54a97430e8afe1c6f20eaa522167fe501e6cc20e Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 00:38:21 +0100 Subject: [PATCH 16/23] generate cli docs with libvirt --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index b146c270e91..f70f9d41bcf 100644 --- a/Makefile +++ b/Makefile @@ -434,7 +434,7 @@ docs-dependencies: ## Install docs dependencies .PHONY: generate-docs generate-docs: ## Generate docs (currently only for the cli) - CGO_ENABLED=${CGO_ENABLED} 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 From 37a3966ce0215270551023bb30b4a42cd0f77264 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 09:51:28 +0100 Subject: [PATCH 17/23] fix windows build and only have libvirt on linux --- .woodpecker/binaries.yaml | 2 +- Makefile | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.woodpecker/binaries.yaml b/.woodpecker/binaries.yaml index 57dbc82496d..f05a93bd058 100644 --- a/.woodpecker/binaries.yaml +++ b/.woodpecker/binaries.yaml @@ -40,7 +40,7 @@ steps: - apt install -y tree - make cross-compile-server environment: - PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;windows|amd64;freebsd|amd64' + PLATFORMS: 'linux|arm64/v8;linux|amd64;linux|riscv64;windows-10|amd64;freebsd|amd64' SQLITE_ENABLED: 'true' STATIC_BUILD: 'true' TAGS: 'netgo' diff --git a/Makefile b/Makefile index f70f9d41bcf..b709d93a6fa 100644 --- a/Makefile +++ b/Makefile @@ -52,6 +52,10 @@ ifeq ($(shell hash go > /dev/null 2>&1 && echo 1),$(CGO_ENABLED)) endif CGO_CFLAGS ?= +ifneq ($(TARGETOS),linux) + override LIBVIRT_ENABLED := false +endif + # enable libvirt by default if cgo is enabled ifeq ($(CGO_ENABLED),1) LIBVIRT_ENABLED ?= true From 85a84dbe2f2f7694dcfb2418c10404a05d970a3f Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 10:19:11 +0100 Subject: [PATCH 18/23] libvirt is needed for engine test --- .woodpecker/test.yaml | 11 ++++++++++- flake.nix | 1 + 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.woodpecker/test.yaml b/.woodpecker/test.yaml index 577356d72f3..f48da4a4d49 100644 --- a/.woodpecker/test.yaml +++ b/.woodpecker/test.yaml @@ -84,7 +84,7 @@ steps: - apk add --no-cache -q bash && bash .woodpecker/check-test-file-map-source-file.sh when: *when - test: + test-components: depends_on: - vendor image: *golang_image @@ -92,6 +92,15 @@ steps: - make test-agent - make test-server - make test-cli + when: + - path: *when_path + + test-engine: + depends_on: + - vendor + image: *golang_image + commands: + - apt install -y libvirt - make test-lib when: - path: *when_path diff --git a/flake.nix b/flake.nix index 2f683c518f4..1a151366993 100644 --- a/flake.nix +++ b/flake.nix @@ -63,6 +63,7 @@ bash nushell powershell + libvirt ]; CFLAGS = "-I${pkgs.glibc.dev}/include"; LDFLAGS = "-L${pkgs.glibc}/lib"; From df3b515c9b6d1aef7faaac35000ca484061eb7f5 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 10:31:50 +0100 Subject: [PATCH 19/23] fix golang-lint-issues and use helper for common go codeblocks etc --- .golangci.yaml | 4 + .woodpecker/test.yaml | 2 +- pipeline/backend/libvirt/disk.go | 82 ++++++------ pipeline/backend/libvirt/domain.go | 50 ++++---- pipeline/backend/libvirt/libvirt.go | 153 +++++++++++++---------- pipeline/backend/libvirt/prelude.go | 25 ++-- pipeline/backend/libvirt/prelude_test.go | 49 ++++++++ pipeline/backend/libvirt/script_posix.go | 2 +- pipeline/backend/libvirt/script_win.go | 2 +- pipeline/backend/libvirt/ssh.go | 58 ++++----- 10 files changed, 250 insertions(+), 177 deletions(-) create mode 100644 pipeline/backend/libvirt/prelude_test.go diff --git a/.golangci.yaml b/.golangci.yaml index d851a6c15d0..0a923130322 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -192,6 +192,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/test.yaml b/.woodpecker/test.yaml index f48da4a4d49..fd9d0eab29d 100644 --- a/.woodpecker/test.yaml +++ b/.woodpecker/test.yaml @@ -100,7 +100,7 @@ steps: - vendor image: *golang_image commands: - - apt install -y libvirt + - apt update && apt install -y libvirt-dev - make test-lib when: - path: *when_path diff --git a/pipeline/backend/libvirt/disk.go b/pipeline/backend/libvirt/disk.go index 8fd65b86089..88e826c5a32 100644 --- a/pipeline/backend/libvirt/disk.go +++ b/pipeline/backend/libvirt/disk.go @@ -28,10 +28,10 @@ import ( "github.com/rs/zerolog/log" ) -func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainType string, diskSize string, taskUUID string) (string, string, error) { +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 diskUUID string var fstype string if guestOS == "windows" { fstype = "ntfs" @@ -53,7 +53,7 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy log.Debug().Msgf("Create shared disk: %s", cmd.Args) _, err := cmd.Output() if err != nil { - return "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return "", "", cmdError(cmd, err) } } @@ -80,28 +80,26 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy log.Debug().Msgf("Format disk: %s", cmd.Args) _, err := cmd.Output() if err != nil { - return "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return "", "", cmdError(cmd, err) } } - } // get uuid - diskUuid, err = GetQemuDiskUUID(disk) + diskUUID, err = GetQemuDiskUUID(disk) if err != nil { return "", "", err } - return disk, diskUuid, nil - + 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) + 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 loop_dev []byte + var loopDev []byte _, statErr := os.Stat(disk) if statErr != nil { @@ -111,7 +109,7 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy log.Debug().Msgf("Create shared disk: %s", cmd.Args) _, err := cmd.Output() if err != nil { - return "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return "", "", cmdError(cmd, err) } } } @@ -119,7 +117,7 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy // mount loop device { var err error - loop_dev, err = MountLoopDev(disk) + loopDev, err = MountLoopDev(disk) if err != nil { return "", "", err } @@ -129,11 +127,11 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy // 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(loop_dev)) + 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 "", "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return "", "", cmdError(cmd, err) } } } @@ -141,7 +139,7 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy // Get disk UUID { var err error - diskUuid, err = GetBhyveDiskUUIDLoop(loop_dev) + diskUUID, err = GetBhyveDiskUUIDLoop(loopDev) if err != nil { return "", "", err } @@ -149,17 +147,17 @@ func (e *libvirt) CreateSharedDisk(ctx context.Context, guestOS string, domainTy // detach loop device { - err := UnmountLoopDev(loop_dev) + err := UnmountLoopDev(loopDev) if err != nil { return "", "", err } } - return disk, diskUuid, nil + return disk, diskUUID, nil } } -func (e *libvirt) FromBaseImage(ctx context.Context, baseImage string, targetImg string, overwrite bool) (string, error) { +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) @@ -176,7 +174,7 @@ func (e *libvirt) FromBaseImage(ctx context.Context, baseImage string, targetImg 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", string(err.(*exec.ExitError).Stderr)) + 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 @@ -192,18 +190,18 @@ func (e *libvirt) FromBaseImage(ctx context.Context, baseImage string, targetImg return libvirtImg, nil } -func GetQemuDiskUUID(disk string) (diskUuid string, err error) { +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 "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + 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: %s", err.Error()) + return "", fmt.Errorf("failed parsing CVS output for UUID: %w", err) } i := -1 for ix, e := range header { @@ -213,37 +211,37 @@ func GetQemuDiskUUID(disk string) (diskUuid string, err error) { } if i == -1 { - return "", fmt.Errorf("Could not find UUID in: %s", header) + 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: %s", err.Error()) + return "", fmt.Errorf("failed parsing CVS output for UUID: %w", err) } - diskUuid = data[i] + diskUUID = data[i] - return diskUuid, nil + return diskUUID, nil } -func GetBhyveDiskUUIDLoop(loop_dev []byte) (diskUuid string, err error) { - cmd := CmdViaSudo("blkid", "-o", "value", "--match-tag", "UUID", string(loop_dev)) +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 "", fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return "", cmdError(cmd, err) } - diskUuid = string(bytes) + diskUUID = string(bytes) - return diskUuid, nil + return diskUUID, nil } -func GetBhyveDiskUUID(disk string) (diskUuid string, err error) { - var loop_dev []byte +func GetBhyveDiskUUID(disk string) (diskUUID string, err error) { + var loopDev []byte // mount loop device { var err error - loop_dev, err = MountLoopDev(disk) + loopDev, err = MountLoopDev(disk) if err != nil { return "", err } @@ -252,7 +250,7 @@ func GetBhyveDiskUUID(disk string) (diskUuid string, err error) { // Get disk UUID { var err error - diskUuid, err = GetBhyveDiskUUIDLoop(loop_dev) + diskUUID, err = GetBhyveDiskUUIDLoop(loopDev) if err != nil { return "", err } @@ -260,13 +258,13 @@ func GetBhyveDiskUUID(disk string) (diskUuid string, err error) { // detach loop device { - err = UnmountLoopDev(loop_dev) + err = UnmountLoopDev(loopDev) if err != nil { return "", err } } - return diskUuid, nil + return diskUUID, nil } func MountLoopDev(disk string) ([]byte, error) { @@ -274,22 +272,22 @@ func MountLoopDev(disk string) ([]byte, error) { log.Debug().Msgf("Mount loop device: %s", cmd.Args) out, err := cmd.Output() if err != nil { - return nil, fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return nil, cmdError(cmd, err) } return out, nil } -func UnmountLoopDev(loop_dev []byte) error { - cmd := CmdViaSudo("losetup", "--detach", string(loop_dev)) +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 fmt.Errorf("command %s failed with %s and stderr: %s", cmd.String(), err.Error(), err.(*exec.ExitError).Stderr) + return cmdError(cmd, err) } return nil } -func GetDiskUUID(disk string, domainType string) (diskUuid string, err error) { +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 { diff --git a/pipeline/backend/libvirt/domain.go b/pipeline/backend/libvirt/domain.go index d14d9de7c01..7c73fb13e76 100644 --- a/pipeline/backend/libvirt/domain.go +++ b/pipeline/backend/libvirt/domain.go @@ -19,6 +19,7 @@ package libvirt import ( "context" "encoding/xml" + "errors" "fmt" "path/filepath" "slices" @@ -28,19 +29,21 @@ import ( "github.com/beevik/etree" "github.com/cenkalti/backoff/v7" "github.com/rs/zerolog/log" - pipeline_errors "go.woodpecker-ci.org/woodpecker/v3/pipeline/errors" 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 string, stepUUID string) (outDomain *virt.Domain, newName string, guestOS string, uuid string, err error) { +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 } - defer domain.Free() + // 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 { @@ -48,14 +51,14 @@ func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]s } // get the XML from the loaded domain - domXml, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) + domXML, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) if err != nil { return nil, "", "", "", err } domcfg := &libvirtxml.Domain{} { - err := domcfg.Unmarshal(domXml) + err := domcfg.Unmarshal(domXML) if err != nil { return nil, "", "", "", err } @@ -65,7 +68,7 @@ func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]s domcfg.UUID = "" if domcfg.Devices == nil { - return nil, "", "", "", fmt.Errorf("No devices in domain") + return nil, "", "", "", fmt.Errorf("no devices in domain") } if !persistent { @@ -122,7 +125,7 @@ func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]s } var disk string - var diskUuid string + var diskUUID string // insert the shared disk if any if sharedDisk.Disk != "" { @@ -138,16 +141,15 @@ func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]s log.Debug().Msgf("Inserting shared disk: %s", sharedDisk.Disk) if sharedDisk.UUID != "" { - diskUuid = 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) + disk, diskUUID, err = e.CreateSharedDisk(ctx, guestOS, domainType, diskSize, taskUUID) if err != nil { return nil, "", "", "", err } @@ -246,15 +248,15 @@ func (e *libvirt) LoadDomain(ctx context.Context, image string, env map[string]s uuid = serial } else { // if we don't have a disk UUID by now, get it explicitly - if diskUuid == "" { - diskUuid, err = GetDiskUUID(disk, domainType) + 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 + uuid = diskUUID } // insert @@ -310,7 +312,6 @@ func ShutdownVM(ctx context.Context, domain *virt.Domain) error { if err != nil { return err } - } // wait 2 minutes for clean shutdown @@ -321,7 +322,7 @@ func ShutdownVM(ctx context.Context, domain *virt.Domain) error { info, err := domain.GetInfo() if err != nil { // sometimes we race and the domain is shut down already - if lverr, ok := err.(virt.Error); ok && lverr.Code == virt.ERR_NO_DOMAIN { + if lverr, ok := errors.AsType[virt.Error](err); ok && lverr.Code == virt.ERR_NO_DOMAIN { return nil, nil } else { return nil, err @@ -335,7 +336,7 @@ func ShutdownVM(ctx context.Context, domain *virt.Domain) error { case virt.DOMAIN_SHUTOFF: return nil, nil default: - return nil, backoff.Permanent(fmt.Errorf("Unexpected state: %d", info.State)) + return nil, backoff.Permanent(fmt.Errorf("unexpected state: %d", info.State)) } }, backoff.WithMaxElapsedTime(maxBackOff)) if err != nil { @@ -346,7 +347,7 @@ func ShutdownVM(ctx context.Context, domain *virt.Domain) error { } } - domain.Free() + _ = domain.Free() return nil } @@ -356,25 +357,25 @@ func getGuestOS(domain *virt.Domain) (string, error) { 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) + 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 { + 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") + 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") + return "", fmt.Errorf("could not determine guest platform, add libosinfo metadata to the domain") } switch { case strings.Contains(fileAttr.Value, "/win/"): @@ -420,9 +421,8 @@ func getGuestOS(domain *virt.Domain) (string, error) { case strings.Contains(fileAttr.Value, "dragonflybsd"): return "dragonflybsd", nil default: - return "", fmt.Errorf("Could not determine guest platform, add libosinfo metadata to the domain") + 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 @@ -430,13 +430,13 @@ func getGuestOS(domain *virt.Domain) (string, error) { } func GetDomainType(ctx context.Context, domain *virt.Domain) (string, error) { - domXml, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) + domXML, err := domain.GetXMLDesc(virt.DOMAIN_XML_INACTIVE) if err != nil { return "", err } domcfg := &libvirtxml.Domain{} { - err := domcfg.Unmarshal(domXml) + err := domcfg.Unmarshal(domXML) if err != nil { return "", err } diff --git a/pipeline/backend/libvirt/libvirt.go b/pipeline/backend/libvirt/libvirt.go index d20f26f5222..17a7ed5a387 100644 --- a/pipeline/backend/libvirt/libvirt.go +++ b/pipeline/backend/libvirt/libvirt.go @@ -29,26 +29,23 @@ import ( "time" "darvaza.org/x/sync/mutex" - "github.com/jakobii/syncx" - "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" - "github.com/melbahja/goph" - - "go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types" 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'") + ErrUnsupportedCloning = errors.New("automatic cloning is not supported in libvirt, set 'skip_clone: true'") ) type libvirt struct { @@ -75,6 +72,8 @@ const ( sharedDiskPattern = "shared_%s%s" defaultMaxTimeout = "2m" defaultGuestInterface = "eth0" + sshPort = 22 + logBufferSize = 1024 * 1024 ) func New() backend_types.Backend { @@ -101,9 +100,9 @@ func ConnectToLibvirt(ctx context.Context) (*virt.Connect, error) { if !ok { return nil, backend_types.ErrNoCliContextFound } - libvirtUri := c.String("backend-libvirt-uri") + libvirtURI := c.String("backend-libvirt-uri") - conn, err := virt.NewConnect(libvirtUri) + conn, err := virt.NewConnect(libvirtURI) if err != nil { return nil, fmt.Errorf("libvirt backend is unavailable: %w", err) } @@ -111,7 +110,7 @@ func ConnectToLibvirt(ctx context.Context) (*virt.Connect, error) { } // it's hard to figure out just the socket, so we attempt -// a basic connection and close it immediately +// a basic connection and close it immediately. func (e *libvirt) IsAvailable(ctx context.Context) bool { conn, err := ConnectToLibvirt(ctx) if err != nil { @@ -148,12 +147,12 @@ func (e *libvirt) SetupWorkflow(ctx context.Context, conf *backend_types.Config, return nil } -func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskUUID string) (ret_err error) { +func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskUUID string) (retErr error) { switch step.Type { - case types.StepTypeClone: + case backend_types.StepTypeClone: return ErrUnsupportedCloning - case types.StepTypeCommands: - case types.StepTypePlugin: + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: return ErrUnsupportedStepType default: return ErrUnsupportedStepType @@ -169,8 +168,8 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU log.Debug().Msgf("Step %s acquired lock", step.Name) defer func() { - if ret_err != nil { - mutex.SafeUnlock(&e.stepLock) + if retErr != nil { + e.unlockStep() } }() @@ -229,7 +228,7 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU sshPw, ok := step.Environment["LIBVIRT_SSH_PW"] if !ok { - return fmt.Errorf("No SSH password set for libvirt guest. Set LIBVIRT_SSH_PW via a secret.") + 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) @@ -238,7 +237,7 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU User: options.SSHConfig.User, Auth: goph.Password(sshPw), Addr: sshAddr, - Port: 22, + Port: sshPort, Timeout: goph.DefaultTimeout, Callback: ssh.InsecureIgnoreHostKey(), }) @@ -323,7 +322,7 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU // we need to create pipes and set Stdout here // in TailStep it is potentially too late - pr, pw := nio.Pipe(buffer.New(1024 * 1024)) + pr, pw := nio.Pipe(buffer.New(logBufferSize)) sshCmd.Stdout = nil // see comment below sshCmd.Stderr = nil @@ -351,12 +350,12 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU // 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) + _, _ = io.Copy(pw, stdoutR) wg.Done() }() go func() { - io.Copy(pw, stderrR) + _, _ = io.Copy(pw, stderrR) wg.Done() }() @@ -374,7 +373,8 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU go func() { select { case <-ctx.Done(): - err := e.TerminateSshCommand(options, client, sshCmd, guestOS, taskUUID, step.UUID) + // 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) } @@ -404,62 +404,62 @@ func (e *libvirt) StartStep(ctx context.Context, step *backend_types.Step, taskU return nil } -func (e *libvirt) WaitStep(ctx context.Context, step *backend_types.Step, taskUUID string) (b_state *backend_types.State, ret_err error) { +func (e *libvirt) WaitStep(ctx context.Context, step *backend_types.Step, taskUUID string) (*backend_types.State, error) { switch step.Type { - case types.StepTypeClone: + case backend_types.StepTypeClone: return nil, ErrUnsupportedCloning - case types.StepTypeCommands: - case types.StepTypePlugin: + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: return nil, ErrUnsupportedStepType default: return nil, ErrUnsupportedStepType } - defer func() { - mutex.SafeUnlock(&e.stepLock) - }() + defer e.unlockStep() - sshCmd, ok := e.commands.Load(step.UUID) + sshCmd, ok := load[*goph.Cmd](&e.commands, step.UUID) if !ok { - return nil, fmt.Errorf("Could not find key %s for commands", step.UUID) + return nil, fmt.Errorf("could not find key %s for commands", step.UUID) } - done, ok := e.doneChannel.Load(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) + return nil, fmt.Errorf("could not find key %s for doneChannel", step.UUID) } - sshErr := sshCmd.(*goph.Cmd).Wait() - close(done.(chan struct{})) + sshErr := sshCmd.Wait() + close(done) - domain, ok := e.domains.Load(step.UUID) + domain, ok := load[*virt.Domain](&e.domains, step.UUID) if !ok { - return nil, fmt.Errorf("Could not find key %s for domains", step.UUID) + 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.(*virt.Domain)) + err := ShutdownVM(ctx, domain) if err != nil { return nil, err } e.domains.Delete(step.UUID) - switch e := sshErr.(type) { - case *ssh.ExitMissingError: + 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 *ssh.ExitError: + case errors.As(sshErr, &exitErr): return &backend_types.State{ Exited: true, - ExitCode: e.ExitStatus(), + ExitCode: exitErr.ExitStatus(), OOMKilled: false, }, sshErr - case nil: + case sshErr == nil: return &backend_types.State{ Exited: true, ExitCode: 0, @@ -470,31 +470,45 @@ func (e *libvirt) WaitStep(ctx context.Context, step *backend_types.Step, taskUU } } +// 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 types.StepTypeClone: + case backend_types.StepTypeClone: return nil, ErrUnsupportedCloning - case types.StepTypeCommands: - case types.StepTypePlugin: + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: return nil, ErrUnsupportedStepType default: return nil, ErrUnsupportedStepType } - pOut, ok := e.pipesStdOut.Load(step.UUID) + pOut, ok := load[*pipes](&e.pipesStdOut, step.UUID) if !ok { - return nil, fmt.Errorf("Could not find key %s for pipesStdOut", step.UUID) + return nil, fmt.Errorf("could not find key %s for pipesStdOut", step.UUID) } rc := struct { io.Reader io.Closer }{ - Reader: pOut.(*pipes).pr, + Reader: pOut.pr, Closer: closerFunc(func() error { log.Debug().Msgf("Done log streaming") return nil @@ -506,11 +520,11 @@ func (e *libvirt) TailStep(ctx context.Context, step *backend_types.Step, taskUU func (e *libvirt) DestroyStep(ctx context.Context, step *backend_types.Step, taskUUID string) error { switch step.Type { - case types.StepTypeClone: + case backend_types.StepTypeClone: // ignore cloning for now return ErrUnsupportedCloning - case types.StepTypeCommands: - case types.StepTypePlugin: + case backend_types.StepTypeCommands: + case backend_types.StepTypePlugin: return ErrUnsupportedStepType default: return ErrUnsupportedStepType @@ -519,15 +533,12 @@ func (e *libvirt) DestroyStep(ctx context.Context, step *backend_types.Step, tas defer func() { // release lock - err := mutex.SafeUnlock(&e.stepLock) - if err != nil { - log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) - } + e.unlockStep() - keep_tmp := e.c.Bool("backend-libvirt-keep-tmp") + keepTmp := e.c.Bool("backend-libvirt-keep-tmp") // clean up ephemeral image - if !keep_tmp { + if !keepTmp { ephemeralImgs := filepath.Join(libvirtImgDir, fmt.Sprintf(baseImagePattern, "*", taskUUID, step.UUID, ".*")) matches, err := filepath.Glob(ephemeralImgs) if err != nil { @@ -554,14 +565,14 @@ func (e *libvirt) DestroyStep(ctx context.Context, step *backend_types.Step, tas } }() - sshCmd, ok := e.commands.Load(step.UUID) + sshCmd, ok := load[*goph.Cmd](&e.commands, step.UUID) if !ok { - return fmt.Errorf("Could not find key %s for commands", step.UUID) + 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.(*goph.Cmd).Close() + _ = sshCmd.Close() e.commands.Delete(step.UUID) @@ -572,26 +583,30 @@ func (e *libvirt) DestroyStep(ctx context.Context, step *backend_types.Step, tas } func (e *libvirt) DestroyWorkflow(ctx context.Context, conf *backend_types.Config, taskUUID string) error { - err := mutex.SafeUnlock(&e.stepLock) - if err != nil { - log.Debug().Msgf("Error while unlocking step mutex: %s", err.Error()) - } + e.unlockStep() e.commands.Range(func(key, value any) bool { - value.(*goph.Cmd).Close() + if sshCmd, ok := value.(*goph.Cmd); ok { + _ = sshCmd.Close() + } e.commands.Delete(key) return true }) e.domains.Range(func(key, value any) bool { - ShutdownVM(ctx, value.(*virt.Domain)) + 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 }) - keep_tmp := e.c.Bool("backend-libvirt-keep-tmp") + keepTmp := e.c.Bool("backend-libvirt-keep-tmp") // clean up shared disk - if !keep_tmp { + if !keepTmp { libvirtImgDir := e.c.String("backend-libvirt-image-dir") ephemeralImgs := filepath.Join(libvirtImgDir, fmt.Sprintf(sharedDiskPattern, taskUUID, ".*")) matches, err := filepath.Glob(ephemeralImgs) @@ -611,7 +626,7 @@ func (e *libvirt) DestroyWorkflow(ctx context.Context, conf *backend_types.Confi libvirtImgDir := e.c.String("backend-libvirt-image-dir") // clean up ephemeral images - if !keep_tmp { + if !keepTmp { { ephemeralImgs := filepath.Join(libvirtImgDir, fmt.Sprintf(baseImagePattern, "*", taskUUID, "*", ".*")) matches, err := filepath.Glob(ephemeralImgs) diff --git a/pipeline/backend/libvirt/prelude.go b/pipeline/backend/libvirt/prelude.go index 074c89f9047..bc6bfd3e454 100644 --- a/pipeline/backend/libvirt/prelude.go +++ b/pipeline/backend/libvirt/prelude.go @@ -17,6 +17,7 @@ package libvirt import ( + "errors" "fmt" "io" "math/rand" @@ -33,22 +34,30 @@ func CmdViaSudo(cmd string, arg ...string) *exec.Cmd { } } +// 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 string, to string, overwrite bool) error { +func CopyFile(from, to string, overwrite bool) error { fromFile, err := os.Open(from) if err != nil { return err } defer fromFile.Close() - if overwrite == false { + if !overwrite { _, err := os.Stat(to) if err == nil { - return fmt.Errorf("File %s already exists", to) + return fmt.Errorf("file %s already exists", to) } } @@ -67,17 +76,13 @@ func CopyFile(from string, to string, overwrite bool) error { } // derived from https://github.com/rprata/macgo/blob/85ffbfd9b6ec3c18bde5640302adf7521ef1c2c2/generator/generator.go#L11 -// MIT licensed +// MIT licensed. func GenerateRandomMACAddress() (string, error) { r := rand.New(rand.NewSource(time.Now().UnixNano())) - var macBytes []byte + macBytes := make([]byte, 6) - macBytes = make([]byte, 6) - - for i := 0; i < len(macBytes); i++ { - macBytes[i] = byte(r.Intn(256)) - } + _, _ = r.Read(macBytes) // never fails // we want locally administered unicast macBytes[0] |= 0x02 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_posix.go b/pipeline/backend/libvirt/script_posix.go index e3b31086a13..a163a55cfea 100644 --- a/pipeline/backend/libvirt/script_posix.go +++ b/pipeline/backend/libvirt/script_posix.go @@ -25,7 +25,7 @@ import ( // 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 string, stepUUID string, injectEnv bool) string { +func generateScriptPosix(commands []string, env map[string]string, workDir, stepUUID string, injectEnv bool) string { var buf bytes.Buffer var envBuf bytes.Buffer diff --git a/pipeline/backend/libvirt/script_win.go b/pipeline/backend/libvirt/script_win.go index 627e283df1c..ed9ff281a79 100644 --- a/pipeline/backend/libvirt/script_win.go +++ b/pipeline/backend/libvirt/script_win.go @@ -23,7 +23,7 @@ import ( "text/template" ) -func generateScriptWindows(commands []string, env map[string]string, workDir string, stepUUID string, injectEnv bool) string { +func generateScriptWindows(commands []string, env map[string]string, workDir, stepUUID string, injectEnv bool) string { var buf bytes.Buffer var envBuf bytes.Buffer diff --git a/pipeline/backend/libvirt/ssh.go b/pipeline/backend/libvirt/ssh.go index 2ea43470deb..24576b7ffaf 100644 --- a/pipeline/backend/libvirt/ssh.go +++ b/pipeline/backend/libvirt/ssh.go @@ -19,6 +19,7 @@ package libvirt import ( "context" "encoding/base64" + "errors" "fmt" "os" "time" @@ -30,7 +31,7 @@ import ( "golang.org/x/text/encoding/unicode" ) -func AdhocSSH(ctx context.Context, client *goph.Client, cmd string, args []string, taskUUID string, stepUUID string) error { +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 { @@ -43,7 +44,7 @@ func AdhocSSH(ctx context.Context, client *goph.Client, cmd string, args []strin return err } -func AdhocSSHElevated(ctx context.Context, client *goph.Client, cmd string, args []string, taskUUID string, stepUUID string) error { +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 { @@ -55,7 +56,7 @@ func AdhocSSHElevated(ctx context.Context, client *goph.Client, cmd string, args } b, err := sshCmd.Output() if err != nil { - return fmt.Errorf("Failed to check for sudo: %s", err) + return fmt.Errorf("failed to check for sudo: %w", err) } out = string(b) } @@ -70,7 +71,7 @@ func AdhocSSHElevated(ctx context.Context, client *goph.Client, cmd string, args log.Debug().Msgf("Running as root") command = append([]string{cmd}, args...) default: - return fmt.Errorf("Unexpected privilege escalation command: %s", out) + return fmt.Errorf("unexpected privilege escalation command: %s", out) } // execute command @@ -80,13 +81,13 @@ func AdhocSSHElevated(ctx context.Context, client *goph.Client, cmd string, args // This tries to terminate the command we spawned, not the SSH session itself. // It does so, by: // -// 1. send SIGINT... if that doesn't do it -// 2. send SIGTERM... if that doesn't do it -// 3. execute 'kill -2 ' +// 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(options BackendOptions, client *goph.Client, sshCmd *goph.Cmd, guestOS string, taskUUID string, stepUUID string) error { +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 @@ -112,14 +113,13 @@ func (e *libvirt) TerminateSshCommand(options BackendOptions, client *goph.Clien log.Debug().Msgf("Running taskkill failed with: %s", err) } - running, err := CheckSshPid(pid, client, guestOS, stepUUID) + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) if err != nil { return err } if running { - return fmt.Errorf("All methods exhausted. Failed to stop SSH process!") + 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") @@ -129,7 +129,7 @@ func (e *libvirt) TerminateSshCommand(options BackendOptions, client *goph.Clien } // check if the process died - running, err := CheckSshPid(pid, client, guestOS, stepUUID) + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) if err != nil { return err } @@ -142,7 +142,7 @@ func (e *libvirt) TerminateSshCommand(options BackendOptions, client *goph.Clien } // check if the process died - running, err := CheckSshPid(pid, client, guestOS, stepUUID) + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) if err != nil { return err } @@ -161,12 +161,12 @@ func (e *libvirt) TerminateSshCommand(options BackendOptions, client *goph.Clien } // check if the process died - running, err := CheckSshPid(pid, client, guestOS, stepUUID) + running, err := CheckSSHPid(ctx, pid, client, guestOS, stepUUID) if err != nil { return err } if running { - return fmt.Errorf("All methods exhausted. Failed to stop SSH process!") + return errors.New("all methods exhausted, failed to stop SSH process") } } } @@ -175,7 +175,7 @@ func (e *libvirt) TerminateSshCommand(options BackendOptions, client *goph.Clien return nil } -func GetWoodpeckerPid(client *goph.Client, guestOS string, stepUUID string) (string, error) { +func GetWoodpeckerPid(client *goph.Client, guestOS, stepUUID string) (string, error) { var sshCmd *goph.Cmd // assembler the per-platform command to get the running pid @@ -209,7 +209,7 @@ func GetWoodpeckerPid(client *goph.Client, guestOS string, stepUUID string) (str } // (Re-)Check if the spawned process is still running with a timeout of 15s. -func CheckSshPid(pid string, client *goph.Client, guestOS string, stepUUID string) (bool, error) { +func CheckSSHPid(ctx context.Context, pid string, client *goph.Client, guestOS, stepUUID string) (bool, error) { var sshCmd *goph.Cmd maxBackOff, _ := time.ParseDuration("15s") @@ -225,31 +225,33 @@ func CheckSshPid(pid string, client *goph.Client, guestOS string, stepUUID strin sshCmd, err = client.Command("powershell.exe", "-noprofile", "-noninteractive", "-encodedcommand", base64Cmd) if err != nil { - return true, backoff.Permanent(fmt.Errorf("Error running command: %s", err)) + 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: %s", err)) + return true, backoff.Permanent(fmt.Errorf("error running command: %w", err)) } } // run with exponential backoff - b, _ := backoff.Retry(context.Background(), func() (bool, error) { + b, _ := backoff.Retry(ctx, func() (bool, error) { sshErr := sshCmd.Run() // if we can't figure out if it's running... assume it is - switch sshErr.(type) { - case *ssh.ExitMissingError: - log.Debug().Msgf("ExitMissingError in CheckSshPid: %s", sshErr) + 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 *ssh.ExitError: - log.Debug().Msgf("ExitError in CheckSshPid: %s", sshErr) + case errors.As(sshErr, &exitErr): + log.Debug().Msgf("ExitError in CheckSSHPid: %s", sshErr) return false, nil - case nil: - return true, fmt.Errorf("Process still running") + case sshErr == nil: + return true, fmt.Errorf("process still running") default: - log.Debug().Msgf("Unexpected error in CheckSshPid: %s", sshErr) + log.Debug().Msgf("Unexpected error in CheckSSHPid: %s", sshErr) return true, nil } }, backoff.WithMaxElapsedTime(maxBackOff)) From 0e731c38d5d469921b9372d4c8bd6b41cfaf84d7 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 10:33:32 +0100 Subject: [PATCH 20/23] fix ci config --- .woodpecker/test.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.woodpecker/test.yaml b/.woodpecker/test.yaml index fd9d0eab29d..5e03472adf9 100644 --- a/.woodpecker/test.yaml +++ b/.woodpecker/test.yaml @@ -160,7 +160,8 @@ steps: codecov: depends_on: - - test + - test-components + - test-engine - sqlite pull: true image: docker.io/woodpeckerci/plugin-codecov:2.3.3 From 6175dc2f1b152f7aad586d5719a830953b1410e2 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 11:14:12 +0100 Subject: [PATCH 21/23] tests run localy without libvirt --- Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index b709d93a6fa..c3a9add9213 100644 --- a/Makefile +++ b/Makefile @@ -227,14 +227,14 @@ 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 libvirt libvirt_dlopen' 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 # 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 libvirt libvirt_dlopen' 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 @@ -253,10 +253,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 From 4a35a2c60a45db06edbc2be05e65528a0e3d7eee Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 11 Nov 2026 11:20:26 +0100 Subject: [PATCH 22/23] set golangci-lint timeout to 30 minutes --- .golangci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.golangci.yaml b/.golangci.yaml index 0a923130322..6fd5c32985e 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,6 +1,6 @@ version: '2' run: - timeout: 15m + timeout: 30m build-tags: - test - sqlite From a1ba488d1a81b94c8bd8094446270fad792f8fc9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 24 Nov 2026 23:28:08 +0100 Subject: [PATCH 23/23] Apply suggestion from @6543 --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index 54c12829858..49f4f22358e 100644 --- a/Makefile +++ b/Makefile @@ -103,6 +103,7 @@ ifeq (in_docker,$(firstword $(MAKECMDGOALS))) -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