From 709c2d3e6c4657981fc4628d81ce50c0cbbe6cdc Mon Sep 17 00:00:00 2001 From: Basil Bruhn Date: Mon, 23 Nov 2026 16:47:49 +0100 Subject: [PATCH 1/4] Migrate ELOG packages and container builds to Gitea Actions --- .dockerignore | 18 ++++ .gitea/scripts/build-rpm.sh | 47 ++++++++++ .gitea/scripts/metadata.sh | 35 +++++++ .gitea/scripts/smoke-container.sh | 26 ++++++ .gitea/scripts/smoke-server.sh | 38 ++++++++ .gitea/workflows/build.yml | 115 +++++++++++++++++++++++ .gitignore | 1 + Dockerfile | 27 ++++-- Dockerfile.dockerignore | 8 ++ README.md | 3 + bitbucket-pipelines.yml | 99 -------------------- doc/ci-and-releases.md | 146 ++++++++++++++++++++++++++++++ docker/Dockerfile.build | 31 +++++++ docker/krb5.conf | 21 +++++ makegit | 8 +- 15 files changed, 516 insertions(+), 107 deletions(-) create mode 100644 .dockerignore create mode 100644 .gitea/scripts/build-rpm.sh create mode 100644 .gitea/scripts/metadata.sh create mode 100644 .gitea/scripts/smoke-container.sh create mode 100644 .gitea/scripts/smoke-server.sh create mode 100644 .gitea/workflows/build.yml create mode 100644 Dockerfile.dockerignore delete mode 100644 bitbucket-pipelines.yml create mode 100644 doc/ci-and-releases.md create mode 100644 docker/Dockerfile.build create mode 100644 docker/krb5.conf diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..4a106afc --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +.git +**/.git +.agents +.codex +.aws +.env* +.DS_Store +.idea +build +cmake-build-* +dist +elog +elogd +elconv +*.o +src/git-revision.h +src/git-revision.h.tmp +elog.spec diff --git a/.gitea/scripts/build-rpm.sh b/.gitea/scripts/build-rpm.sh new file mode 100644 index 00000000..8cf7ed3b --- /dev/null +++ b/.gitea/scripts/build-rpm.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Run inside docker/Dockerfile.build, or on an EL host with build dependencies. +set -euo pipefail +cd "$(dirname "$0")/../.." + +release=${1:?Usage: build-rpm.sh RPM_RELEASE OUTPUT_DIRECTORY} +output=${2:?Usage: build-rpm.sh RPM_RELEASE OUTPUT_DIRECTORY} +[[ "$release" =~ ^[0-9][0-9A-Za-z.]*$ ]] || { echo 'Invalid RPM release' >&2; exit 1; } +version=$(sed -n 's/^#define VERSION "\([0-9][0-9.]*\)"/\1/p' src/elog-version.h) +[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid source version' >&2; exit 1; } +[[ -f mxml/mxml.cxx ]] || { echo 'Run git submodule update --init --recursive first' >&2; exit 1; } +revision=${ELOG_BUILD_REVISION:-$(git rev-parse HEAD)} +[[ "$revision" =~ ^[0-9a-f]{40}$|^unknown$ ]] || { echo 'Invalid revision' >&2; exit 1; } + +mkdir -p "$output" +output=$(cd "$output" && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +name="elog-$version-$release" +source_dir="$work/$name" +topdir="$work/rpmbuild" +mkdir -p "$source_dir" "$topdir"/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} + +# Include the checked-out submodule, without nesting Git metadata in releases. +tar --exclude=.git --exclude=git-revision.h --exclude=git-revision.h.tmp -cf - \ + src mxml doc man contrib scripts resources ssl themes logbooks cmake \ + CMakeLists.txt Makefile COPYING README.md elogd.cfg.example \ + elogd.init_template elogd.service elogd.plist makegit \ + | tar -xf - -C "$source_dir" +cp README.md "$source_dir/README" # The existing RPM spec installs this name. +printf '#define GIT_REVISION "%s"\n' "$revision" > "$source_dir/src/git-revision.h" +sed -e "s/__ELOGVER__/$version/g" -e "s/__ELOGREL__/$release/g" \ + -e "s/__GIT__/$revision/g" elog.spec.template > "$topdir/SPECS/elog.spec" +cp "$topdir/SPECS/elog.spec" "$source_dir/elog.spec" +tar -czf "$topdir/SOURCES/$name.tar.gz" -C "$work" "$name" + +rpmbuild -ba "$topdir/SPECS/elog.spec" \ + --define "_topdir $topdir" --define 'debug_package %{nil}' \ + --with krb5 --with ldap --with pam --with ssl + +mkdir -p "$output"/{RPMS,SRPMS,SOURCES} +find "$topdir/RPMS" -name '*.rpm' -exec cp '{}' "$output/RPMS/" \; +cp "$topdir"/SRPMS/*.rpm "$output/SRPMS/" +cp "$topdir/SOURCES/$name.tar.gz" "$output/SOURCES/" +printf 'version=%s\nrelease=%s\nrevision=%s\n' "$version" "$release" "$revision" > "$output/build-info.txt" +cd "$output" +find RPMS SRPMS SOURCES -type f -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS diff --git a/.gitea/scripts/metadata.sh b/.gitea/scripts/metadata.sh new file mode 100644 index 00000000..584931be --- /dev/null +++ b/.gitea/scripts/metadata.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -euo pipefail +export TZ=UTC +cd "$(dirname "$0")/../.." + +version=$(sed -n 's/^#define VERSION "\([0-9][0-9.]*\)"/\1/p' src/elog-version.h) +[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid source version' >&2; exit 1; } +revision=$(git rev-parse HEAD) +short_revision=${revision:0:12} +epoch=$(git show -s --format=%ct HEAD) +timestamp=$(git show -s --format=%cd --date=format-local:%Y%m%d%H%M%S HEAD) +ref=${BUILD_REF:-refs/heads/local} + +if [[ "$ref" == refs/tags/* ]]; then + [[ "$ref" == "refs/tags/v$version" ]] || { + echo "Release tag must be v$version to match src/elog-version.h" >&2 + exit 1 + } + release=1 + image_tag=$version +else + release="0.$timestamp.git$short_revision" + image_tag="sha-$short_revision" +fi + +if [[ -n "${GITHUB_OUTPUT:-}" ]]; then + exec >> "$GITHUB_OUTPUT" +fi +{ + printf 'version=%s\n' "$version" + printf 'revision=%s\n' "$revision" + printf 'source_date_epoch=%s\n' "$epoch" + printf 'rpm_release=%s\n' "$release" + printf 'image_tag=%s\n' "$image_tag" +} diff --git a/.gitea/scripts/smoke-container.sh b/.gitea/scripts/smoke-container.sh new file mode 100644 index 00000000..74efc986 --- /dev/null +++ b/.gitea/scripts/smoke-container.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail +image=${1:?Usage: smoke-container.sh IMAGE} +container=$(docker run --detach "$image") +# shellcheck disable=SC2329 # Invoked by the EXIT trap. +cleanup() { + if [[ "$?" != 0 ]]; then docker logs "$container" >&2 || true; fi + docker rm --force "$container" >/dev/null +} +trap 'cleanup' EXIT +for _attempt in {1..30}; do + # Run in the container's network namespace: runners may themselves be containers. + if docker exec "$container" bash -c ' + exec 3<>/dev/tcp/127.0.0.1/8080 + printf "GET /demo/ HTTP/1.0\r\nHost: localhost\r\n\r\n" >&3 + IFS= read -r -t 5 status <&3 + [[ "$status" == *" 200 "* ]] + ' 2>/dev/null; then + echo 'ELOG container HTTP smoke check passed' + exit 0 + fi + [[ "$(docker inspect -f '{{.State.Running}}' "$container")" == true ]] || break + sleep 1 +done +echo 'ELOG container HTTP smoke check failed' >&2 +exit 1 diff --git a/.gitea/scripts/smoke-server.sh b/.gitea/scripts/smoke-server.sh new file mode 100644 index 00000000..719ed2e2 --- /dev/null +++ b/.gitea/scripts/smoke-server.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail +binary=${1:?Usage: smoke-server.sh ELOGD RESOURCE_DIRECTORY} +resources=${2:?Usage: smoke-server.sh ELOGD RESOURCE_DIRECTORY} +work=$(mktemp -d) +pid= +# shellcheck disable=SC2329 # Invoked by the EXIT trap. +cleanup() { + if [[ -n "$pid" ]]; then kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true; fi + rm -rf "$work" +} +trap 'cleanup' EXIT +mkdir "$work/logbooks" +cat > "$work/elogd.cfg" <<'EOF' +[global] +Usr = root +Grp = root +Logging Level = 0 +Resolve host names = 0 +[ci] +Attributes = Subject +EOF +"$binary" -c "$work/elogd.cfg" -d "$work/logbooks" -s "$resources" \ + -n 127.0.0.1 -p 8080 -f "$work/elogd.pid" > "$work/elogd.log" 2>&1 & +pid=$! +for _attempt in {1..30}; do + if curl --noproxy '*' --fail --silent --show-error --max-time 2 http://127.0.0.1:8080/ci/ > "$work/index.html" 2>/dev/null; then + if grep -qi 'ELOG' "$work/index.html"; then + echo 'ELOG HTTP smoke check passed' + exit 0 + fi + fi + kill -0 "$pid" 2>/dev/null || break + sleep 1 +done +cat "$work/elogd.log" >&2 +echo 'ELOG HTTP smoke check failed' >&2 +exit 1 diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml new file mode 100644 index 00000000..bcd17724 --- /dev/null +++ b/.gitea/workflows/build.yml @@ -0,0 +1,115 @@ +name: Build, test and package ELOG + +on: + push: + branches: ['**'] + tags: ['v*'] + pull_request: + workflow_dispatch: + +env: + # Keep the image address used by deployments from the former images/elog repo. + CONTAINER_IMAGE: gitea.psi.ch/images/elog + +jobs: + packages: + name: Build and test EL${{ matrix.el }} + runs-on: ubuntu-latest-intranet + strategy: + fail-fast: false + matrix: + el: [8, 9, 10] + steps: + - name: Checkout source and mxml + uses: https://gitea.psi.ch/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + submodules: recursive + persist-credentials: false + - name: Derive version and validate release tag + id: metadata + env: + BUILD_REF: ${{ github.ref }} + run: bash .gitea/scripts/metadata.sh + - name: Build, HTTP-test and export packages + env: + EL_VERSION: ${{ matrix.el }} + REVISION: ${{ steps.metadata.outputs.revision }} + RPM_RELEASE: ${{ steps.metadata.outputs.rpm_release }} + SOURCE_DATE_EPOCH: ${{ steps.metadata.outputs.source_date_epoch }} + run: | + docker build --platform linux/amd64 --file docker/Dockerfile.build \ + --build-arg "EL_VERSION=$EL_VERSION" \ + --build-arg "REVISION=$REVISION" \ + --build-arg "RPM_RELEASE=$RPM_RELEASE" \ + --build-arg "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH" \ + --output "type=local,dest=dist/el$EL_VERSION" . + - name: Store RPMs, source archive and checksums + # PSI's Node 20 build of the Gitea-compatible v3 artifact protocol. + uses: https://gitea.psi.ch/actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 + with: + name: elog-el${{ matrix.el }} + path: dist/el${{ matrix.el }}/ + if-no-files-found: error + retention-days: 30 + + container: + name: Build and test EL9 container + needs: packages + runs-on: ubuntu-latest-intranet + steps: + - name: Checkout + uses: https://gitea.psi.ch/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: Download the tested EL9 RPM + uses: https://gitea.psi.ch/actions/download-artifact@ad191675b41f6a5b46da9a048cb6893812da158b # v3.1.0-node20 + with: + name: elog-el9 + path: dist/el9 + - name: Verify artifacts + run: cd dist/el9 && sha256sum --check SHA256SUMS + - name: Derive image version + id: metadata + env: + BUILD_REF: ${{ github.ref }} + run: bash .gitea/scripts/metadata.sh + - name: Build runtime image from the tested RPM + env: + VERSION: ${{ steps.metadata.outputs.version }} + REVISION: ${{ steps.metadata.outputs.revision }} + run: | + docker build --platform linux/amd64 \ + --build-arg "VERSION=$VERSION" --build-arg "REVISION=$REVISION" \ + --tag "elog-ci:$GITHUB_RUN_ID" . + bash .gitea/scripts/smoke-container.sh "elog-ci:$GITHUB_RUN_ID" + - name: Publish snapshots or versioned release image + # PRs, feature branches and manual runs never receive the registry token. + if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')) + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + IMAGE_TAG: ${{ steps.metadata.outputs.image_tag }} + BUILD_REF: ${{ github.ref }} + run: | + set -euo pipefail + : "${REGISTRY_USERNAME:?Set REGISTRY_USERNAME to the package token owner}" + : "${REGISTRY_TOKEN:?Set REGISTRY_TOKEN with write:package access to images/elog}" + export DOCKER_CONFIG + DOCKER_CONFIG=$(mktemp -d) + trap 'rm -rf "$DOCKER_CONFIG"' EXIT + printf '%s' "$REGISTRY_TOKEN" | docker login gitea.psi.ch \ + --username "$REGISTRY_USERNAME" --password-stdin + docker tag "elog-ci:$GITHUB_RUN_ID" "$CONTAINER_IMAGE:$IMAGE_TAG" + docker push "$CONTAINER_IMAGE:$IMAGE_TAG" + docker image rm "$CONTAINER_IMAGE:$IMAGE_TAG" + if [[ "$BUILD_REF" == refs/tags/* ]]; then + # Deliberately leave latest promotion to the release operator. + echo "Release image published as $CONTAINER_IMAGE:$IMAGE_TAG" + else + docker tag "elog-ci:$GITHUB_RUN_ID" "$CONTAINER_IMAGE:edge" + docker push "$CONTAINER_IMAGE:edge" + docker image rm "$CONTAINER_IMAGE:edge" + fi + - name: Remove local CI image + if: always() + run: docker image rm "elog-ci:$GITHUB_RUN_ID" || true diff --git a/.gitignore b/.gitignore index 33c6a615..c612a630 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ cmake-build-debug cmake-build-release build xcode +dist/ diff --git a/Dockerfile b/Dockerfile index 8d49e21f..a10e4c8e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,20 @@ -FROM gcc:latest -RUN apt-get -qq update && apt-get -y -qq install cmake && apt-get -y -qq install emacs -RUN git clone --quiet https://ritt@bitbucket.org/ritt/elog.git -WORKDIR /elog -RUN git submodule update --init -RUN mkdir build && cd build && cmake .. && make -RUN ls -l build +ARG RUNTIME_IMAGE=gitea.psi.ch/images/rhel9:latest +FROM ${RUNTIME_IMAGE} + +ARG VERSION=unknown +ARG REVISION=unknown +LABEL org.opencontainers.image.title="ELOG" \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.revision="${REVISION}" + +# Install the RPM produced from this checkout, rather than the repository's latest. +COPY dist/el9/RPMS/*.rpm /tmp/elog-rpms/ +# Prefer libraries already present in the PSI base; resolve any missing ones online. +RUN (dnf install -y --disablerepo='*' /tmp/elog-rpms/*.rpm \ + || dnf install -y /tmp/elog-rpms/*.rpm) \ + && dnf clean all \ + && rm -rf /tmp/elog-rpms /var/cache/dnf + +COPY docker/krb5.conf /etc/krb5.conf +EXPOSE 8080 +CMD ["elogd", "-c", "/usr/local/elog/elogd.cfg"] diff --git a/Dockerfile.dockerignore b/Dockerfile.dockerignore new file mode 100644 index 00000000..eddb29bc --- /dev/null +++ b/Dockerfile.dockerignore @@ -0,0 +1,8 @@ +# The runtime image needs only the tested RPM and Kerberos configuration. +** +!dist/ +!dist/el9/ +!dist/el9/RPMS/ +!dist/el9/RPMS/*.rpm +!docker/ +!docker/krb5.conf diff --git a/README.md b/README.md index a1178358..29cb7be9 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,9 @@ Welcome to the ELOG package This is ELOG, an electronic logbook. +Builds and container images are managed here with Gitea Actions. See +[CI, container usage and release recommendations](doc/ci-and-releases.md). + For the full documentation please visit: https://elog.psi.ch/elog Please send all bug reports and comments to [stefan.ritt@psi.ch](stefan.ritt@psi.ch) diff --git a/bitbucket-pipelines.yml b/bitbucket-pipelines.yml deleted file mode 100644 index 98b63e07..00000000 --- a/bitbucket-pipelines.yml +++ /dev/null @@ -1,99 +0,0 @@ -# ELOG Application - -# This template allows you to validate your C++ application. -# The workflow allows running tests and code linting on the default branch. - -image: gcc:latest - - -pipelines: - default: - - step: - name: Build run and test - image: gcc:latest - deployment: test - script: - # Execute your C++ application after compilation to check success - - apt-get -qq update && apt-get -y --force-yes -qq install cmake wget lsof - - git submodule update --init - # Add elog user - - groupadd -r elog - - useradd -d / -s /bin/false -g elog -M -r elog - # Build elog - - mkdir build; cd build - - cmake .. - - make - # Install in default /usr/local/elog - - echo "install in test environment" - - make install - # Start elogd - - echo "Start ELOG" - - /usr/local/sbin/elogd -v 3 -c /usr/local/elog/elogd.cfg 2>&1 & - - sleep 5 - - if [ -f /var/run/elogd.pid ]; then cat /var/run/elogd.pid ; fi - # Check open files - - lsof -p $(cat /var/run/elogd.pid) - # Test Web page - - echo "test web" - - sleep 3 - - wget http://localhost:8080 && true || false - - parallel: - steps: - - step: - name: Build on EL7 - image: mydumper/mydumper-builder-el7 - # trigger: manual # Uncomment to make this a manual deployment. - script: - - echo "Deploying to test environment" - - yum -y update && yum -y install rpm-build gcc gcc-c++ git openssl-devel krb5-devel pam-devel openldap-devel csh which - - git submodule update --init - # git clone https://bitbucket.org/ritt/elog --recursive - - ./buildrpm 3.1.5 $(date +%Y%m%d) -krb5 -ldap -pam -ssl - - mkdir RPMS - - find ~/rpmbuild/RPMS/ -name "*.rpm" -exec mv {} RPMS \; - - ls -l RPMS - artifacts: # defining the artifacts to be passed to each future step. - download: false # do not download artifacts in this step - paths: - - RPMS/*.rpm - - step: - name: Build on EL8 - image: lj020326/centos8-systemd - # trigger: manual # Uncomment to make this a manual deployment. - script: - - echo "Deploying to test environment" - - yum -y update && yum -y install rpm-build gcc gcc-c++ git openssl-devel krb5-devel pam-devel openldap-devel csh make cmake - - git submodule update --init - # git clone https://bitbucket.org/ritt/elog --recursive - - ./buildrpm 3.1.5 $(date +%Y%m%d) -krb5 -ldap -pam -ssl - - mkdir RPMS - - find ~/rpmbuild/RPMS/ -name "*.rpm" -exec mv {} RPMS \; - - ls -l RPMS - artifacts: # defining the artifacts to be passed to each future step. - download: false # do not download artifacts in this step - paths: - - RPMS/*.rpm - - step: - name: Build on EL9 - image: dokken/centos-stream-9 - # trigger: manual # Uncomment to make this a manual deployment. - script: - - echo "Deploying to test environment" - - yum -y update && yum -y install rpm-build gcc gcc-c++ git openssl-devel krb5-devel pam-devel openldap-devel csh - - git submodule update --init - # git clone https://bitbucket.org/ritt/elog --recursive - - ./buildrpm 3.1.5 $(date +%Y%m%d) -krb5 -ldap -pam -ssl - - mkdir RPMS - - find ~/rpmbuild/RPMS/ -name "*.rpm" -exec mv {} RPMS \; - - ls -l RPMS - artifacts: # defining the artifacts to be passed to each future step. - download: false # do not download artifacts in this step - paths: - - RPMS/*.rpm - - step: # non-parallel step - name: Deployement - deployment: staging - script: - - echo "Deliver results" - - ls -l RPMS - diff --git a/doc/ci-and-releases.md b/doc/ci-and-releases.md new file mode 100644 index 00000000..1b1d855d --- /dev/null +++ b/doc/ci-and-releases.md @@ -0,0 +1,146 @@ +# Gitea builds, containers and releases + +The source, RPM build and container definition now live in this repository. +`.gitea/workflows/build.yml` replaces `bitbucket-pipelines.yml` and the build +workflow from `images/elog`. The published container address stays +`gitea.psi.ch/images/elog` so deployments can keep their existing registry path. + +## Builds + +Every branch push, pull request and manual run builds x86_64 packages for EL8, +EL9 and EL10 using Rocky Linux build containers. Each build: + +1. Checks out the pinned `mxml` submodule. +2. Builds with CMake and checks the running daemon over HTTP. +3. Builds binary and source RPMs with SSL, Kerberos, LDAP and PAM enabled. +4. Installs the RPM and repeats the HTTP check. +5. Uploads an `elog-el8`, `elog-el9` or `elog-el10` artifact containing `RPMS`, `SRPMS`, + `SOURCES`, `build-info.txt` and `SHA256SUMS`. + +After all three builds pass, the container job downloads the tested EL9 artifact, +checks its SHA256 sums, builds the runtime image and checks its HTTP response. +The runtime installs that exact RPM; it does not install ELOG from a separately +maintained package repository. The existing PSI RHEL9 base and Kerberos settings +from `images/elog` are retained. + +The supported package targets are EL8, EL9 and EL10. The old EL7 builder is +removed from routine CI. + +| Trigger | RPM release | Published image tags | +| --- | --- | --- | +| Feature branch, pull request or manual run | `0..git` | None | +| Push to `master` | `0..git` | `sha-<12-character sha>`, `edge` | +| Push of `vX.Y.Z` matching the source version | `1` | `X.Y.Z` | + +The version comes from `src/elog-version.h`; it is no longer hard-coded in CI. +Snapshot RPM releases sort before release `1` of the same version. Tag names +that do not match the source version fail before building. Prerelease tags are +not implemented yet. `latest` is deliberately promoted separately, after a +release has been reviewed. + +## Gitea setup and cutover + +1. Enable Actions on this repository. Provide an `ubuntu-latest-intranet` runner + with Docker/BuildKit, an amd64 build environment, Bash, Git and Node 20/24. + It needs access to PSI Gitea, `gitea.psi.ch/images/rhel9`, `repos.psi.ch`, Docker + Hub and the Rocky package repositories. The runtime base must be readable by validation + jobs without the publishing token, including pull requests. +2. Set Actions secrets `REGISTRY_USERNAME` and `REGISTRY_TOKEN` here. The username + must be the account owning the token, and the token needs `write:package` + access plus permission to publish under the `images` organization. The source + repository owner (`ritt`) is not the package namespace (`images`). +3. Push the migration branch and inspect the RPM artifacts and the container + check before merging. The branch does not publish images. +4. Disable the old `images/elog` build workflow when cutting over; otherwise it + can still overwrite `latest` with its independently sourced RPM. Archive that + repository after the new workflow has passed on `master`. +5. Retire the Bitbucket pipeline after the Gitea build is confirmed. There is no + deployment step: publishing an image does not restart running services. + +Actions are fetched from verified PSI mirrors and pinned to commits. The artifact +actions use PSI's Node 20 variants of the v3 protocol; update upload and download +together when changing protocols. Registry credentials are provided only to the +publishing step on `master` and version tag pushes, using a temporary Docker +configuration. Gitea's automatic job token cannot publish container packages: +see the [Gitea compatibility documentation](https://docs.gitea.com/usage/actions/comparison/). + +## Suggested release process + +1. Protect `master` and `v*` tags in Gitea. Require all three package builds and the + container check before merging. Restrict release tag creation to maintainers. +2. Update `src/elog-version.h` and `doc/ChangeLog` in a reviewed change. Use patch + versions for compatible fixes, minor versions for compatible features and + major versions for breaking changes. +3. Create an annotated tag on the reviewed commit, for example `v3.1.6` for the + current header. Push the tag only when ready to build a release. The tag build + produces `elog-3.1.6-1.el8.x86_64.rpm`, its EL9/EL10 equivalents, source RPMs and + source archives, plus `gitea.psi.ch/images/elog:3.1.6`. +4. Create a draft Gitea Release for the tag. Attach the contents of all three CI + artifacts, keeping files for each EL version in separate directories/archives so + their checksum manifests remain usable. Include changes, upgrade notes and + the full image digest. Review it, then publish the release. CI artifacts expire + after 30 days, so release assets are the durable download location. +5. Promote the reviewed image to `latest`, then deploy by version or digest. + Keep `edge` for integration testing. Never move an existing version tag; + publish a new version when a released artifact must change. + +After releasing, bump the source version for the next development cycle so that +its snapshot RPMs sort after the previous stable version. + +For a registry login with publishing access, promotion can use: + +```sh +docker buildx imagetools create \ + --tag gitea.psi.ch/images/elog:latest \ + gitea.psi.ch/images/elog:3.1.6 +``` + +Automating draft release creation and asset attachment is a useful next step. +RPM signing and publishing to Gitea's RPM registry would also let native installs +consume tested releases directly; these require choosing a signing identity and +package repository policy. Rebuilding for base-image updates should have its own +revision/tag convention before it is automated, so a release tag continues to +identify a reviewed artifact. + +## Local validation + +Initialize the submodule, then build and export the same packages used in CI: + +```sh +git submodule update --init --recursive +docker build --platform linux/amd64 -f docker/Dockerfile.build \ + --build-arg EL_VERSION=9 \ + --build-arg "REVISION=$(git rev-parse HEAD)" \ + --build-arg "SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)" \ + --build-arg RPM_RELEASE=0.local \ + --output type=local,dest=dist/el9 . +docker build --platform linux/amd64 -t elog:local . +bash .gitea/scripts/smoke-container.sh elog:local +``` + +Use `EL_VERSION=8` and `dest=dist/el8`, or `EL_VERSION=10` and `dest=dist/el10`, +for the other package checks. EL10 requires an +[x86-64-v3 capable build host](https://docs.rockylinux.org/guides/minimum_hardware_requirements/). +If the PSI base +is unavailable, `--build-arg RUNTIME_IMAGE=rockylinux:9` allows local runtime +validation; production continues to use the PSI base. + +## Running the container + +Mount a valid configuration and persistent data. The default configuration and +demo logbook are installed with the RPM. For your own configuration, set logbook +directories beneath `/var/lib/elog`, or pass `-d /var/lib/elog` explicitly: + +```sh +docker run --rm -p 8080:8080 \ + -v "$PWD/elogd.cfg:/usr/local/elog/elogd.cfg:ro" \ + -v "$PWD/logbook-data:/var/lib/elog" \ + gitea.psi.ch/images/elog:3.1.6 \ + elogd -c /usr/local/elog/elogd.cfg -d /var/lib/elog +``` + +The data directory must be writable by the `elog` account in the container. +Existing installations using an AIT NFS share can keep that mount and their +configured logbook paths. Do not store logbook data only in the container layer. +For configuration examples see `elogd.cfg.example` and the +[ELOG configuration manual](https://elog.psi.ch/elog/config.html). diff --git a/docker/Dockerfile.build b/docker/Dockerfile.build new file mode 100644 index 00000000..46b9bed6 --- /dev/null +++ b/docker/Dockerfile.build @@ -0,0 +1,31 @@ +# syntax=docker/dockerfile:1 +ARG EL_VERSION=9 +FROM rockylinux:${EL_VERSION} AS build +ARG EL_VERSION +RUN dnf install -y dnf-plugins-core \ + && if [ "$EL_VERSION" = 8 ]; then \ + dnf config-manager --set-enabled powertools; \ + else \ + dnf config-manager --set-enabled crb; \ + fi \ + && dnf install -y --allowerasing rpm-build gcc gcc-c++ make cmake git which \ + openssl-devel krb5-devel pam-devel openldap-devel curl \ + && dnf clean all + +WORKDIR /src +COPY . . +ARG REVISION=unknown +ARG SOURCE_DATE_EPOCH=0 +ARG RPM_RELEASE=0.local +ENV ELOG_BUILD_REVISION=${REVISION} SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH} + +# Keep the old CMake build/start/HTTP check, as well as the full-feature RPM build. +RUN cmake -S . -B /tmp/elog-cmake -DCMAKE_BUILD_TYPE=Release \ + && cmake --build /tmp/elog-cmake --parallel 2 \ + && bash .gitea/scripts/smoke-server.sh /tmp/elog-cmake/elogd /src \ + && bash .gitea/scripts/build-rpm.sh "$RPM_RELEASE" /out \ + && dnf install -y --disablerepo='*' /out/RPMS/*.rpm \ + && bash .gitea/scripts/smoke-server.sh /usr/local/sbin/elogd /usr/local/elog + +FROM scratch AS packages +COPY --from=build /out/ / diff --git a/docker/krb5.conf b/docker/krb5.conf new file mode 100644 index 00000000..2f4e27ab --- /dev/null +++ b/docker/krb5.conf @@ -0,0 +1,21 @@ +[libdefaults] + default_realm = D.PSI.CH + dns_lookup_realm = false + ticket_lifetime = 10h + renew_lifetime = 30d + forwardable = true + rdns = false + udp_preference_limit = 10 + default_ccache_name = FILE:/tmp/krb5cc_%{uid} + +[realms] + D.PSI.CH = { + kdc = dc00.d.psi.ch + kdc = dc01.d.psi.ch + kdc = dc02.d.psi.ch + admin_server = dc00.d.psi.ch + } + +[domain_realm] + psi.ch = D.PSI.CH + .psi.ch = D.PSI.CH diff --git a/makegit b/makegit index 79056e58..c7353668 100755 --- a/makegit +++ b/makegit @@ -1 +1,7 @@ -echo \#define GIT_REVISION \"`git log -n 1 --pretty=format:'%ad - %h' --date=short`\" +#!/bin/sh +# Docker builds receive the revision without copying Git metadata/credentials. +revision=${ELOG_BUILD_REVISION:-} +if [ -z "$revision" ]; then + revision=$(git log -n 1 --pretty=format:'%ad - %h' --date=short 2>/dev/null) || revision=unknown +fi +printf '#define GIT_REVISION "%s"\n' "$revision" -- 2.54.1 From 5fda1c250ad18f1169973fff91766e59fe4e225b Mon Sep 17 00:00:00 2001 From: Basil Bruhn Date: Mon, 23 Nov 2026 17:11:43 +0100 Subject: [PATCH 2/4] Add Gitea releases and Windows builds --- .dockerignore | 1 + .gitea/scripts/build-rpm.sh | 2 +- .gitea/scripts/build-windows.ps1 | 67 +++++++++++ .gitea/scripts/metadata.sh | 3 - .gitea/scripts/release.py | 119 +++++++++++++++++++ .gitea/workflows/build.yml | 127 +++++++++++---------- .gitignore | 1 + CMakeLists.txt | 20 ++-- README.md | 2 +- doc/ci-and-releases.md | 189 +++++++++++++------------------ makegit.bat | 7 +- tests/test_release.py | 149 ++++++++++++++++++++++++ 12 files changed, 499 insertions(+), 188 deletions(-) create mode 100644 .gitea/scripts/build-windows.ps1 create mode 100644 .gitea/scripts/release.py create mode 100644 tests/test_release.py diff --git a/.dockerignore b/.dockerignore index 4a106afc..89c5e0e5 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,3 +16,4 @@ elconv src/git-revision.h src/git-revision.h.tmp elog.spec +**/__pycache__ diff --git a/.gitea/scripts/build-rpm.sh b/.gitea/scripts/build-rpm.sh index 8cf7ed3b..e987d5bd 100644 --- a/.gitea/scripts/build-rpm.sh +++ b/.gitea/scripts/build-rpm.sh @@ -25,7 +25,7 @@ mkdir -p "$source_dir" "$topdir"/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS} tar --exclude=.git --exclude=git-revision.h --exclude=git-revision.h.tmp -cf - \ src mxml doc man contrib scripts resources ssl themes logbooks cmake \ CMakeLists.txt Makefile COPYING README.md elogd.cfg.example \ - elogd.init_template elogd.service elogd.plist makegit \ + elogd.init_template elogd.service elogd.plist makegit makegit.bat \ | tar -xf - -C "$source_dir" cp README.md "$source_dir/README" # The existing RPM spec installs this name. printf '#define GIT_REVISION "%s"\n' "$revision" > "$source_dir/src/git-revision.h" diff --git a/.gitea/scripts/build-windows.ps1 b/.gitea/scripts/build-windows.ps1 new file mode 100644 index 00000000..08a368a6 --- /dev/null +++ b/.gitea/scripts/build-windows.ps1 @@ -0,0 +1,67 @@ +# Requires Visual Studio C++ Build Tools, CMake and a shared x64 OpenSSL SDK. +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $true +Set-Location "$PSScriptRoot/../.." + +if ($env:WINDOWS_OPENSSL_ROOT) { $env:OPENSSL_ROOT_DIR = $env:WINDOWS_OPENSSL_ROOT } +if (!(Test-Path "$env:OPENSSL_ROOT_DIR/include/openssl/ssl.h")) { + throw 'Set OPENSSL_ROOT_DIR to the shared x64 OpenSSL SDK on the runner.' +} +if ((Get-Content src/elog-version.h -Raw) -notmatch '#define VERSION "([0-9.]+)"') { + throw 'Cannot read the ELOG version.' +} +$version = $Matches[1] +if ($env:BUILD_REF -like 'refs/tags/*' -and $env:BUILD_REF -ne "refs/tags/v$version") { + throw "The release tag must match v$version." +} +$env:ELOG_BUILD_REVISION = (git rev-parse HEAD).Trim() + +cmake -S . -B build/windows -A x64 ` + "-DOPENSSL_ROOT_DIR=$env:OPENSSL_ROOT_DIR" -DOPENSSL_USE_STATIC_LIBS=OFF ` + -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded +cmake --build build/windows --config Release --parallel 2 + +$package = Join-Path $PWD 'dist/windows/elog' +if (Test-Path $package) { Remove-Item $package -Recurse -Force } +New-Item -ItemType Directory -Force $package | Out-Null +Copy-Item build/windows/Release/elog.exe, build/windows/Release/elogd.exe, build/windows/Release/elconv.exe $package +$dlls = @(Get-ChildItem "$env:OPENSSL_ROOT_DIR/bin/*.dll") +if (!$dlls.Count) { throw 'The OpenSSL SDK must provide its runtime DLLs in bin/.' } +$dlls | Copy-Item -Destination $package +# OpenSSL DLLs may need the Visual C++ runtime even though ELOG uses /MT. +$vswhere = "${env:ProgramFiles(x86)}/Microsoft Visual Studio/Installer/vswhere.exe" +$visualStudio = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$crt = Get-ChildItem "$visualStudio/VC/Redist/MSVC/*/x64/Microsoft.VC*.CRT" -Directory | + Sort-Object FullName -Descending | Select-Object -First 1 +if (!$crt) { throw 'Install the Visual C++ redistributable files on the build runner.' } +Copy-Item "$($crt.FullName)/*.dll" $package +Copy-Item scripts, resources, themes, ssl, logbooks -Destination $package -Recurse -Force +Copy-Item COPYING, README.md -Destination $package +Copy-Item elogd.cfg.example "$package/elogd.cfg" + +# Test the files we will ship, including the OpenSSL DLLs. +$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) +$listener.Start() +$port = $listener.LocalEndpoint.Port +$listener.Stop() +$server = Start-Process "$package/elogd.exe" -PassThru -NoNewWindow -ArgumentList ` + "-c `"$package/elogd.cfg`" -s `"$package`" -d `"$package/logbooks`" -n 127.0.0.1 -p $port" +try { + $ready = $false + for ($attempt = 0; $attempt -lt 30; $attempt++) { + if ($server.HasExited) { throw 'elogd exited before the HTTP check.' } + try { + $page = Invoke-WebRequest "http://127.0.0.1:$port/demo/" -TimeoutSec 2 -NoProxy + if ($page.StatusCode -eq 200 -and $page.Content -match 'ELOG') { $ready = $true; break } + } catch { Start-Sleep -Seconds 1 } + } + if (!$ready) { throw 'Windows HTTP smoke check failed.' } +} finally { + Stop-Process -Id $server.Id -ErrorAction SilentlyContinue +} + +$archive = "dist/windows/elog-$version-windows-x64.zip" +Compress-Archive "$package/*" $archive -Force +Remove-Item $package -Recurse -Force +$hash = (Get-FileHash $archive -Algorithm SHA256).Hash.ToLowerInvariant() +Set-Content dist/windows/SHA256SUMS "$hash $(Split-Path $archive -Leaf)`n" -NoNewline diff --git a/.gitea/scripts/metadata.sh b/.gitea/scripts/metadata.sh index 584931be..6de66fda 100644 --- a/.gitea/scripts/metadata.sh +++ b/.gitea/scripts/metadata.sh @@ -17,10 +17,8 @@ if [[ "$ref" == refs/tags/* ]]; then exit 1 } release=1 - image_tag=$version else release="0.$timestamp.git$short_revision" - image_tag="sha-$short_revision" fi if [[ -n "${GITHUB_OUTPUT:-}" ]]; then @@ -31,5 +29,4 @@ fi printf 'revision=%s\n' "$revision" printf 'source_date_epoch=%s\n' "$epoch" printf 'rpm_release=%s\n' "$release" - printf 'image_tag=%s\n' "$image_tag" } diff --git a/.gitea/scripts/release.py b/.gitea/scripts/release.py new file mode 100644 index 00000000..55e1a51a --- /dev/null +++ b/.gitea/scripts/release.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Publish the tested artifacts for a version tag; leave release notes in a draft.""" +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +from urllib.error import HTTPError +from urllib.parse import quote, urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + + +class AssetRedirect(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + redirected = super().redirect_request(req, fp, code, msg, headers, newurl) + if urlsplit(req.full_url).netloc != urlsplit(newurl).netloc: + redirected.remove_header("Authorization") + return redirected + + +def request(url, token, method="GET", data=None, content_type="application/json"): + headers = {"Authorization": f"token {token}", "Content-Type": content_type} + with build_opener(AssetRedirect).open(Request(url, data=data, headers=headers, method=method), timeout=120) as response: + return response.read() + + +def verify_artifacts(directory): + for target in ("el8", "el9", "el10", "windows"): + root = directory / target + for line in (root / "SHA256SUMS").read_text().splitlines(): + expected, name = line.split(maxsplit=1) + file = root / name + if not file.resolve().is_relative_to(root.resolve()): + raise ValueError(f"Invalid checksum path: {name}") + if hashlib.sha256(file.read_bytes()).hexdigest() != expected: + raise ValueError(f"Checksum mismatch: {file}") + + +def publish(directory, local_image): + verify_artifacts(directory) + server = os.environ["SERVER_URL"].rstrip("/") + repository = os.environ["REPOSITORY"] + owner = repository.split("/")[0] + version = os.environ["VERSION"] + token = os.environ["PUBLISH_TOKEN"] + api = f"{server}/api/v1" + releases = f"{api}/repos/{repository}/releases" + tag = f"v{version}" + notes = Path("doc/ChangeLog").read_text().split("\nVersion ", 1)[0] + if not notes.startswith(f"Version {version},"): + raise ValueError(f"Update doc/ChangeLog for version {version} before releasing") + + # A failed run may resume a draft. Published releases are never changed. + try: + release = json.loads(request(f"{releases}/tags/{quote(tag)}", token)) + except HTTPError as error: + if error.code != 404: + raise + error.close() + body = {"tag_name": tag, "name": f"ELOG {version}", "draft": True, "body": notes} + release = json.loads(request(releases, token, "POST", json.dumps(body).encode())) + if not release["draft"]: + raise ValueError(f"{tag} is already published; create a new version instead") + + registry = server.split("://", 1)[1] + image = f"{registry}/{repository.lower()}:{version}" + with tempfile.TemporaryDirectory(prefix="elog-docker-") as config: + env = {**os.environ, "DOCKER_CONFIG": config} + subprocess.run(["docker", "login", registry, "--username", os.environ["PUBLISH_USER"], + "--password-stdin"], input=token, text=True, env=env, check=True) + subprocess.run(["docker", "tag", local_image, image], env=env, check=True) + subprocess.run(["docker", "push", image], env=env, check=True) + digest = subprocess.check_output(["docker", "inspect", "--format", "{{index .RepoDigests 0}}", image], env=env) + (directory / "image.txt").write_bytes(digest) + subprocess.run(["docker", "image", "rm", image], env=env, check=True) + + rpms = sorted(directory.glob("el*/RPMS/*.rpm")) + sorted(directory.glob("el*/SRPMS/*.rpm")) + files = rpms + sorted((directory / "el9/SOURCES").glob("*.tar.gz")) + files += sorted((directory / "windows").glob("*.zip")) + [directory / "image.txt"] + checksums = directory / "SHA256SUMS" + checksums.write_text("".join(f"{hashlib.sha256(f.read_bytes()).hexdigest()} {f.name}\n" for f in files)) + assets_url = f"{releases}/{release['id']}/assets" + existing = {asset["name"]: asset for asset in json.loads(request(assets_url, token))} + + for file in files + [checksums]: + data = file.read_bytes() + if file.name in existing: + # Fail on different bytes rather than silently replacing a release asset. + url = existing[file.name]["browser_download_url"] + if not url.startswith(server + "/") or request(url, token) != data: + raise ValueError(f"Existing release asset differs: {file.name}") + continue + boundary = "elog-release-attachment" + body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; ' + f'filename="{file.name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode() + body += data + f"\r\n--{boundary}--\r\n".encode() + request(assets_url, token, "POST", body, f"multipart/form-data; boundary={boundary}") + + for file in rpms: + group = file.relative_to(directory).parts[0] # el8, el9 or el10 + url = f"{server}/api/packages/{quote(owner)}/rpm/{group}/upload" + try: + request(url, token, "PUT", file.read_bytes(), "application/octet-stream") + except HTTPError as error: + if error.code != 409: + raise + error.close() + package_version = re.fullmatch(r"elog-(.+)\.[^.]+\.rpm", file.name)[1] + published = json.loads(request(f"{api}/packages/{quote(owner)}/rpm/elog/{package_version}/files", token)) + if not any(item["sha256"] == hashlib.sha256(file.read_bytes()).hexdigest() for item in published): + raise ValueError(f"Existing registry RPM differs: {file.name}") from error + print(f"Review and publish the draft: {release['html_url']}") + + +if __name__ == "__main__": + publish(Path(sys.argv[1]), sys.argv[2]) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index bcd17724..6a91186d 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -1,4 +1,4 @@ -name: Build, test and package ELOG +name: Build and release ELOG on: push: @@ -7,35 +7,33 @@ on: pull_request: workflow_dispatch: -env: - # Keep the image address used by deployments from the former images/elog repo. - CONTAINER_IMAGE: gitea.psi.ch/images/elog - jobs: - packages: - name: Build and test EL${{ matrix.el }} + linux: + name: EL${{ matrix.el }} runs-on: ubuntu-latest-intranet strategy: fail-fast: false matrix: el: [8, 9, 10] steps: - - name: Checkout source and mxml - uses: https://gitea.psi.ch/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: https://gitea.psi.ch/actions/checkout@v7 with: submodules: recursive persist-credentials: false - - name: Derive version and validate release tag - id: metadata + - name: Test release publishing against a local API + if: matrix.el == 9 + run: python3 -m unittest discover -s tests -p test_release.py + - name: Read version + id: version env: BUILD_REF: ${{ github.ref }} run: bash .gitea/scripts/metadata.sh - - name: Build, HTTP-test and export packages + - name: Build and test RPMs env: EL_VERSION: ${{ matrix.el }} - REVISION: ${{ steps.metadata.outputs.revision }} - RPM_RELEASE: ${{ steps.metadata.outputs.rpm_release }} - SOURCE_DATE_EPOCH: ${{ steps.metadata.outputs.source_date_epoch }} + REVISION: ${{ steps.version.outputs.revision }} + RPM_RELEASE: ${{ steps.version.outputs.rpm_release }} + SOURCE_DATE_EPOCH: ${{ steps.version.outputs.source_date_epoch }} run: | docker build --platform linux/amd64 --file docker/Dockerfile.build \ --build-arg "EL_VERSION=$EL_VERSION" \ @@ -43,73 +41,78 @@ jobs: --build-arg "RPM_RELEASE=$RPM_RELEASE" \ --build-arg "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH" \ --output "type=local,dest=dist/el$EL_VERSION" . - - name: Store RPMs, source archive and checksums - # PSI's Node 20 build of the Gitea-compatible v3 artifact protocol. - uses: https://gitea.psi.ch/actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 + # These PSI v3 artifact actions use Node 24. + - uses: https://gitea.psi.ch/actions/upload-artifact@v3.2.2 with: - name: elog-el${{ matrix.el }} + name: el${{ matrix.el }} path: dist/el${{ matrix.el }}/ if-no-files-found: error retention-days: 30 - container: - name: Build and test EL9 container - needs: packages + windows: + name: Windows x64 + runs-on: ${{ vars.WINDOWS_RUNNER || 'windows-latest' }} + steps: + - uses: https://gitea.psi.ch/actions/checkout@v7 + with: + submodules: recursive + persist-credentials: false + - name: Build, test and zip Windows binaries + shell: pwsh + env: + BUILD_REF: ${{ github.ref }} + WINDOWS_OPENSSL_ROOT: ${{ vars.WINDOWS_OPENSSL_ROOT }} + run: ./.gitea/scripts/build-windows.ps1 + - uses: https://gitea.psi.ch/actions/upload-artifact@v3.2.2 + with: + name: windows + path: dist/windows/ + if-no-files-found: error + retention-days: 30 + + release: + name: Container and release + needs: [linux, windows] runs-on: ubuntu-latest-intranet steps: - - name: Checkout - uses: https://gitea.psi.ch/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: https://gitea.psi.ch/actions/checkout@v7 with: persist-credentials: false - - name: Download the tested EL9 RPM - uses: https://gitea.psi.ch/actions/download-artifact@ad191675b41f6a5b46da9a048cb6893812da158b # v3.1.0-node20 + - uses: https://gitea.psi.ch/actions/download-artifact@v3.1.0 with: - name: elog-el9 - path: dist/el9 - - name: Verify artifacts - run: cd dist/el9 && sha256sum --check SHA256SUMS - - name: Derive image version - id: metadata + path: dist + - name: Check downloads + run: | + for target in el8 el9 el10 windows; do + (cd "dist/$target" && sha256sum --check SHA256SUMS) + done + - name: Read version + id: version env: BUILD_REF: ${{ github.ref }} run: bash .gitea/scripts/metadata.sh - - name: Build runtime image from the tested RPM + - name: Build and test the container env: - VERSION: ${{ steps.metadata.outputs.version }} - REVISION: ${{ steps.metadata.outputs.revision }} + VERSION: ${{ steps.version.outputs.version }} + REVISION: ${{ steps.version.outputs.revision }} run: | docker build --platform linux/amd64 \ --build-arg "VERSION=$VERSION" --build-arg "REVISION=$REVISION" \ --tag "elog-ci:$GITHUB_RUN_ID" . bash .gitea/scripts/smoke-container.sh "elog-ci:$GITHUB_RUN_ID" - - name: Publish snapshots or versioned release image - # PRs, feature branches and manual runs never receive the registry token. - if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')) + # A matching version tag is the only publishing trigger. + - name: Publish versioned image, RPMs and release draft + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') env: - REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} - REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} - IMAGE_TAG: ${{ steps.metadata.outputs.image_tag }} - BUILD_REF: ${{ github.ref }} + VERSION: ${{ steps.version.outputs.version }} + SERVER_URL: ${{ github.server_url }} + REPOSITORY: ${{ github.repository }} + PUBLISH_USER: ${{ secrets.PUBLISH_USER }} + PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }} run: | - set -euo pipefail - : "${REGISTRY_USERNAME:?Set REGISTRY_USERNAME to the package token owner}" - : "${REGISTRY_TOKEN:?Set REGISTRY_TOKEN with write:package access to images/elog}" - export DOCKER_CONFIG - DOCKER_CONFIG=$(mktemp -d) - trap 'rm -rf "$DOCKER_CONFIG"' EXIT - printf '%s' "$REGISTRY_TOKEN" | docker login gitea.psi.ch \ - --username "$REGISTRY_USERNAME" --password-stdin - docker tag "elog-ci:$GITHUB_RUN_ID" "$CONTAINER_IMAGE:$IMAGE_TAG" - docker push "$CONTAINER_IMAGE:$IMAGE_TAG" - docker image rm "$CONTAINER_IMAGE:$IMAGE_TAG" - if [[ "$BUILD_REF" == refs/tags/* ]]; then - # Deliberately leave latest promotion to the release operator. - echo "Release image published as $CONTAINER_IMAGE:$IMAGE_TAG" - else - docker tag "elog-ci:$GITHUB_RUN_ID" "$CONTAINER_IMAGE:edge" - docker push "$CONTAINER_IMAGE:edge" - docker image rm "$CONTAINER_IMAGE:edge" - fi - - name: Remove local CI image + : "${PUBLISH_USER:?Set PUBLISH_USER and PUBLISH_TOKEN}" + : "${PUBLISH_TOKEN:?Token needs package and repository write access}" + python3 .gitea/scripts/release.py dist "elog-ci:$GITHUB_RUN_ID" + - name: Clean up local image if: always() run: docker image rm "elog-ci:$GITHUB_RUN_ID" || true diff --git a/.gitignore b/.gitignore index c612a630..1f8659b7 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,4 @@ cmake-build-release build xcode dist/ +__pycache__/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 8ff39474..59dfd624 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ # CMakeLists.txt for ELOG project -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.15) project(ELOG) # C++ version @@ -40,7 +40,11 @@ find_package(Git) set(GIT_REVISION ${CMAKE_SOURCE_DIR}/src/git-revision.h) # disable warnings for regex.c -set_source_files_properties(${CMAKE_SOURCE_DIR}/src/regex.c PROPERTIES COMPILE_FLAGS -w) +if (MSVC) + set_source_files_properties(${CMAKE_SOURCE_DIR}/src/regex.c PROPERTIES COMPILE_FLAGS /w) +else() + set_source_files_properties(${CMAKE_SOURCE_DIR}/src/regex.c PROPERTIES COMPILE_FLAGS -w) +endif() # Package finders list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake) @@ -99,18 +103,14 @@ add_executable(elogd ${CMAKE_SOURCE_DIR}/src/crypt.cxx ) -if (WIN32) -target_sources(elog PRIVATE - ${CMAKE_SOURCE_DIR}/src/regex.c -) -endif() - add_executable(elog ${CMAKE_SOURCE_DIR}/src/elog.cxx ${CMAKE_SOURCE_DIR}/src/crypt.cxx ${CMAKE_SOURCE_DIR}/src/strlcpy.cxx ) +add_executable(elconv ${CMAKE_SOURCE_DIR}/src/elconv.cxx) + add_dependencies(elogd git_revision_h) add_dependencies(elog git_revision_h) @@ -129,7 +129,9 @@ if(USE_PAM) endif(USE_PAM) if (WIN32) - target_link_libraries(elogd wsock32 ws2_32) + target_sources(elogd PRIVATE ${CMAKE_SOURCE_DIR}/src/regex.c) + target_include_directories(elogd PRIVATE ${CMAKE_SOURCE_DIR}/src) + target_link_libraries(elogd wsock32 ws2_32 shlwapi advapi32) target_link_libraries(elog wsock32 ws2_32) endif() diff --git a/README.md b/README.md index 29cb7be9..50a07df5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Welcome to the ELOG package This is ELOG, an electronic logbook. Builds and container images are managed here with Gitea Actions. See -[CI, container usage and release recommendations](doc/ci-and-releases.md). +[CI, container usage and releases](doc/ci-and-releases.md). For the full documentation please visit: https://elog.psi.ch/elog diff --git a/doc/ci-and-releases.md b/doc/ci-and-releases.md index 1b1d855d..3415a712 100644 --- a/doc/ci-and-releases.md +++ b/doc/ci-and-releases.md @@ -1,146 +1,113 @@ -# Gitea builds, containers and releases +# Builds and releases -The source, RPM build and container definition now live in this repository. -`.gitea/workflows/build.yml` replaces `bitbucket-pipelines.yml` and the build -workflow from `images/elog`. The published container address stays -`gitea.psi.ch/images/elog` so deployments can keep their existing registry path. +Everything is built by `.gitea/workflows/build.yml`: -## Builds +- EL8, EL9 and EL10: binary RPM, source RPM, source archive and checksums. +- Windows x64: a portable ZIP with `elogd`, `elog`, `elconv`, OpenSSL and VC runtime DLLs, + configuration, resources and the demo logbook. +- Container: the tested EL9 RPM installed in the existing PSI RHEL9 base. -Every branch push, pull request and manual run builds x86_64 packages for EL8, -EL9 and EL10 using Rocky Linux build containers. Each build: +Every build starts ELOG and checks its HTTP response. Branches, pull requests and +manual runs validate the build and retain downloads for 30 days. **Only version +tag pushes publish packages or create release drafts.** -1. Checks out the pinned `mxml` submodule. -2. Builds with CMake and checks the running daemon over HTTP. -3. Builds binary and source RPMs with SSL, Kerberos, LDAP and PAM enabled. -4. Installs the RPM and repeats the HTTP check. -5. Uploads an `elog-el8`, `elog-el9` or `elog-el10` artifact containing `RPMS`, `SRPMS`, - `SOURCES`, `build-info.txt` and `SHA256SUMS`. +## Make a release -After all three builds pass, the container job downloads the tested EL9 artifact, -checks its SHA256 sums, builds the runtime image and checks its HTTP response. -The runtime installs that exact RPM; it does not install ELOG from a separately -maintained package repository. The existing PSI RHEL9 base and Kerberos settings -from `images/elog` are retained. +1. Update `src/elog-version.h` and the first version section in `doc/ChangeLog`. + Use patch versions for fixes, minor versions for compatible features and major + versions for breaking changes. +2. Tag the reviewed commit with the matching version and push it: -The supported package targets are EL8, EL9 and EL10. The old EL7 builder is -removed from routine CI. + ```sh + git tag -a v3.1.6 -m "ELOG 3.1.6" + git push origin v3.1.6 + ``` -| Trigger | RPM release | Published image tags | -| --- | --- | --- | -| Feature branch, pull request or manual run | `0..git` | None | -| Push to `master` | `0..git` | `sha-<12-character sha>`, `edge` | -| Push of `vX.Y.Z` matching the source version | `1` | `X.Y.Z` | +3. After all Linux and Windows checks pass, CI publishes the versioned container + and RPMs, and creates a **draft Gitea Release**. The draft contains the Windows + ZIP, RPMs, source RPMs, a source archive including `mxml`, checksums, the image + digest and notes from `doc/ChangeLog`. Review the notes and publish the draft. -The version comes from `src/elog-version.h`; it is no longer hard-coded in CI. -Snapshot RPM releases sort before release `1` of the same version. Tag names -that do not match the source version fail before building. Prerelease tags are -not implemented yet. `latest` is deliberately promoted separately, after a -release has been reviewed. +The tag must match the source version exactly. Prerelease tags are not supported. +Protect `v*` tags and never move a released tag. After releasing, bump the source +version for the next development cycle. Snapshot RPMs use release +`0..git`; tagged RPMs use release `1`. -## Gitea setup and cutover +Published releases are never edited by CI. A failed publishing job can resume a +draft when its artifacts are identical; conflicting files fail instead of being +replaced. Rerun the failed publishing job using the original build artifacts. -1. Enable Actions on this repository. Provide an `ubuntu-latest-intranet` runner - with Docker/BuildKit, an amd64 build environment, Bash, Git and Node 20/24. - It needs access to PSI Gitea, `gitea.psi.ch/images/rhel9`, `repos.psi.ch`, Docker - Hub and the Rocky package repositories. The runtime base must be readable by validation - jobs without the publishing token, including pull requests. -2. Set Actions secrets `REGISTRY_USERNAME` and `REGISTRY_TOKEN` here. The username - must be the account owning the token, and the token needs `write:package` - access plus permission to publish under the `images` organization. The source - repository owner (`ritt`) is not the package namespace (`images`). -3. Push the migration branch and inspect the RPM artifacts and the container - check before merging. The branch does not publish images. -4. Disable the old `images/elog` build workflow when cutting over; otherwise it - can still overwrite `latest` with its independently sourced RPM. Archive that - repository after the new workflow has passed on `master`. -5. Retire the Bitbucket pipeline after the Gitea build is confirmed. There is no - deployment step: publishing an image does not restart running services. - -Actions are fetched from verified PSI mirrors and pinned to commits. The artifact -actions use PSI's Node 20 variants of the v3 protocol; update upload and download -together when changing protocols. Registry credentials are provided only to the -publishing step on `master` and version tag pushes, using a temporary Docker -configuration. Gitea's automatic job token cannot publish container packages: -see the [Gitea compatibility documentation](https://docs.gitea.com/usage/actions/comparison/). - -## Suggested release process - -1. Protect `master` and `v*` tags in Gitea. Require all three package builds and the - container check before merging. Restrict release tag creation to maintainers. -2. Update `src/elog-version.h` and `doc/ChangeLog` in a reviewed change. Use patch - versions for compatible fixes, minor versions for compatible features and - major versions for breaking changes. -3. Create an annotated tag on the reviewed commit, for example `v3.1.6` for the - current header. Push the tag only when ready to build a release. The tag build - produces `elog-3.1.6-1.el8.x86_64.rpm`, its EL9/EL10 equivalents, source RPMs and - source archives, plus `gitea.psi.ch/images/elog:3.1.6`. -4. Create a draft Gitea Release for the tag. Attach the contents of all three CI - artifacts, keeping files for each EL version in separate directories/archives so - their checksum manifests remain usable. Include changes, upgrade notes and - the full image digest. Review it, then publish the release. CI artifacts expire - after 30 days, so release assets are the durable download location. -5. Promote the reviewed image to `latest`, then deploy by version or digest. - Keep `edge` for integration testing. Never move an existing version tag; - publish a new version when a released artifact must change. - -After releasing, bump the source version for the next development cycle so that -its snapshot RPMs sort after the previous stable version. - -For a registry login with publishing access, promotion can use: +`latest` is optional and stays a deliberate promotion of a reviewed release: ```sh +organization=your-org docker buildx imagetools create \ - --tag gitea.psi.ch/images/elog:latest \ - gitea.psi.ch/images/elog:3.1.6 + --tag "gitea.psi.ch/$organization/elog:latest" \ + "gitea.psi.ch/$organization/elog:3.1.6" ``` -Automating draft release creation and asset attachment is a useful next step. -RPM signing and publishing to Gitea's RPM registry would also let native installs -consume tested releases directly; these require choosing a signing identity and -package repository policy. Rebuilding for base-image updates should have its own -revision/tag convention before it is automated, so a release tag continues to -identify a reviewed artifact. +## Gitea setup -## Local validation +The publishing paths follow the repository automatically. For `my-org/elog`: -Initialize the submodule, then build and export the same packages used in CI: +- Image: `gitea.psi.ch/my-org/elog:3.1.6`. +- RPM repositories: `https://gitea.psi.ch/api/packages/my-org/rpm/el9.repo` + (use `el8` or `el10` for the other targets). +- Release downloads: the repository's Releases tab. + +Moving the repository to its own organization therefore needs no path changes. +Give the publishing account access to that organization and set these secrets: + +| Secret | Value | +| --- | --- | +| `PUBLISH_USER` | The Gitea account owning the token. | +| `PUBLISH_TOKEN` | A token with `write:package` and `write:repository` access. | + +Runners need: + +- `ubuntu-latest-intranet`: Docker/BuildKit, Git, Bash, Python 3.9+ and Node 24. + It must reach PSI Gitea, `repos.psi.ch`, Docker Hub and Rocky's package mirrors. + EL10 needs an [x86-64-v3 capable host](https://docs.rockylinux.org/guides/minimum_hardware_requirements/). +- Windows: Node 24, Git, PowerShell 7.3+, CMake 3.15+ and Visual Studio C++ Build + Tools with the Windows SDK and C++ redistributable files. Set the Actions variable `WINDOWS_RUNNER` to its + label; the default is `windows-latest`. Set `WINDOWS_OPENSSL_ROOT` to a shared + x64 OpenSSL SDK with headers, import libraries and DLLs in `bin`. An existing + runner environment variable `OPENSSL_ROOT_DIR` also works. + +The workflow uses readable version tags from PSI's action mirrors. Upload +`v3.2.2` and download `v3.1.0` use Node 24 and the compatible v3 artifact protocol; +the protocol version and Node runtime are separate choices. See the +[PSI upload action](https://gitea.psi.ch/actions/upload-artifact/src/tag/v3.2.2/action.yml). + +At cutover, disable the old `images/elog` workflow. Existing deployments keep +using their current image until you update them to the new organization's path. +Publishing packages does not restart running services. + +## Local builds and containers ```sh git submodule update --init --recursive docker build --platform linux/amd64 -f docker/Dockerfile.build \ - --build-arg EL_VERSION=9 \ + --build-arg EL_VERSION=9 --build-arg RPM_RELEASE=0.local \ --build-arg "REVISION=$(git rev-parse HEAD)" \ --build-arg "SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)" \ - --build-arg RPM_RELEASE=0.local \ --output type=local,dest=dist/el9 . docker build --platform linux/amd64 -t elog:local . bash .gitea/scripts/smoke-container.sh elog:local ``` -Use `EL_VERSION=8` and `dest=dist/el8`, or `EL_VERSION=10` and `dest=dist/el10`, -for the other package checks. EL10 requires an -[x86-64-v3 capable build host](https://docs.rockylinux.org/guides/minimum_hardware_requirements/). -If the PSI base -is unavailable, `--build-arg RUNTIME_IMAGE=rockylinux:9` allows local runtime -validation; production continues to use the PSI base. - -## Running the container - -Mount a valid configuration and persistent data. The default configuration and -demo logbook are installed with the RPM. For your own configuration, set logbook -directories beneath `/var/lib/elog`, or pass `-d /var/lib/elog` explicitly: +Use `EL_VERSION=8`/`dest=dist/el8` or `EL_VERSION=10`/`dest=dist/el10` for the +other packages. On Windows, run `.gitea/scripts/build-windows.ps1` from PowerShell. +The default container ships a demo logbook. For persistent data and your own +configuration: ```sh docker run --rm -p 8080:8080 \ -v "$PWD/elogd.cfg:/usr/local/elog/elogd.cfg:ro" \ -v "$PWD/logbook-data:/var/lib/elog" \ - gitea.psi.ch/images/elog:3.1.6 \ - elogd -c /usr/local/elog/elogd.cfg -d /var/lib/elog + elog:local elogd -c /usr/local/elog/elogd.cfg -d /var/lib/elog ``` -The data directory must be writable by the `elog` account in the container. -Existing installations using an AIT NFS share can keep that mount and their -configured logbook paths. Do not store logbook data only in the container layer. -For configuration examples see `elogd.cfg.example` and the -[ELOG configuration manual](https://elog.psi.ch/elog/config.html). +Make the data directory writable by the container's `elog` account. Existing NFS +mounts can keep their configured paths. See `elogd.cfg.example` and the +[configuration manual](https://elog.psi.ch/elog/config.html). diff --git a/makegit.bat b/makegit.bat index 8e0c995f..5c196dcf 100644 --- a/makegit.bat +++ b/makegit.bat @@ -1 +1,6 @@ -/cygwin64/bin/sh -c /cygdrive/c/Users/ritt/Documents/elog/makegit > c:\Users\ritt\Documents\elog\src\git-revision.h.tmp +@echo off +setlocal +set "REVISION=%ELOG_BUILD_REVISION%" +if not defined REVISION for /f %%i in ('git rev-parse --short HEAD') do set "REVISION=%%i" +if not defined REVISION set "REVISION=unknown" +>"%~dp0src\git-revision.h.tmp" echo #define GIT_REVISION "%REVISION%" diff --git a/tests/test_release.py b/tests/test_release.py new file mode 100644 index 00000000..9410acfb --- /dev/null +++ b/tests/test_release.py @@ -0,0 +1,149 @@ +"""Exercise publishing against a local Gitea API stand-in; Docker is mocked.""" +import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import threading +import unittest +from unittest.mock import patch +from email.parser import BytesParser +from email.policy import default + +spec = importlib.util.spec_from_file_location("release", Path(__file__).parents[1] / ".gitea/scripts/release.py") +release = importlib.util.module_from_spec(spec) +spec.loader.exec_module(release) + + +class ReleaseTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.directory = Path(self.temp.name) + previous_directory = Path.cwd() + self.addCleanup(os.chdir, previous_directory) + os.chdir(self.directory) + (self.directory / "doc").mkdir() + (self.directory / "doc/ChangeLog").write_text("Version 3.1.6, released for this test\n- Fixture release notes\n") + for target in ("el8", "el9", "el10", "windows"): + root = self.directory / target + names = ([f"RPMS/elog-3.1.6-1.{target}.x86_64.rpm", f"SRPMS/elog-3.1.6-1.{target}.src.rpm"] + if target != "windows" else ["elog-3.1.6-windows-x64.zip"]) + if target == "el9": + names.append("SOURCES/elog-3.1.6-1.tar.gz") + for name in names: + file = root / name + file.parent.mkdir(parents=True, exist_ok=True) + file.write_bytes(name.encode()) + (root / "SHA256SUMS").write_text("".join( + f"{hashlib.sha256((root / name).read_bytes()).hexdigest()} {name}\n" for name in names)) + self.draft = None + self.assets = {} + self.rpms = {} + self.writes = 0 + test = self + + class Handler(BaseHTTPRequestHandler): + def parse_request(self): + valid = super().parse_request() + if valid: + test.assertEqual(self.headers.get("Authorization"), "token test-token") + return valid + + def log_message(self, *args): + pass + + def reply(self, code, data): + self.send_response(code) + self.end_headers() + self.wfile.write(data if isinstance(data, bytes) else json.dumps(data).encode()) + + def do_GET(self): + if self.path.startswith("/asset/"): + return self.reply(200, test.assets[self.path.removeprefix("/asset/")]) + if self.path.endswith("/releases/tags/v3.1.6"): + return self.reply(200, test.draft) if test.draft else self.reply(404, {}) + if self.path.endswith("/assets"): + return self.reply(200, [{"name": name, "browser_download_url": test.server_url + "/asset/" + name} + for name in test.assets]) + if "/packages/new-org/rpm/elog/" in self.path: + test.assertRegex(self.path, r"^/api/v1/packages/new-org/rpm/elog/3\.1\.6-1\.el(8|9|10)/files$") + version = self.path.split("/")[-2] + return self.reply(200, [{"sha256": hashlib.sha256(data).hexdigest()} + for name, data in test.rpms.items() if f"elog-{version}." in name]) + self.reply(404, {}) + + def do_POST(self): + test.writes += 1 + body = self.rfile.read(int(self.headers["Content-Length"])) + if self.path.endswith("/releases"): + test.draft = {**json.loads(body), "id": 1, "html_url": test.server_url + "/release/1"} + return self.reply(201, test.draft) + message = BytesParser(policy=default).parsebytes( + f"Content-Type: {self.headers['Content-Type']}\r\n\r\n".encode() + body) + attachment = next(message.iter_attachments()) + name = attachment.get_filename() + test.assertNotIn(name, test.assets, "Release assets must not be overwritten") + test.assets[name] = attachment.get_payload(decode=True) + self.reply(201, {}) + + def do_PUT(self): + test.writes += 1 + test.assertRegex(self.path, r"^/api/packages/new-org/rpm/el(8|9|10)/upload$") + data = self.rfile.read(int(self.headers["Content-Length"])) + name = data.decode() # Fixture contents identify the RPM. + if name in test.rpms: + return self.reply(409, {}) + test.rpms[name] = data + self.reply(201, {}) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.server_url = f"http://127.0.0.1:{self.server.server_port}" + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + env = {"SERVER_URL": self.server_url, "REPOSITORY": "new-org/elog", "VERSION": "3.1.6", + "PUBLISH_USER": "publisher", "PUBLISH_TOKEN": "test-token"} + self.addCleanup(patch.stopall) + patch.dict(os.environ, env).start() + self.docker = patch.object(release.subprocess, "run").start() + patch.object(release.subprocess, "check_output", return_value=b"image@sha256:example\n").start() + + def test_publish_and_retry_draft_in_new_organization(self): + release.publish(self.directory, "elog:test") + self.assertTrue(self.draft["draft"]) + self.assertEqual(len(self.rpms), 6) + self.assertEqual(len(self.assets), 10) + self.assertTrue(any("new-org/elog:3.1.6" in call.args[0][-1] for call in self.docker.call_args_list)) + for line in self.assets["SHA256SUMS"].decode().splitlines(): + expected, name = line.split(maxsplit=1) + self.assertEqual(expected, hashlib.sha256(self.assets[name]).hexdigest()) + release.publish(self.directory, "elog:test") + self.assertEqual(len(self.rpms), 6) + self.assertEqual(len(self.assets), 10) + + def test_bad_checksum_stops_before_publishing(self): + next((self.directory / "el9/RPMS").glob("*.rpm")).write_bytes(b"corrupt") + with self.assertRaisesRegex(ValueError, "Checksum mismatch"): + release.publish(self.directory, "elog:test") + self.assertEqual(self.writes, 0) + self.docker.assert_not_called() + + def test_conflicting_registry_package_is_rejected(self): + release.publish(self.directory, "elog:test") + self.rpms[next(iter(self.rpms))] = b"different RPM in registry" + with self.assertRaisesRegex(ValueError, "Existing registry RPM differs"): + release.publish(self.directory, "elog:test") + + def test_published_release_is_untouched(self): + self.draft = {"draft": False, "id": 1} + with self.assertRaisesRegex(ValueError, "already published"): + release.publish(self.directory, "elog:test") + self.assertEqual(self.writes, 0) + self.docker.assert_not_called() + + +if __name__ == "__main__": + unittest.main() -- 2.54.1 From dc5814211a2ea0718b591e335297bd4446055b6f Mon Sep 17 00:00:00 2001 From: Basil Bruhn Date: Mon, 23 Nov 2026 18:41:52 +0100 Subject: [PATCH 3/4] Use a public Rocky Linux runtime image --- Dockerfile | 8 ++------ Dockerfile.dockerignore | 4 +--- doc/ci-and-releases.md | 11 +++++++++-- docker/krb5.conf | 21 --------------------- elog.spec.template | 2 ++ 5 files changed, 14 insertions(+), 32 deletions(-) delete mode 100644 docker/krb5.conf diff --git a/Dockerfile b/Dockerfile index a10e4c8e..e57388dc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,4 @@ -ARG RUNTIME_IMAGE=gitea.psi.ch/images/rhel9:latest -FROM ${RUNTIME_IMAGE} +FROM rockylinux/rockylinux:9 ARG VERSION=unknown ARG REVISION=unknown @@ -9,12 +8,9 @@ LABEL org.opencontainers.image.title="ELOG" \ # Install the RPM produced from this checkout, rather than the repository's latest. COPY dist/el9/RPMS/*.rpm /tmp/elog-rpms/ -# Prefer libraries already present in the PSI base; resolve any missing ones online. -RUN (dnf install -y --disablerepo='*' /tmp/elog-rpms/*.rpm \ - || dnf install -y /tmp/elog-rpms/*.rpm) \ +RUN dnf install -y --setopt=install_weak_deps=False /tmp/elog-rpms/*.rpm \ && dnf clean all \ && rm -rf /tmp/elog-rpms /var/cache/dnf -COPY docker/krb5.conf /etc/krb5.conf EXPOSE 8080 CMD ["elogd", "-c", "/usr/local/elog/elogd.cfg"] diff --git a/Dockerfile.dockerignore b/Dockerfile.dockerignore index eddb29bc..f5861a38 100644 --- a/Dockerfile.dockerignore +++ b/Dockerfile.dockerignore @@ -1,8 +1,6 @@ -# The runtime image needs only the tested RPM and Kerberos configuration. +# The runtime image needs only the tested RPM. ** !dist/ !dist/el9/ !dist/el9/RPMS/ !dist/el9/RPMS/*.rpm -!docker/ -!docker/krb5.conf diff --git a/doc/ci-and-releases.md b/doc/ci-and-releases.md index 3415a712..8f7605a5 100644 --- a/doc/ci-and-releases.md +++ b/doc/ci-and-releases.md @@ -5,7 +5,10 @@ Everything is built by `.gitea/workflows/build.yml`: - EL8, EL9 and EL10: binary RPM, source RPM, source archive and checksums. - Windows x64: a portable ZIP with `elogd`, `elog`, `elconv`, OpenSSL and VC runtime DLLs, configuration, resources and the demo logbook. -- Container: the tested EL9 RPM installed in the existing PSI RHEL9 base. +- Container: the tested EL9 RPM installed in the public + [`rockylinux/rockylinux:9`](https://hub.docker.com/r/rockylinux/rockylinux) image. + Builds and runtime dependencies use public Rocky repositories; no private + RHEL image or PSI package mirror is required. Every build starts ELOG and checks its HTTP response. Branches, pull requests and manual runs validate the build and retain downloads for 30 days. **Only version @@ -66,7 +69,7 @@ Give the publishing account access to that organization and set these secrets: Runners need: - `ubuntu-latest-intranet`: Docker/BuildKit, Git, Bash, Python 3.9+ and Node 24. - It must reach PSI Gitea, `repos.psi.ch`, Docker Hub and Rocky's package mirrors. + It must reach Gitea, Docker Hub and Rocky's public package mirrors. EL10 needs an [x86-64-v3 capable host](https://docs.rockylinux.org/guides/minimum_hardware_requirements/). - Windows: Node 24, Git, PowerShell 7.3+, CMake 3.15+ and Visual Studio C++ Build Tools with the Windows SDK and C++ redistributable files. Set the Actions variable `WINDOWS_RUNNER` to its @@ -111,3 +114,7 @@ docker run --rm -p 8080:8080 \ Make the data directory writable by the container's `elog` account. Existing NFS mounts can keep their configured paths. See `elogd.cfg.example` and the [configuration manual](https://elog.psi.ch/elog/config.html). + +Kerberos support is compiled in, but the image contains no site-specific realms +or servers. If you use Kerberos, add a read-only mount for your own configuration: +`-v "$PWD/krb5.conf:/etc/krb5.conf:ro"`. diff --git a/docker/krb5.conf b/docker/krb5.conf deleted file mode 100644 index 2f4e27ab..00000000 --- a/docker/krb5.conf +++ /dev/null @@ -1,21 +0,0 @@ -[libdefaults] - default_realm = D.PSI.CH - dns_lookup_realm = false - ticket_lifetime = 10h - renew_lifetime = 30d - forwardable = true - rdns = false - udp_preference_limit = 10 - default_ccache_name = FILE:/tmp/krb5cc_%{uid} - -[realms] - D.PSI.CH = { - kdc = dc00.d.psi.ch - kdc = dc01.d.psi.ch - kdc = dc02.d.psi.ch - admin_server = dc00.d.psi.ch - } - -[domain_realm] - psi.ch = D.PSI.CH - .psi.ch = D.PSI.CH diff --git a/elog.spec.template b/elog.spec.template index a30dd67a..f317a95b 100644 --- a/elog.spec.template +++ b/elog.spec.template @@ -35,6 +35,8 @@ Vendor: Stefan Ritt URL: http://elog.psi.ch/elog BuildRoot: /tmp/%{name}-root Prefix: /usr/local +# The pre-install script creates the elog account. +Requires(pre): shadow-utils # Add build dependencies for pam, ssl and ldap features if enabled. # Note: Tag tokens must start at beginning-of-line. # -- 2.54.1 From 33f8ea70648c65b7c1589d865ff08bdb0474ed44 Mon Sep 17 00:00:00 2001 From: Basil Bruhn Date: Mon, 23 Nov 2026 18:48:18 +0100 Subject: [PATCH 4/4] Remove release test harness and document the release process --- .gitea/workflows/build.yml | 3 - doc/ci-and-releases.md | 116 ++++++++++++++++++++++------- tests/test_release.py | 149 ------------------------------------- 3 files changed, 91 insertions(+), 177 deletions(-) delete mode 100644 tests/test_release.py diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 6a91186d..ab33832b 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -20,9 +20,6 @@ jobs: with: submodules: recursive persist-credentials: false - - name: Test release publishing against a local API - if: matrix.el == 9 - run: python3 -m unittest discover -s tests -p test_release.py - name: Read version id: version env: diff --git a/doc/ci-and-releases.md b/doc/ci-and-releases.md index 8f7605a5..d3ab4ec4 100644 --- a/doc/ci-and-releases.md +++ b/doc/ci-and-releases.md @@ -10,45 +10,111 @@ Everything is built by `.gitea/workflows/build.yml`: Builds and runtime dependencies use public Rocky repositories; no private RHEL image or PSI package mirror is required. +ELOG itself is compiled from this checkout, including the pinned `mxml` +submodule. The container installs that newly built RPM. Gitea supplies the +source, Actions and release hosting; Docker Hub and public Rocky mirrors supply +the base images, compilers and system libraries. `repos.psi.ch` was used by the +previous private RHEL image and is no longer used by this workflow. + Every build starts ELOG and checks its HTTP response. Branches, pull requests and manual runs validate the build and retain downloads for 30 days. **Only version tag pushes publish packages or create release drafts.** -## Make a release +## What triggers publishing? -1. Update `src/elog-version.h` and the first version section in `doc/ChangeLog`. - Use patch versions for fixes, minor versions for compatible features and major - versions for breaking changes. -2. Tag the reviewed commit with the matching version and push it: +| Action | Result | +| --- | --- | +| Push a branch, open a pull request or start a manual run | Build and check the packages and container; retain CI downloads for 30 days. | +| Push a matching version tag, such as `v3.1.7` | Run all builds and checks, then publish versioned packages and prepare a Gitea release draft. | +| Click **Publish release** in Gitea | Make the release page public to readers of the repository. Packages are already published; no build or deployment is started. | - ```sh - git tag -a v3.1.6 -m "ELOG 3.1.6" - git push origin v3.1.6 +Developers own functional validation and release approval, using the project's +usual review process. CI retains the build, installation and HTTP checks. +`.gitea/scripts/release.py` handles the uploads and release draft. + +## Full example: release 3.1.7 + +Assume this repository has moved to `elog/elog`, its default branch is `master`, +and the setup below is complete. These are example commands, not a release that +has already been created. + +1. Prepare the version and release notes through the project's usual change and + review process. Change `src/elog-version.h` to: + + ```c + #define VERSION "3.1.7" ``` -3. After all Linux and Windows checks pass, CI publishes the versioned container - and RPMs, and creates a **draft Gitea Release**. The draft contains the Windows - ZIP, RPMs, source RPMs, a source archive including `mxml`, checksums, the image - digest and notes from `doc/ChangeLog`. Review the notes and publish the draft. + Prepend a section to `doc/ChangeLog`, retaining the older entries: -The tag must match the source version exactly. Prerelease tags are not supported. -Protect `v*` tags and never move a released tag. After releasing, bump the source -version for the next development cycle. Snapshot RPMs use release -`0..git`; tagged RPMs use release `1`. + ```text + Version 3.1.7, released November 23rd, 2026 + ========================================== + + - Build Linux and Windows packages with Gitea Actions. + - Use a public Rocky Linux base for the container. + ``` + + Use the actual release date and changes. Merge the reviewed change as usual. + +2. Tag the reviewed commit on the default branch: + + ```sh + git switch master + git pull --ff-only + git tag -a v3.1.7 -m "ELOG 3.1.7" + git push origin v3.1.7 + ``` + + Pushing the tag authorizes package publication. The tag must match the source + version exactly; a mismatch fails the build. An ordinary branch push does + not publish packages. + +3. Wait for the tag's Actions run to finish. CI builds and checks EL8, EL9 and + EL10 RPMs plus the Windows ZIP. It then builds the container from the checked + EL9 RPM and checks its HTTP response. After those checks pass, the publishing + helper creates a draft, pushes the versioned image, attaches the downloads + and uploads the RPMs to the organization's package registry. + + For this example the results are: + + | Output | Location/name | + | --- | --- | + | Container | `gitea.psi.ch/elog/elog:3.1.7` | + | Native RPMs | `elog-3.1.7-1.el8.x86_64.rpm`, plus EL9 and EL10 equivalents | + | Source RPMs | `elog-3.1.7-1.el8.src.rpm`, plus EL9 and EL10 equivalents | + | Source archive, including `mxml` | `elog-3.1.7-1.tar.gz` | + | Windows download | `elog-3.1.7-windows-x64.zip` | + | Integrity/provenance | `SHA256SUMS` and `image.txt` containing the image digest | + | RPM repositories | `https://gitea.psi.ch/api/packages/elog/rpm/el9.repo`, plus `el8` and `el10` | + +4. Open **Releases** in the repository. Wait for the publishing job to succeed, + review the **ELOG 3.1.7** draft, its notes and attached files, then click + **Publish release**. Notes are initially taken from the first section of + `doc/ChangeLog`. + + The image and RPMs become available during step 3, before this manual step. + Publishing the draft does not promote `latest` or restart any installation. + Update deployments separately to use `gitea.psi.ch/elog/elog:3.1.7` or its + recorded digest. If you also maintain `latest`, promote it explicitly after + reviewing the release: + + ```sh + docker login gitea.psi.ch + docker buildx imagetools create \ + --tag gitea.psi.ch/elog/elog:latest \ + gitea.psi.ch/elog/elog:3.1.7 + ``` + +Protect `v*` tags and never move a released tag. Prerelease tags are not +supported. Snapshot RPMs use release `0..git`; tagged RPMs +use release `1`. Bump the source version for the next development cycle when +appropriate so its snapshots sort after the previous stable release. Published releases are never edited by CI. A failed publishing job can resume a draft when its artifacts are identical; conflicting files fail instead of being replaced. Rerun the failed publishing job using the original build artifacts. -`latest` is optional and stays a deliberate promotion of a reviewed release: - -```sh -organization=your-org -docker buildx imagetools create \ - --tag "gitea.psi.ch/$organization/elog:latest" \ - "gitea.psi.ch/$organization/elog:3.1.6" -``` - ## Gitea setup The publishing paths follow the repository automatically. For `my-org/elog`: diff --git a/tests/test_release.py b/tests/test_release.py deleted file mode 100644 index 9410acfb..00000000 --- a/tests/test_release.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Exercise publishing against a local Gitea API stand-in; Docker is mocked.""" -import hashlib -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -import importlib.util -import json -import os -from pathlib import Path -import tempfile -import threading -import unittest -from unittest.mock import patch -from email.parser import BytesParser -from email.policy import default - -spec = importlib.util.spec_from_file_location("release", Path(__file__).parents[1] / ".gitea/scripts/release.py") -release = importlib.util.module_from_spec(spec) -spec.loader.exec_module(release) - - -class ReleaseTest(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - self.directory = Path(self.temp.name) - previous_directory = Path.cwd() - self.addCleanup(os.chdir, previous_directory) - os.chdir(self.directory) - (self.directory / "doc").mkdir() - (self.directory / "doc/ChangeLog").write_text("Version 3.1.6, released for this test\n- Fixture release notes\n") - for target in ("el8", "el9", "el10", "windows"): - root = self.directory / target - names = ([f"RPMS/elog-3.1.6-1.{target}.x86_64.rpm", f"SRPMS/elog-3.1.6-1.{target}.src.rpm"] - if target != "windows" else ["elog-3.1.6-windows-x64.zip"]) - if target == "el9": - names.append("SOURCES/elog-3.1.6-1.tar.gz") - for name in names: - file = root / name - file.parent.mkdir(parents=True, exist_ok=True) - file.write_bytes(name.encode()) - (root / "SHA256SUMS").write_text("".join( - f"{hashlib.sha256((root / name).read_bytes()).hexdigest()} {name}\n" for name in names)) - self.draft = None - self.assets = {} - self.rpms = {} - self.writes = 0 - test = self - - class Handler(BaseHTTPRequestHandler): - def parse_request(self): - valid = super().parse_request() - if valid: - test.assertEqual(self.headers.get("Authorization"), "token test-token") - return valid - - def log_message(self, *args): - pass - - def reply(self, code, data): - self.send_response(code) - self.end_headers() - self.wfile.write(data if isinstance(data, bytes) else json.dumps(data).encode()) - - def do_GET(self): - if self.path.startswith("/asset/"): - return self.reply(200, test.assets[self.path.removeprefix("/asset/")]) - if self.path.endswith("/releases/tags/v3.1.6"): - return self.reply(200, test.draft) if test.draft else self.reply(404, {}) - if self.path.endswith("/assets"): - return self.reply(200, [{"name": name, "browser_download_url": test.server_url + "/asset/" + name} - for name in test.assets]) - if "/packages/new-org/rpm/elog/" in self.path: - test.assertRegex(self.path, r"^/api/v1/packages/new-org/rpm/elog/3\.1\.6-1\.el(8|9|10)/files$") - version = self.path.split("/")[-2] - return self.reply(200, [{"sha256": hashlib.sha256(data).hexdigest()} - for name, data in test.rpms.items() if f"elog-{version}." in name]) - self.reply(404, {}) - - def do_POST(self): - test.writes += 1 - body = self.rfile.read(int(self.headers["Content-Length"])) - if self.path.endswith("/releases"): - test.draft = {**json.loads(body), "id": 1, "html_url": test.server_url + "/release/1"} - return self.reply(201, test.draft) - message = BytesParser(policy=default).parsebytes( - f"Content-Type: {self.headers['Content-Type']}\r\n\r\n".encode() + body) - attachment = next(message.iter_attachments()) - name = attachment.get_filename() - test.assertNotIn(name, test.assets, "Release assets must not be overwritten") - test.assets[name] = attachment.get_payload(decode=True) - self.reply(201, {}) - - def do_PUT(self): - test.writes += 1 - test.assertRegex(self.path, r"^/api/packages/new-org/rpm/el(8|9|10)/upload$") - data = self.rfile.read(int(self.headers["Content-Length"])) - name = data.decode() # Fixture contents identify the RPM. - if name in test.rpms: - return self.reply(409, {}) - test.rpms[name] = data - self.reply(201, {}) - - self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - self.server_url = f"http://127.0.0.1:{self.server.server_port}" - threading.Thread(target=self.server.serve_forever, daemon=True).start() - self.addCleanup(self.server.server_close) - self.addCleanup(self.server.shutdown) - env = {"SERVER_URL": self.server_url, "REPOSITORY": "new-org/elog", "VERSION": "3.1.6", - "PUBLISH_USER": "publisher", "PUBLISH_TOKEN": "test-token"} - self.addCleanup(patch.stopall) - patch.dict(os.environ, env).start() - self.docker = patch.object(release.subprocess, "run").start() - patch.object(release.subprocess, "check_output", return_value=b"image@sha256:example\n").start() - - def test_publish_and_retry_draft_in_new_organization(self): - release.publish(self.directory, "elog:test") - self.assertTrue(self.draft["draft"]) - self.assertEqual(len(self.rpms), 6) - self.assertEqual(len(self.assets), 10) - self.assertTrue(any("new-org/elog:3.1.6" in call.args[0][-1] for call in self.docker.call_args_list)) - for line in self.assets["SHA256SUMS"].decode().splitlines(): - expected, name = line.split(maxsplit=1) - self.assertEqual(expected, hashlib.sha256(self.assets[name]).hexdigest()) - release.publish(self.directory, "elog:test") - self.assertEqual(len(self.rpms), 6) - self.assertEqual(len(self.assets), 10) - - def test_bad_checksum_stops_before_publishing(self): - next((self.directory / "el9/RPMS").glob("*.rpm")).write_bytes(b"corrupt") - with self.assertRaisesRegex(ValueError, "Checksum mismatch"): - release.publish(self.directory, "elog:test") - self.assertEqual(self.writes, 0) - self.docker.assert_not_called() - - def test_conflicting_registry_package_is_rejected(self): - release.publish(self.directory, "elog:test") - self.rpms[next(iter(self.rpms))] = b"different RPM in registry" - with self.assertRaisesRegex(ValueError, "Existing registry RPM differs"): - release.publish(self.directory, "elog:test") - - def test_published_release_is_untouched(self): - self.draft = {"draft": False, "id": 1} - with self.assertRaisesRegex(ValueError, "already published"): - release.publish(self.directory, "elog:test") - self.assertEqual(self.writes, 0) - self.docker.assert_not_called() - - -if __name__ == "__main__": - unittest.main() -- 2.54.1