diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..89c5e0e5 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +.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 +**/__pycache__ diff --git a/.gitea/scripts/build-rpm.sh b/.gitea/scripts/build-rpm.sh new file mode 100644 index 00000000..e987d5bd --- /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 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" +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/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 new file mode 100644 index 00000000..6de66fda --- /dev/null +++ b/.gitea/scripts/metadata.sh @@ -0,0 +1,32 @@ +#!/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 +else + release="0.$timestamp.git$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" +} 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/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..ab33832b --- /dev/null +++ b/.gitea/workflows/build.yml @@ -0,0 +1,115 @@ +name: Build and release ELOG + +on: + push: + branches: ['**'] + tags: ['v*'] + pull_request: + workflow_dispatch: + +jobs: + linux: + name: EL${{ matrix.el }} + runs-on: ubuntu-latest-intranet + strategy: + fail-fast: false + matrix: + el: [8, 9, 10] + steps: + - uses: https://gitea.psi.ch/actions/checkout@v7 + with: + submodules: recursive + persist-credentials: false + - name: Read version + id: version + env: + BUILD_REF: ${{ github.ref }} + run: bash .gitea/scripts/metadata.sh + - name: Build and test RPMs + env: + EL_VERSION: ${{ matrix.el }} + 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" \ + --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" . + # These PSI v3 artifact actions use Node 24. + - uses: https://gitea.psi.ch/actions/upload-artifact@v3.2.2 + with: + name: el${{ matrix.el }} + path: dist/el${{ matrix.el }}/ + if-no-files-found: error + retention-days: 30 + + 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: + - uses: https://gitea.psi.ch/actions/checkout@v7 + with: + persist-credentials: false + - uses: https://gitea.psi.ch/actions/download-artifact@v3.1.0 + with: + 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 and test the container + env: + 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" + # 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: + VERSION: ${{ steps.version.outputs.version }} + SERVER_URL: ${{ github.server_url }} + REPOSITORY: ${{ github.repository }} + PUBLISH_USER: ${{ secrets.PUBLISH_USER }} + PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }} + run: | + : "${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 33c6a615..1f8659b7 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,5 @@ cmake-build-debug 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/Dockerfile b/Dockerfile index 8d49e21f..e57388dc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,16 @@ -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 +FROM rockylinux/rockylinux:9 + +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/ +RUN dnf install -y --setopt=install_weak_deps=False /tmp/elog-rpms/*.rpm \ + && dnf clean all \ + && rm -rf /tmp/elog-rpms /var/cache/dnf + +EXPOSE 8080 +CMD ["elogd", "-c", "/usr/local/elog/elogd.cfg"] diff --git a/Dockerfile.dockerignore b/Dockerfile.dockerignore new file mode 100644 index 00000000..f5861a38 --- /dev/null +++ b/Dockerfile.dockerignore @@ -0,0 +1,6 @@ +# The runtime image needs only the tested RPM. +** +!dist/ +!dist/el9/ +!dist/el9/RPMS/ +!dist/el9/RPMS/*.rpm diff --git a/README.md b/README.md index a1178358..50a07df5 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 releases](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..d3ab4ec4 --- /dev/null +++ b/doc/ci-and-releases.md @@ -0,0 +1,186 @@ +# Builds and releases + +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 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. + +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.** + +## What triggers publishing? + +| 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. | + +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" + ``` + + Prepend a section to `doc/ChangeLog`, retaining the older entries: + + ```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. + +## Gitea setup + +The publishing paths follow the repository automatically. For `my-org/elog`: + +- 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 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 + 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 RPM_RELEASE=0.local \ + --build-arg "REVISION=$(git rev-parse HEAD)" \ + --build-arg "SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)" \ + --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`/`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" \ + elog:local elogd -c /usr/local/elog/elogd.cfg -d /var/lib/elog +``` + +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/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/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. # 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" 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%"