diff --git a/docs/3._Knowledge_Center/01_Tutorials/02_python.md b/docs/3._Knowledge_Center/01_Tutorials/02_python.md index 9b42b4f9..e9b653fc 100644 --- a/docs/3._Knowledge_Center/01_Tutorials/02_python.md +++ b/docs/3._Knowledge_Center/01_Tutorials/02_python.md @@ -9,9 +9,20 @@ tags: # PSI Python Environment -In this tutorial you build `pvshow`, a small Python tool that reads PVs over Channel Access and prints their value and timestamp. You start with a ten-line script and grow it in four stages into a package with a command, tests, a version tag and the files to package it. Every stage runs before you go on. The tool only reads PVs. Plan about an hour. +In this tutorial you build `pvshow`, a small Python tool that reads PVs over Channel Access and prints their value and timestamp. You start with a ten-line script and grow it in six stages into a package with a command, tests, a release, an RPM spec, a container image and automatic builds in Gitea. Every stage runs before you go on. The tool only reads PVs. -![The four stages: 1 one script, read_pv.py; 2 a package with a command, pyproject.toml and pvshow/cli.py, installed with pip install -e .; 3 a tool you can rely on, with several PVs, JSON, follow mode, logs on stderr and unit tests; 4 ready to hand over, with version 1.0.0, python -m build and pvshow.spec for an RPM](images/02_python_overview.svg) +You do not need all of this. The tutorial shows how to set up everything a tool might need; a real tool uses only the parts it needs, and many stop after stage 2 or 3. Stages 1 and 2 are the base. After that, take only the stages you need; stage 6 automates what you set up in stages 3 to 5, so leave out the workflow steps for parts you do not have. + +![The six stages: 1 one script; 2 a package with a command; optional: 3 a tool you can rely on, with tests; 4 ready to hand over, with version, tag, wheel, sdist and RPM spec; 5 a container image; 6 automatic builds with Gitea Actions. Take only the optional stages your tool needs; the tool reaches Controls hosts with autodeploy](images/02_python_overview.svg) + +| Stage | What you get | When you need it | +| --- | --- | --- | +| 1. One script | a script that reads a PV | to try something out | +| 2. A package with a command | the command `pvshow`, installed with pip, with options and exit codes | for every tool that others install; the base for the rest | +| 3. A tool you can rely on (optional) | several PVs, JSON, follow mode, logging, unit tests | when others depend on the tool or it runs as a service | +| 4. Ready to hand over (optional) | version and tag, wheel and sdist, RPM spec | when you release it to others | +| 5. A container image (optional) | an image in the Gitea registry | when the tool runs in a container | +| 6. Automatic builds (optional) | tests on every push, a release built and published from a tag | when you release often or several people work on the tool | ## Before you start @@ -78,7 +89,7 @@ Put the project under Git from the start. Create `.gitignore`, so the venv stays A script is run by its path. A package with a command is installed into the venv and run by its name, with options, a help text and exit codes that other programs can check. The finished project looks like this; in this stage you create `pyproject.toml` and the folder `pvshow/` with `__init__.py` and `cli.py`. The package folder sits directly next to `pyproject.toml` (a flat layout): nothing more to learn for a package of this size. -![Layout of the finished project: pyproject.toml, README.md, .gitignore, pvshow.spec, the package folder pvshow with __init__.py, cli.py and reader.py, the folder tests and .venv, which is not in Git; the line pvshow = "pvshow.cli:main" in pyproject.toml makes pip write .venv/bin/pvshow, which calls main() in pvshow/cli.py](images/02_python_layout.svg) +![Layout of the finished project: pyproject.toml, README.md, .gitignore, pvshow.spec, Containerfile, .containerignore, the package folder pvshow with __init__.py, cli.py and reader.py, the folders tests and .gitea/workflows with ci.yml and release.yml, and .venv, which is not in Git; the line pvshow = "pvshow.cli:main" in pyproject.toml makes pip write .venv/bin/pvshow, which calls main() in pvshow/cli.py](images/02_python_layout.svg) The command replaces the script. Remove it, create the package folder and its empty `__init__.py`, which makes the folder a package: @@ -174,7 +185,7 @@ Run it: The first prints name, value and timestamp, for example ` 21.5 2026-11-25 14:04:47.849`. The second prints `pvshow: TUT:DOES-NOT-EXIST: no connection within 1.0 s` and exit code `1`. `which pvshow` shows where the command lives: `/psi.ch//git/pvshow/.venv/bin/pvshow`. Because the install is editable, a change in `cli.py` takes effect at the next run, without installing again. Commit the stage. -## Stage 3: a tool you can rely on +## Stage 3: a tool you can rely on (optional) Now the tool reads several PVs at once, prints JSON for other programs, can keep running and print every change, logs what goes wrong, and has tests. The reading moves into its own module, `pvshow/reader.py`, so that it can be tested without the command line: @@ -395,7 +406,7 @@ Give the stage a new version: in `pyproject.toml`, change `version = "0.1.0"` to Commit the stage. -## Stage 4: ready to hand over +## Stage 4: ready to hand over (optional) Before others use the tool, it gets a version they can ask for, a tag in Git, and the files to package it. How you package and deliver it is your choice; this stage shows two ways briefly. @@ -484,16 +495,261 @@ Commit, then publish the repository. In Gitea, create an empty repository `pvsho The repository page in Gitea shows your files and the tag `1.0.0`. -Getting the tool onto Controls hosts is done with [Autodeploy](../../2._Services_Portfolio/Services/11_autodeploy.md); the policy for Python software on the Controls platform is in [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software). +## Stage 5: a container image (optional) + +Package the tool as a container image when it should run in a container, for example as a service on a container host. This stage keeps to the essentials; everything else about images, the registry and running containers is in [How-To: Use Containers](../03_how_to/09_containers.md). Give the release a new version first: set `version = "1.1.0"` in `pyproject.toml` and `%define version 1.1.0` in `pvshow.spec`. + +Create `Containerfile` in the project folder: + + # Build for linux/amd64: pyepics bundles its Channel Access library (libca) + # for linux64 only, and the Controls hosts are x86_64. + # + # podman build --platform linux/amd64 -t pvshow:dev . + FROM python:3.11-slim + WORKDIR /app + COPY pyproject.toml README.md ./ + COPY pvshow/ pvshow/ + RUN pip install --no-cache-dir . + ENV PYTHONUNBUFFERED=1 + RUN useradd --create-home --uid 10001 appuser + USER appuser + ENTRYPOINT ["pvshow"] + +Line by line: + +- `FROM python:3.11-slim`: a small Debian image with Python 3.11, pinned to that version so a rebuild gives the same Python. +- `COPY` and `RUN pip install --no-cache-dir .`: copy only what the package needs and install it with pip, as in a venv; `--no-cache-dir` keeps pip's cache out of the image. +- `ENV PYTHONUNBUFFERED=1`: output is written at once and reaches the journal. +- `useradd --uid 10001` and `USER appuser`: the tool runs as an ordinary user with a fixed uid, not as root. +- `ENTRYPOINT ["pvshow"]`: the container runs the command, and the arguments of `podman run` after the image name go to `pvshow`. The list form makes `pvshow` the main process, so it receives the stop signal directly. + +Create `.containerignore`, which keeps Git data, the venv, the tests and build output out of the build: + + .git + .gitea + .venv + __pycache__ + *.pyc + *.egg-info + build + dist + RPMS + tests + .env + +On a machine with Podman, build the image for `linux/amd64` and run it. The platform matters: pyepics brings its Channel Access library for 64-bit Linux on x86 only, and the Controls hosts are x86_64, so an image built for arm64 on a Mac with Apple Silicon cannot open a single channel. + + podman build --platform linux/amd64 -t pvshow:dev . + podman run --rm pvshow:dev --help + +The second command prints the same help as `pvshow --help`. To read a PV, the container needs what the tool uses on the host: the Channel Access environment and the network. `-e NAME` without a value copies the variable from your shell; `--network host` lets the container search on the same networks as the host, including the CA gateway named in `EPICS_CA_ADDR_LIST`: + + podman run --rm --network host -e EPICS_CA_ADDR_LIST -e EPICS_CA_AUTO_ADDR_LIST pvshow:dev + +Publish the image by hand to the Gitea registry `gitea.psi.ch`, under your group's organisation and the version. Log in with your Gitea user and, as password, a Gitea access token with the scope `write:package` (**Settings → Applications → Access Tokens**): + + podman login gitea.psi.ch -u + podman tag pvshow:dev gitea.psi.ch//pvshow:1.1.0 + podman push gitea.psi.ch//pvshow:1.1.0 + +The image is then listed in the **Packages** tab of the organisation in Gitea. Commit, tag and push the release: + + git add . + git commit -m "Stage 5: container image, version 1.1.0" + git tag 1.1.0 + git push origin HEAD 1.1.0 + +## Stage 6: automatic builds with Gitea Actions (optional) + +Until now you ran the tests and built the packages and the image by hand. Gitea Actions does it for you: Gitea runs the workflows in `.gitea/workflows/` of your repository on its runners. This stage adds two workflows, modelled on the ones that build and release the gfa-monitoring application on this Gitea: + +- `ci.yml` checks every push to `main` and every pull request. +- `release.yml` builds and publishes a release when you push a version tag. + +Create `.gitea/workflows/ci.yml`: + + name: CI + + # On every push to main and every pull request: install the package, run the + # tests, build the wheel and sdist, and check that the container image builds. + # Nothing is published. + + on: + push: + branches: [main] + pull_request: + + jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install + run: pip install --no-cache-dir . + - name: Tests + run: python -m unittest -v + - name: Build wheel and sdist + run: | + pip install --no-cache-dir build + python -m build + + container: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build image + run: docker build -f Containerfile -t pvshow:ci . + +- The job `test` checks out the commit, sets up Python 3.11, installs the package, runs the unit tests and builds the wheel and the sdist. +- The job `container` builds the image with Docker on the runner, to show that the `Containerfile` still works. Nothing is published. + +Create `.gitea/workflows/release.yml`: + + name: Release + + # On a version tag (the bare version number) that is on main: + # + # git tag 1.2.0 && git push origin 1.2.0 + # + # test, build the wheel and sdist and keep them as artifacts of the run, then + # build the image for linux/amd64 and push it to the Gitea registry with the + # tags :1.2.0, :1.2, :latest and :sha-. + # + # Requires a repository secret REGISTRY_TOKEN holding a Gitea access token + # with write:package. The built-in token has no package scope. + + on: + push: + tags: ["[0-9]*"] + + permissions: + contents: read + packages: write + + env: + REGISTRY: gitea.psi.ch + IMAGE_NAME: ${{ gitea.repository }} + + jobs: + guard: + name: Verify the tag is on main + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Reject tags that are not contained in main + run: | + set -euo pipefail + git fetch --quiet origin main + TAG_SHA="$(git rev-list -n 1 "${{ gitea.ref }}")" + if git merge-base --is-ancestor "$TAG_SHA" origin/main; then + echo "Tag ${{ gitea.ref_name }} is on main. Proceeding." + else + echo "::error::Tag ${{ gitea.ref_name }} is not on main. Only tags on main are released." + exit 1 + fi + + packages: + name: Test and build wheel and sdist + needs: guard + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: pip install --no-cache-dir . + - run: python -m unittest -v + - run: | + pip install --no-cache-dir build + python -m build + - uses: actions/upload-artifact@v3 + with: + name: pvshow-${{ gitea.ref_name }} + path: dist/ + + image: + name: Build and push the image + needs: packages + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - name: Fail early if no registry token is configured + run: | + if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then + echo "::error::REGISTRY_TOKEN is not set; the push would fail with 'unauthorized'." + exit 1 + fi + - name: Log in to the Gitea registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + - name: Derive tags + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=sha,prefix=sha-,format=short + type=raw,value=latest + - name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: Containerfile + push: true + # pyepics bundles libca for linux64 only; the Controls hosts are x86_64. + platforms: linux/amd64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + +- `on: push: tags: ["[0-9]*"]`: the workflow runs for tags that start with a digit, so for version tags like `1.2.0`. +- The job `guard` stops the release when the tag points at a commit that is not on `main`; a tag can be pushed from any commit. +- The job `packages` runs the tests, builds the wheel and the sdist, and keeps `dist/` as an artifact of the run, named after the tag. +- The job `image` logs in to `gitea.psi.ch` with the token from the secret `REGISTRY_TOKEN`, derives the image tags from the version tag (`1.2.0`, `1.2`, `latest`, `sha-`), builds the image for `linux/amd64` and pushes it to `gitea.psi.ch//pvshow`. It stops at once with an error when the secret is missing. + +The RPM is not built here: build it by hand as in stage 4. + +Set up the repository once in Gitea: + +1. In the repository settings, enable Actions for the repository. +2. Create an access token with the scope `write:package` under **Settings → Applications → Access Tokens**. The built-in token of Gitea Actions has no package scope, so the push needs a token of its own. +3. Store the token in the repository under **Settings → Actions → Secrets** as `REGISTRY_TOKEN`. + +Commit and push the workflows: + + git add .gitea + git commit -m "Stage 6: Gitea Actions for CI and release" + git push + +In the **Actions** tab of the repository, a run of **CI** appears with the jobs `test` and `container`; when both are green, the commit passed. A pull request shows the same checks. Now release with a version tag. Set the version `1.2.0` in `pyproject.toml` and `pvshow.spec`, commit, tag and push: + + git commit -am "Version 1.2.0" + git push + git tag 1.2.0 + git push origin 1.2.0 + +A run of **Release** appears with the jobs `guard`, `packages` and `image`. When it is green, the run page offers the artifact `pvshow-1.2.0` with the wheel and the sdist for download, and the organisation's **Packages** tab lists the image `pvshow` with the tags `1.2.0`, `1.2`, `latest` and `sha-`. ## What you have learned -You have grown a script into a Python tool the Controls way: a package with standard metadata in `pyproject.toml` and a command, installed with pip into a venv in editable mode; output on stdout and log messages on stderr, so that it works as a service; tests that run without an EPICS network; a README with the requirements per install route; a version and a tag in Gitea; and a wheel, a source archive and an RPM spec, ready for the packaging you choose. +You have grown a script into a Python tool the Controls way: a package with standard metadata in `pyproject.toml` and a command, installed with pip into a venv in editable mode; output on stdout and log messages on stderr, so that it works as a service; tests that run without an EPICS network; a README with the requirements per install route; a version and a tag in Gitea; a wheel, a source archive and an RPM spec; a container image in the Gitea registry; and workflows that test every push and publish a release from a tag. + +Again: you do not need all of it. Keep the stages your tool needs and leave out the rest. Getting the tool onto Controls hosts is done with [Autodeploy](../../2._Services_Portfolio/Services/11_autodeploy.md); the policy for Python software on the Controls platform is in [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software). Where to go next: - [How-To: Manage Virtual Python Environments](../03_how_to/08_python_venv.md): reproduce an environment on another machine, run a tool from a service, pixi as an alternative. - [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software): the policy and the install routes. - [IOC Utils](../../2._Services_Portfolio/Tools/01_ioc_utils.md): a Controls Python tool in daily use. -- [How-To: Use Containers](../03_how_to/09_containers.md): run a Python service in a container. +- [How-To: Use Containers](../03_how_to/09_containers.md): images, the registry and running containers on a container host. - [How-To: Build and Deploy RPMs](../03_how_to/07_build_deploy_rpms.md). diff --git a/docs/3._Knowledge_Center/01_Tutorials/images/02_python_layout.svg b/docs/3._Knowledge_Center/01_Tutorials/images/02_python_layout.svg index e2ddacf5..f77d83fd 100644 --- a/docs/3._Knowledge_Center/01_Tutorials/images/02_python_layout.svg +++ b/docs/3._Knowledge_Center/01_Tutorials/images/02_python_layout.svg @@ -1,6 +1,6 @@ - + Layout of the pvshow project and how the command finds its code - The finished project folder pvshow holds pyproject.toml (name, version, dependencies, command), README.md (requirements per install route), .gitignore (keeps .venv and build output out of Git), pvshow.spec (RPM, if you choose one), the package folder pvshow with __init__.py, cli.py (main: options and output) and reader.py (reads PVs, follows changes), the folder tests with test_pvshow.py, which needs no EPICS network, and .venv, which is not in Git. The line pvshow = "pvshow.cli:main" in pyproject.toml makes pip write the script .venv/bin/pvshow, which calls main() in pvshow/cli.py. + The finished project folder pvshow holds pyproject.toml (metadata and the command), README.md (requirements per install route), .gitignore, pvshow.spec (RPM, stage 4), Containerfile and .containerignore (container image, stage 5), the package folder pvshow with __init__.py, cli.py (main: options and output) and reader.py (reads PVs, follows changes), the folder tests, the folder .gitea/workflows with ci.yml (on push and pull request) and release.yml (on a version tag), stage 6, and .venv, which is not in Git. The line pvshow = "pvshow.cli:main" in pyproject.toml makes pip write the script .venv/bin/pvshow, which calls main() in pvshow/cli.py.