diff --git a/docs/2._Services_Portfolio/Services/03_devops.md b/docs/2._Services_Portfolio/Services/03_devops.md index e5cf652d..4fb94490 100644 --- a/docs/2._Services_Portfolio/Services/03_devops.md +++ b/docs/2._Services_Portfolio/Services/03_devops.md @@ -198,7 +198,7 @@ Controls delivers Python tools that work with the control system, for example th | Outside the RPM, the main way to install a Python tool is `pip` in a virtual environment (venv). | It stays in your home directory, does not change the host, and works on any machine that has Python. | | **pixi** is an optional alternative for a project that wants its Python and packages declared in a manifest and a lock file that pins every version. | The environment rebuilds identically on every machine and after a re-create. AIT supports pixi for the beamlines, so Controls uses the same tool instead of a parallel one. | | Installing into your user's Python (`pip install --user`) is possible for one user without root and without a venv. | It also stays in your home directory and does not change the host. | -| Every Controls Python tool states its requirements for each way of installing it. | The requirements differ: system packages for the RPM, PyPI for pip, package channels for pixi. | +| Every Controls Python tool states all of its requirements properly, for each way of installing it. | Installing the tool must be enough to make it work: the package declares every dependency and the install pulls them in, so nobody has to install something extra by hand afterwards. The requirements differ per route: system packages for the RPM, PyPI for pip, package channels for pixi. | | No `sudo pip install` into the system Python, no hand-installed packages on a standard host, no conda. | A host changed by hand has left its standard. It is no longer supported, and the remedy is a re-create to standard. | The one exception to "no conda": `ioc install` still builds the environment of a Python IOC with conda. This is legacy and still works, see [Python IOCs](#python-iocs). @@ -302,7 +302,7 @@ What your project needs: - Source in a Git repository, documented in a `README.md`. Nothing that matters may live only on a machine: source and build results belong in Git and in the repositories, so a machine can be re-created at any time. - Standard packaging metadata in `pyproject.toml` or `setup.py`: name, version, dependencies, and the commands as console-script entry points. `cas-iocutils/setup.py` is a working example. -- The requirements for each install method, stated in the README: supported Python versions (`requires-python`), dependencies, and where they come from. +- All requirements stated properly: every dependency declared in the package metadata, so that installing the tool pulls them in and nothing has to be installed by hand afterwards; and in the README, for each install method, the supported Python versions (`requires-python`), the dependencies and where they come from. - `pip install .` must work in a fresh venv as a normal user. Do not install files to absolute system paths (for example via `data_files` to `/etc`). - For pixi: a `pixi.toml` and a `pixi.lock` in the repository. - For RPM delivery: a `.spec` file, written by the application developer. Every dependency must exist as a RHEL9 `python3-*` RPM, because the RPM declares them with `Requires:` and does not bundle them. Pure-Python tools are built as `noarch`. Build the RPM on a RHEL9 machine with `rpm-build` (`rpmbuild -bb .spec`); give each release a new version number in both the packaging metadata and the spec, in the same commit, and tag that commit. diff --git a/docs/2._Services_Portfolio/Tools/08_monitoring_tools.md b/docs/2._Services_Portfolio/Tools/08_monitoring_tools.md index 2fedfaf4..d3fb499e 100644 --- a/docs/2._Services_Portfolio/Tools/08_monitoring_tools.md +++ b/docs/2._Services_Portfolio/Tools/08_monitoring_tools.md @@ -8,3 +8,156 @@ tags: --- # Monitoring Tools + +## Which tool for which question + +![Which tool for which question: IOC running or red, host state, PVs and CA gateways in gfa-monitoring; host load history in Grafana; logs in Kibana or with journalctl; past PV values in the archiver viewer](images/08_monitoring_chooser.svg) + +The same questions can be answered from a terminal with the `ioc` command, see [IOC Utils: on the command line](#ioc-utils-on-the-command-line). What Controls IT collects and how the logs travel is described in [Controls IT Services: Logging](../Services/03_devops.md#logging) and [Monitoring](../Services/03_devops.md#monitoring). + +## gfa-monitoring + +gfa-monitoring is planned to become the web-based hub for the Controls IT services. Today it is a proof of concept: it runs and you can use it, but its functions and screens may still change. Once Controls IT has settled its functionality and user interface, it will be implemented professionally for long-term maintenance, support and security. Machines are also requested there, see [Controls IT Infrastructure](../Services/02_computingandboot.md#how-to-request-a-machine-or-a-change). + +Open [http://gfa-monitoring.psi.ch](http://gfa-monitoring.psi.ch) in a browser inside PSI. There is no login. The start page is the **Facilities overview**. + +### The views you need + +| Sidebar entry | Use it for | +|---|---| +| Facilities overview | one card per facility: how many IOCs are ok, warn and in error, the share on a supported EPICS version, and the latest problem IOCs | +| Wall dashboard | the same for a large screen; opens in a new tab without the sidebar | +| Host list, Host details | every host with its status; one host with its checks, its IOCs and their CPU and memory use, its installed packages, and links to Grafana and Puppetboard | +| IOC list, IOC details | every IOC with its status; one IOC with the reason for each check, boot host and time, uptime, loaded modules, live resources and its PVs | +| PV list, PV monitoring | find a PV by name, IOC, host or facility and see which IOC and host serve it; watch a set of PVs live and compare snapshots | +| Gateways | the live state of every Channel Access gateway per facility | + +Every list has a search and filters. A filter that limits the rows is shown in red, with "Filtered: showing N of M" above the table; **Show everything** removes all limits. Hosts that have not reported for 24 hours and IOCs not booted this year are hidden until you remove that limit. Filters are part of the address (for example `?facility=sls`), so a link you send shows the same view. + +### Reading a status + +![From the Facilities overview to the IOC list of the facility to IOC details, where each check shows its grade and the reason, for example Online error with Unanswered probe 2 of 3; grades from best to worst are ok, unknown, warn, error](images/08_monitoring_drilldown.svg) + +Every check ends in one of four grades. The status of a host or an IOC is its worst check, and the reason is shown next to each check. + +| Grade | Colour | Meaning | +|---|---|---| +| ok | green | the check passed | +| unknown | grey | no data to judge; "we do not know", not "it is fine" | +| warn | orange | worth a look | +| error | red | the check failed | + +| Host check | ok | warn | error | +|---|---|---|---| +| Monitoring: age of the host's last report | under 25 h | 25 h to 7 days | over 7 days | +| Puppet: last Puppet run, at the time of that report | under 25 h | 25 h to 7 days | over 7 days | +| OS release | el8, el9 | el7 | older or not recognised | + +| IOC check | Not ok when | +|---|---| +| Online | `:TOD` does not answer (error) | +| Compliance | name pattern, unsupported EPICS version, clock more than 10 s off | +| Infrastructure | a module version that is not a release (warn) | +| Resources | suspended tasks, file descriptors over 80 %, memory over 90 % (warn) | +| Restarts | booted in the last 15 minutes, or two restarts within 24 h of uptime (warn) | + +- An IOC that does not answer is **error** while it is retried ("Unanswered probe N of 3"). After three unanswered probes in a row it is **OFFLINE**: it counts as error and is rechecked once per hour. It comes back by itself when a recheck answers or it boots again; **Probe** on IOC details checks it at once. +- A status that has not been refreshed for an hour turns **unknown**, with the time of the last probe. +- IOC states are collected for SwissFEL, SLS, HIPA, PROSCAN and CRYO. IOCs of other facilities (for example the SwissFEL endstations, TWLHA, ESI, office) stay unknown with the reason "not polled by any status sweep". That is a known gap, not a fault of the IOC. +- Hosts report once per day, so host checks are up to a day old; IOC states are refreshed every 2 minutes, gateway states every minute. + +### How do I find my IOC and see why it is not ok? + +1. Open **IOC details** and search for the IOC name, or click it in the IOC list or in the problem list of the Facilities overview. +2. Read the check that is not ok and its reason. If **Online** fails, the IOC does not answer on Channel Access. +3. Open the boot host in **Host details**: does the host itself report (Monitoring check)? Several red IOCs on one host point to the host or its network. +4. Read the IOC's log on the host with `journalctl` or in Kibana, see [Logs](#logs-kibana-and-journalctl). For **Restarts** warn, compare the boot time on IOC details with the journal around that time. + +Many IOCs of one facility red or unknown at the same moment is rarely many IOC failures: look at that facility's gateway on the Gateways page first. An IOC that is grey with "no sweep result since …" is a problem of gfa-monitoring, not of the IOC. + +### How do I see which IOCs run on a host? + +Open **Host details** and search for the host name. The page lists the IOCs on the host with their CPU and memory use, the three host checks, and links to **Grafana** (the host's metrics, last 6 hours) and **Puppetboard** (the host's last Puppet runs and their logs). A Puppet warn or error: open Puppetboard. An OS release warn: the host runs el7. + +### How do I check whether a PV is served, and by which IOC? + +Open **PV list** and search for the PV name. The result shows the IOC and the host that serve it. On that IOC's details page the PV list shows a one-time read of the current values, whether each PV is archived, and a link to its history in [Data Board](05_data_board.md). To watch several PVs live, use **PV monitoring**. + +### How do I check a CA gateway? + +Open **Gateways** and filter by facility or gateway name. The live status comes from the gateway's statistics PVs: ok when they answer, warn when fewer than half of the requested PVs are connected, unknown when the statistics PVs did not answer. Beamline gateways answer through `sls-cagw`. **Live statistics** on a row shows the gateway's counters (PVs connected, clients, rates, load). More on the gateways, and what to do when a channel is not reachable: [CA gateways](../Services/02_computingandboot.md#ca-gateways). + +## What does the work underneath + +gfa-monitoring is the view. The data comes from services underneath it, which you can also use directly: + +- **iocinfo** ([http://iocinfo.psi.ch](http://iocinfo.psi.ch)): every IOC sends its information to iocinfo when it starts: where and when it booted, the libraries it loaded and its records. iocinfo stores this and serves it through a REST API. gfa-monitoring imports its list of IOCs from there, and the `ioc search`, `ioc records`, `ioc libraries` and `ioc boots` commands ask it directly. The API is described at [http://iocinfo.psi.ch/swagger-ui.html](http://iocinfo.psi.ch/swagger-ui.html). If your own application needs this data, use the REST API, not the `ioc` command. +- **sysreport** (`sysreport.psi.ch`): the host information database. Each Linux host reports about itself once per day; gfa-monitoring imports these reports every hour. +- **Channel Access**: the live state of IOCs and gateways is read directly from their PVs. + +How iocinfo works in detail is in the Knowledge Center: [IT Infrastructure reference: iocinfo](../../3._Knowledge_Center/06_references/01_it_infrastructure.md#iocinfo). + +## IOC Utils: on the command line + +The `ioc` command gives you the same information in a terminal. It is installed on every Controls host. The basic commands: + +| Command | What it gives you | +|---|---| +| `ioc status` | whether your IOC runs; run it in the IOC's project folder | +| `ioc search ` | the IOCs whose name matches the pattern | +| `ioc records -i ` | the records of one IOC; `ioc records ` finds records by name | +| `ioc libraries ` | the libraries an IOC has loaded, with their versions | +| `ioc boots -i ` | the boot history of an IOC | +| `ioc duplicates` | record names that are defined on more than one IOC | +| `ioc shell ` | the shell of the running IOC | +| `ioc connect ` | the serial console of an IOC that is cabled to a port server | + +Patterns are regular expressions, and every command has its own `--help`. The full guide, with deploying and restarting an IOC, is on the [IOC Utils](01_ioc_utils.md) page. + +## Grafana: host metrics + +Host metrics (CPU, memory, disks, network) are collected by Telegraf on the Controls hosts and shown in Grafana at [https://metrics.psi.ch](https://metrics.psi.ch), dashboard **Linux GFA**. Use it for the history of a host's load. + +The fastest way to one host: open the host in gfa-monitoring **Host details** and click **Grafana**. The dashboard opens for that host, last 6 hours. Change the time range in the top right corner of Grafana. Directly in Grafana, choose the host in the dashboard's host selector by its full name, for example `.psi.ch`. + +## Logs: Kibana and journalctl + +Services and IOCs on Controls hosts write to the systemd journal. Only hosts of the `controls` Puppet environment (the RHEL9 Controls hosts) ship their journal to Elastic today; on all other hosts, including the Channel Access gateways, read the logs on the host with `journalctl`. + +### On the host: journalctl + +Follow one service live: + + journalctl -u -f + +Everything one service wrote in the last two hours: + + journalctl -u --since "2 hours ago" + +Only errors and worse since the last boot of the host: + + journalctl -b -p err + +More examples, and what your software must do so its messages end up there: [Controls IT Services: Logging](../Services/03_devops.md#on-the-host-journalctl). + +### Centrally: Kibana + +Open [https://kibana.psi.ch](https://kibana.psi.ch), switch to the Controls space (`data-controls`), open **Discover**, set the time range and filter on the host name, then on the service or the IOC name. Kibana is the place for searching across hosts and for the logs of a host that is down. You need a PSI account with access to the Controls space. Step-by-step: [Centrally: Elastic and Kibana](../Services/03_devops.md#centrally-elastic-and-kibana). + +## What is planned + +The platform strategy makes logging and monitoring a service of the Controls layer: standard agents on every standard machine, self-service dashboards in Elastic where your group queries its own data, and drift and failure detection that compares each machine with its declared standard. Details: [What is planned](../Services/03_devops.md#what-is-planned). + +## Support status & contact + +gfa-monitoring runs and can be used today, as a proof of concept. Shipping the journal to Elastic is switched on for the hosts of the `controls` Puppet environment. For questions ask your Controls contact ([SLS beamlines](../../4._Contacts_Support/BL_SLS.md), [SwissFEL endstations](../../4._Contacts_Support/BL_SF.md)) or see [Controls Services contacts](../../4._Contacts_Support/Service.md). + +## Further reading + +- [Controls IT Services](../Services/03_devops.md): Logging and Monitoring, what is collected and how +- [Controls IT Infrastructure](../Services/02_computingandboot.md), including the CA gateways +- [IOC Utils](01_ioc_utils.md) +- [Archiver Viewer](07_archiver_viewer.md) and [Data Board](05_data_board.md) +- [Troubleshooting IOCs](../../3._Knowledge_Center/04_troubleshooting/05_iocs.md) +- [IT Infrastructure reference: logging pipeline](../../3._Knowledge_Center/06_references/01_it_infrastructure.md) for Controls staff +- gfa-monitoring source and documentation: [gitea.psi.ch/controls_it/gfa_monitoring](https://gitea.psi.ch/controls_it/gfa_monitoring) (access to the repository is needed) diff --git a/docs/2._Services_Portfolio/Tools/images/08_monitoring_chooser.svg b/docs/2._Services_Portfolio/Tools/images/08_monitoring_chooser.svg new file mode 100644 index 00000000..540fbfc5 --- /dev/null +++ b/docs/2._Services_Portfolio/Tools/images/08_monitoring_chooser.svg @@ -0,0 +1,119 @@ + + Which monitoring tool for which question + Is my IOC running, why is it red: gfa-monitoring, IOC details. Is my host all right, which IOCs run on it: gfa-monitoring, Host details. Is a PV served and by which IOC, is a gateway all right: gfa-monitoring, PV list and Gateways. How loaded is a host, CPU and memory history: Grafana, dashboard Linux GFA on metrics.psi.ch. What did a service or IOC log: Kibana centrally, journalctl on the host. What was a PV doing in the past: the archiver viewer. + + + + + + + + + + + + YOUR QUESTION + OPEN + + + + + + Is my IOC running? + Why is it red? + + + + + + gfa-monitoring + IOC list, IOC details + + + + + + + Is my host all right? + Which IOCs run on it? + + + + + + gfa-monitoring + Host list, Host details + + + + + + + Is a PV served, and by which IOC? + Is a CA gateway all right? + + + + + + gfa-monitoring + PV list, PV monitoring, Gateways + + + + + + + How loaded is a host? + History of CPU and memory + + + + + + Grafana + “Linux GFA” on metrics.psi.ch + + + + + + + What did a service or IOC log? + across hosts, or on one host + + + + + + Kibana centrally + journalctl on the host + + + + + + + What was a PV doing in the past? + + + + + + Archiver viewer + archived history of PVs + + diff --git a/docs/2._Services_Portfolio/Tools/images/08_monitoring_drilldown.svg b/docs/2._Services_Portfolio/Tools/images/08_monitoring_drilldown.svg new file mode 100644 index 00000000..e34be4b1 --- /dev/null +++ b/docs/2._Services_Portfolio/Tools/images/08_monitoring_drilldown.svg @@ -0,0 +1,135 @@ + + From the facilities overview to the reason for a check + Step 1: the Facilities overview shows per facility how many IOCs are ok, warn and in error, and the latest problem IOCs. Step 2: the IOC list of that facility, searched for MY-IOC, shows each IOC with its status. Step 3: IOC details shows each check with its grade and the reason: Online error, Unanswered probe 2 of 3; Compliance ok; Infrastructure ok; Resources ok; Restarts ok. The status of an IOC or host is its worst check. Grades from best to worst: ok, unknown, warn, error. + + + + + + + + + + + + + + + + Facilities overview + + SLS + IOCs + + + + ok + warn + error + + latest problem IOCs + + MY-IOC + + + + + + + IOC list + + + MY-IOC + + Filtered: facility sls + + MY-IOC + + error + + + + ok + + + + + + IOC details + MY-IOC + + error + + Online + + error + Unanswered probe 2 of 3 + + Compliance + Infrastructure + Resources + Restarts + + + ok + ok + ok + ok + + + + + + + + + + + + + + + + + 1 + find the facility + + + + 2 + find the IOC + + + + 3 + read the reason + + + + + Grades, best to worst + + ok + < + unknown + < + warn + < + error + + The status of an IOC or host is its worst check. + diff --git a/docs/3._Knowledge_Center/01_Tutorials/02_python.md b/docs/3._Knowledge_Center/01_Tutorials/02_python.md index f183ae5c..e9b653fc 100644 --- a/docs/3._Knowledge_Center/01_Tutorials/02_python.md +++ b/docs/3._Knowledge_Center/01_Tutorials/02_python.md @@ -8,3 +8,748 @@ 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 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. + +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 + +You need: + +- An account on an LC machine (`-lc.psi.ch`) with RHEL9. The LC machines are the EPICS development and debugging environment that Controls IT operates, see [Development machines](../../2._Services_Portfolio/Services/02_computingandboot.md#development-machines). +- Basic Python: functions, modules, running a script. +- The name of a PV that you may read. Find one with the [`ioc` command](../../2._Services_Portfolio/Tools/01_ioc_utils.md#find-information): `ioc records --ioc --name-only --limit 5` lists records of an IOC you know, and `ioc records "MTEST-.*:TEMP.*" --facility sls` finds temperature records of SLS test IOCs. Below, replace `` with its name. + +Everything in this tutorial only reads. Do not write to PVs of a running machine while you learn; if you want to try writing, use your own test IOC. + +Log in to the LC machine and check Python with `python3 --version`. It prints `Python 3.9` and a patch level: Python 3.9 is the system `python3` on every RHEL9 host. pip installs packages from the PSI package index `pypi.psi.ch`, which Puppet configures for pip on PSI hosts; hosts in the machine networks reach it too. + +## Stage 1: one script + +Create a project folder with a virtual environment (venv), activate it, and upgrade pip. Work in your user folder under `/psi.ch`, not in your home directory; why is explained in [Where to keep the environment](../03_how_to/08_python_venv.md#where-to-keep-the-environment). The pip that a new venv brings on RHEL9 is too old to install the package of stage 2 in editable mode. + + mkdir -p /psi.ch//git/pvshow + cd /psi.ch//git/pvshow + python3 -m venv .venv + source .venv/bin/activate + pip install --upgrade pip + pip install pyepics + +Your prompt now starts with `(.venv)`. In every new shell, change into the project folder and run `source .venv/bin/activate` again. More about venvs is in [How-To: Manage Virtual Python Environments](../03_how_to/08_python_venv.md). + +pip installs the Channel Access library `pyepics` with `numpy` and `pyparsing`; pyepics brings its own copy of the Channel Access client library. Controls also installs Channel Access libraries for the system Python as RPMs (`python3-pyepics` on the Controls consoles and the SLS and SwissFEL LC machines, `python3-CaChannel` on the Controls consoles and the LC machines of SLS, SwissFEL, HIPA, CRYO and TWLHA), but a venv does not see system packages. This tutorial uses pyepics because it exists both on the package index and as a RHEL9 RPM. + +Create `read_pv.py`: + + """Read one EPICS PV over Channel Access and print its value.""" + import sys + + import epics + + if len(sys.argv) != 2: + sys.exit("usage: python3 read_pv.py ") + + name = sys.argv[1] + value = epics.caget(name, timeout=2.0) + if value is None: + sys.exit(f"{name}: no connection") + print(name, value) + +Run it with your PV, then with a PV that does not exist: + + python3 read_pv.py + python3 read_pv.py TUT:DOES-NOT-EXIST; echo $? + +The first prints the name and the value, for example ` 21.5`. The second waits two seconds, prints `cannot connect to TUT:DOES-NOT-EXIST` (from pyepics) and `TUT:DOES-NOT-EXIST: no connection`, and `echo $?` prints `1`: `sys.exit()` with a text writes it to stderr and ends with exit code 1. + +Channel Access finds a PV by searching for its name on the networks listed in the EPICS environment of the host. Puppet sets that environment up on the LC machines; on `hipa-lc9`, for example, the search goes to the HIPA CA gateway. `caq` shows what is set. If your PV does not connect, check its name and the output of `caq`. To reach PVs of another network, see [CA gateways](../../2._Services_Portfolio/Services/02_computingandboot.md#ca-gateways). + +Put the project under Git from the start. Create `.gitignore`, so the venv stays out of Git, and commit: + + printf '.venv/\n__pycache__/\n' > .gitignore + git init + git add . + git commit -m "Stage 1: one script that reads one PV" + +`git status` now reports a clean working tree, without `.venv`. In the following stages, commit at the end of each one in the same way. + +## Stage 2: a package with a command + +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, 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: + + git rm read_pv.py + mkdir pvshow + touch pvshow/__init__.py + +Create `pvshow/cli.py`: + + """pvshow: print the value and timestamp of an EPICS PV (read-only).""" + import argparse + import datetime + import sys + + import epics + + + def main(argv=None): + parser = argparse.ArgumentParser( + prog="pvshow", description="Print the value and timestamp of an EPICS PV.") + parser.add_argument("pv", metavar="PV", help="name of the PV to read") + parser.add_argument("--timeout", type=float, default=2.0, + help="seconds to wait for the PV (default: %(default)s)") + args = parser.parse_args(argv) + + pv = epics.PV(args.pv, form="time", auto_monitor=False) + value = None + if pv.wait_for_connection(timeout=args.timeout): + value = pv.get(timeout=args.timeout, use_monitor=False) + if value is None: + print(f"pvshow: {args.pv}: no connection within {args.timeout} s", file=sys.stderr) + return 1 + stamp = datetime.datetime.fromtimestamp(pv.timestamp) + print(args.pv, value, stamp.isoformat(sep=" ", timespec="milliseconds")) + return 0 + + + if __name__ == "__main__": + sys.exit(main()) + +`form="time"` asks the IOC for the timestamp with the value; `auto_monitor=False` reads once instead of subscribing to changes. `main()` returns the exit code: 0 when the PV was read, 1 when it did not connect; argparse itself exits with 2 when the arguments are wrong. + +Create `pyproject.toml` in the project folder: + + [build-system] + requires = ["setuptools>=64"] + build-backend = "setuptools.build_meta" + + [project] + name = "pvshow" + version = "0.1.0" + description = "Print the value and timestamp of EPICS PVs" + readme = "README.md" + requires-python = ">=3.9" + dependencies = ["pyepics"] + + [project.scripts] + pvshow = "pvshow.cli:main" + +Line by line: + +- `[build-system]`: pip builds the package with setuptools; version 64 or newer is needed for editable installs. +- `name`, `version`, `description`: the package name, its version, one line about it. +- `readme`: the file that describes the project. +- `requires-python`: the Python versions the tool supports; 3.9 is the system Python on RHEL9. +- `dependencies`: a list of all the packages the tool needs. List every one of them: installing the tool must be enough to make it work, without anyone installing something extra by hand afterwards. It must be a list: pip rejects `[project.dependencies]` written as a table with `` `project.dependencies` must be array ``. +- `[project.scripts]`: the command `pvshow` calls the function `main` in the module `pvshow.cli`. + +Create a short `README.md` (you complete it in stage 3), add `*.egg-info/` to `.gitignore` (pip writes the package metadata there), and install the project in editable mode, so the venv uses your source files directly: + + echo "# pvshow" > README.md + echo '*.egg-info/' >> .gitignore + pip install -e . + pvshow --help + +The install ends with `Successfully installed pvshow-0.1.0`, and `pvshow --help` prints: + + usage: pvshow [-h] [--timeout TIMEOUT] PV + + Print the value and timestamp of an EPICS PV. + + positional arguments: + PV name of the PV to read + + optional arguments: + -h, --help show this help message and exit + --timeout TIMEOUT seconds to wait for the PV (default: 2.0) + +Run it: + + pvshow + pvshow --timeout 1 TUT:DOES-NOT-EXIST; echo $? + +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 (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: + + """Read EPICS PVs over Channel Access. Read-only: nothing here writes.""" + import datetime + import logging + + import epics + + log = logging.getLogger(__name__) + + + def _result(name, value, timestamp): + if hasattr(value, "tolist"): # numpy arrays and numbers -> plain Python + value = value.tolist() + stamp = datetime.datetime.fromtimestamp(timestamp) + return {"name": name, "value": value, + "timestamp": stamp.isoformat(sep=" ", timespec="milliseconds")} + + + def read_pvs(names, timeout): + """Read each PV once. Return the results and the names that did not connect.""" + pvs = [epics.PV(name, form="time", auto_monitor=False) for name in names] + results, failed = [], [] + for pv in pvs: + value = None + if pv.wait_for_connection(timeout=timeout): + value = pv.get(timeout=timeout, use_monitor=False) + if value is None: + log.error("%s: no connection within %s s", pv.pvname, timeout) + failed.append(pv.pvname) + continue + results.append(_result(pv.pvname, value, pv.timestamp)) + return results, failed + + + def follow(names, on_update): + """Call on_update(result) on every change of the PVs. + + Returns the PV objects: keep a reference to them as long as you follow. + """ + def on_change(pvname=None, value=None, timestamp=None, **kwargs): + on_update(_result(pvname, value, timestamp)) + + def on_connection(pvname=None, conn=None, **kwargs): + if conn: + log.info("%s: connected", pvname) + else: + log.warning("%s: disconnected", pvname) + + return [epics.PV(name, form="time", callback=on_change, + connection_callback=on_connection) for name in names] + +`read_pvs()` creates all PV objects first, so their searches run at the same time. `follow()` subscribes to the PVs: pyepics calls `on_change` for every new value and `on_connection` when a PV connects or disconnects. + +Replace `pvshow/cli.py` with: + + """pvshow: print the value and timestamp of EPICS PVs (read-only).""" + import argparse + import json + import logging + import signal + import sys + import time + + from pvshow import reader + + log = logging.getLogger("pvshow") + + + def print_result(result, as_json): + if as_json: + print(json.dumps(result), flush=True) + else: + print(f"{result['name']:<30} {result['value']!s:>12} {result['timestamp']}", + flush=True) + + + def main(argv=None): + parser = argparse.ArgumentParser( + prog="pvshow", description="Print the value and timestamp of EPICS PVs.") + parser.add_argument("pvs", nargs="+", metavar="PV", help="name of a PV to read") + parser.add_argument("--timeout", type=float, default=2.0, + help="seconds to wait for each PV (default: %(default)s)") + parser.add_argument("--json", action="store_true", + help="print one JSON object per line") + parser.add_argument("--follow", action="store_true", + help="keep running and print every change, until Ctrl-C") + parser.add_argument("-v", "--verbose", action="store_true", help="log more detail") + args = parser.parse_args(argv) + + # Results go to stdout, log messages to stderr; under systemd both reach the journal. + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, + format="%(levelname)s %(message)s") + + if args.follow: + # systemd stops a service with SIGTERM: end as cleanly as with Ctrl-C. + signal.signal(signal.SIGTERM, signal.default_int_handler) + pvs = reader.follow(args.pvs, lambda result: print_result(result, args.json)) + log.info("following %d PV(s), stop with Ctrl-C", len(pvs)) + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + return 0 + + results, failed = reader.read_pvs(args.pvs, args.timeout) + for result in results: + print_result(result, args.json) + return 1 if failed else 0 + + + if __name__ == "__main__": + sys.exit(main()) + +Results go to stdout and log messages to stderr. When the tool runs as a systemd service, both reach the journal, which is collected centrally, see [Logging](../../2._Services_Portfolio/Services/03_devops.md#what-your-software-must-do). `flush=True` writes each line at once, also when stdout is not a terminal. systemd stops a service with SIGTERM; the signal handler ends `--follow` as cleanly as Ctrl-C. + +Create the folder `tests` with an empty `tests/__init__.py`: + + mkdir tests + touch tests/__init__.py + +Then create `tests/test_pvshow.py`. The tests replace `epics.PV` with a stand-in, so they run without an EPICS network: + + """Tests that run without an EPICS network: the Channel Access PV class is replaced.""" + import contextlib + import io + import json + import unittest + from unittest import mock + + from pvshow import cli, reader + + + class FakePV: + """Stands in for epics.PV: TEST:OK is connected, every other name is not.""" + values = {"TEST:OK": 21.5} + + def __init__(self, name, **kwargs): + self.pvname = name + self.timestamp = 0.0 + + def wait_for_connection(self, timeout=None): + return self.pvname in self.values + + def get(self, timeout=None, use_monitor=None): + return self.values.get(self.pvname) + + + @mock.patch("pvshow.reader.epics.PV", FakePV) + class ReadTest(unittest.TestCase): + + def test_read_connected_and_missing(self): + with self.assertLogs("pvshow.reader", level="ERROR"): + results, failed = reader.read_pvs(["TEST:OK", "TEST:MISSING"], timeout=0.1) + self.assertEqual([r["value"] for r in results], [21.5]) + self.assertEqual(failed, ["TEST:MISSING"]) + + def test_exit_code_and_json(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(cli.main(["--json", "TEST:OK"]), 0) + self.assertEqual(json.loads(out.getvalue())["name"], "TEST:OK") + with self.assertLogs("pvshow.reader", level="ERROR"): + self.assertEqual(cli.main(["--timeout", "0.1", "TEST:MISSING"]), 1) + + + if __name__ == "__main__": + unittest.main() + +Replace `README.md` with a description that states the requirements for each way of installing the tool, as every Controls Python tool does: + + # pvshow + + A small Python tool that reads EPICS PVs over Channel Access. It only reads, it never writes. + + ## Usage + + pvshow [--timeout SECONDS] [--json] [--follow] [-v] PV [PV ...] + + Reads each PV once and prints name, value and timestamp. `--json` prints one JSON object per + line. `--follow` keeps running and prints every change until Ctrl-C. Results go to stdout, log + messages to stderr. Exit code 0: all PVs read. 1: at least one PV did not connect. 2: wrong + arguments. + + ## Requirements + + - pip in a venv: Python 3.9 or newer, a current pip, and access to a package index for + `pyepics` (it pulls in `numpy` and `pyparsing`). On PSI hosts managed by Puppet, pip uses + the PSI package index `pypi.psi.ch`, also from the machine networks. + - RPM: the system `python3` and the RPM `python3-pyepics`. + + ## Install for development + + python3 -m venv .venv + source .venv/bin/activate + pip install --upgrade pip + pip install -e . + + ## Tests + + The tests replace the Channel Access calls and need no EPICS network: + + python -m unittest -v + +Give the stage a new version: in `pyproject.toml`, change `version = "0.1.0"` to `version = "0.2.0"`. Install again, run the tests, and try the new options: + + pip install -e . + python -m unittest -v + pvshow TUT:DOES-NOT-EXIST; echo $? + pvshow --json + pvshow --follow + +- The tests print `test_exit_code_and_json ... ok`, `test_read_connected_and_missing ... ok` and `OK`. +- With two PVs, the readable one is printed as a line, the other one logged as `ERROR TUT:DOES-NOT-EXIST: no connection within 2.0 s`, and the exit code is `1`. +- `--json` prints one JSON object per line, for example `{"name": "", "value": 21.5, "timestamp": "2026-11-25 14:05:23.377"}`. +- `--follow` logs `INFO following 1 PV(s), stop with Ctrl-C` and `INFO : connected`, then prints the current value and a new line for every change. Stop it with Ctrl-C; the exit code is `0`. + +Commit the stage. + +## 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. + +Let the tool report its version. In `pvshow/cli.py`, add the import and the option: + + from importlib.metadata import version + + parser.add_argument("--version", action="version", + version=f"%(prog)s {version('pvshow')}") + +The import goes with the other imports; the option after `--verbose`. In `pyproject.toml`, set `version = "1.0.0"`. Add the build output to `.gitignore`, install again and check: + + printf 'build/\ndist/\nRPMS/\n' >> .gitignore + pip install -e . + pvshow --version + +It prints `pvshow 1.0.0`. + +A wheel and a source archive for a package index. `build` creates both in `dist/`: + + pip install build + python -m build + +It ends with `Successfully built pvshow-1.0.0.tar.gz and pvshow-1.0.0-py3-none-any.whl`. `pip install dist/pvshow-1.0.0-py3-none-any.whl` installs the tool in any venv; to share it, upload the two files to the package index you use, for example with `twine upload --repository-url dist/*`. + +An RPM for RHEL9. For an RPM, every dependency must exist as a RHEL9 `python3-*` RPM, which the RPM declares with `Requires:` instead of bundling it (`pyepics` is `python3-pyepics`); the tool must install no files to absolute system paths; and pure Python is built as `noarch`. The rules are in [Delivering your own Python software](../../2._Services_Portfolio/Services/03_devops.md#delivering-your-own-python-software). The setuptools of the RHEL9 system Python (version 53) cannot read the `[project]` table, so the spec packages the wheel from `dist/` instead of building from the source. Create `pvshow.spec`: + + %define name pvshow + %define version 1.0.0 + %define release 0%{?dist} + + Name: %{name} + Version: %{version} + Release: %{release} + License: MIT + Summary: Print the value and timestamp of EPICS PVs + Source0: %{name}-%{version}-py3-none-any.whl + BuildArch: noarch + Requires: python3-pyepics + BuildRequires: python3-rpm-macros python3-pip + + %global source_date_epoch_from_changelog 0 + + %description + Print the value and timestamp of EPICS PVs. Read-only. + + # Build in this directory from the wheel in dist/ (python -m build); + # the RPM ends up in RPMS/noarch/. + %define _topdir %(pwd) + %define _sourcedir %{_topdir}/dist + %define _builddir %{_topdir} + + %prep + %{__mkdir_p} RPMS + + %install + %{__python3} -m pip install --root %{buildroot} --prefix %{_prefix} --no-deps --no-index --no-compile %{SOURCE0} + + %files + %{_bindir}/pvshow + %{python3_sitelib}/pvshow/ + %{python3_sitelib}/pvshow-%{version}.dist-info/ + +Put your project's licence in `License:`. On the LC machine, which has `rpm-build`, build the RPM after `python -m build` and list its content: + + rpmbuild -bb pvshow.spec + rpm -qlp RPMS/noarch/pvshow-1.0.0-0.el9.noarch.rpm + +The list contains `/usr/bin/pvshow` and the modules under `/usr/lib/python3.9/site-packages/pvshow/`. If `rpmbuild` stops with "Failed build dependencies", the host lacks one of the `BuildRequires` packages. + +Add a release section to `README.md`: + + ## Release + + Change the version in `pyproject.toml` and in `pvshow.spec` in the same commit, then tag + that commit with the bare version number, for example `git tag 1.0.0`. + +Commit, then publish the repository. In Gitea, create an empty repository `pvshow` (no README, no licence) in your group's organisation; [Use Git / Gitea](../03_how_to/12_git_gitea.md) explains the Gitea side. Push, and tag the release: + + git add . + git commit -m "Stage 4: version 1.0.0, packaging files" + git remote add origin https://gitea.psi.ch//pvshow.git + git push -u origin HEAD + git tag 1.0.0 + git push origin 1.0.0 + +The repository page in Gitea shows your files and the tag `1.0.0`. + +## 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; 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): 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 new file mode 100644 index 00000000..f77d83fd --- /dev/null +++ b/docs/3._Knowledge_Center/01_Tutorials/images/02_python_layout.svg @@ -0,0 +1,91 @@ + + Layout of the pvshow project and how the command finds its code + 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. + + + + + + + + + + + + + + + Project pvshow/ + + + pyproject.toml + metadata and the command + README.md + requirements per install route + .gitignore + keeps .venv/ and builds out of Git + pvshow.spec + RPM (stage 4) + Containerfile + container image (stage 5) + .containerignore + keeps files out of the image + pvshow/ + the package + __init__.py + makes pvshow a package + cli.py + main(): options and output + reader.py + reads PVs, follows changes + tests/ + test_pvshow.py, no EPICS needed + .gitea/workflows/ + Gitea Actions (stage 6) + ci.yml + on push and pull request + release.yml + on a version tag + .venv/ + virtual environment, not in Git + + + + + + + How the command + finds your code + + + in pyproject.toml + pvshow = "pvshow.cli:main" + + + pip install writes + + + a script on your PATH + .venv/bin/pvshow + + + which calls + + + in pvshow/cli.py + main() + + diff --git a/docs/3._Knowledge_Center/01_Tutorials/images/02_python_overview.svg b/docs/3._Knowledge_Center/01_Tutorials/images/02_python_overview.svg new file mode 100644 index 00000000..e5d74855 --- /dev/null +++ b/docs/3._Knowledge_Center/01_Tutorials/images/02_python_overview.svg @@ -0,0 +1,92 @@ + + The six stages of the pvshow tool + Stage 1, one script: read_pv.py, run with python3 read_pv.py. Stage 2, a package with a command: pyproject.toml and pvshow/cli.py, installed with pip install -e . and run as pvshow. Stages 1 and 2 are the base. Optional stages: 3, a tool you can rely on, with reader.py, tests, JSON, follow mode and logs, checked with python -m unittest; 4, ready to hand over, with a version and tag, wheel, sdist and an RPM spec, built with python -m build; 5, a container image from a Containerfile, built and pushed with podman; 6, Gitea Actions with ci.yml on every push and release.yml on a version tag. Take only the optional stages you need. The tool reaches Controls hosts with autodeploy. + + + + + + + + + + + + + + + + + + 1 + One script + read_pv.py + reads one PV and prints it + python3 read_pv.py <PV> + + + + + 2 + Package with a command + pyproject.toml pvshow/cli.py + options, timeout, exit codes + pip install -e . + + + + + 3 + A tool you can rely on + reader.py tests/ + JSON, follow mode, logs + python -m unittest + optional + + + + + 4 + Ready to hand over + version and tag 1.0.0 + wheel, sdist, RPM spec + python -m build + optional + + + + + 5 + A container image + Containerfile + pushed to gitea.psi.ch + podman build + optional + + + + + 6 + Automatic builds + ci.yml release.yml + tests on push, release on tag + .gitea/workflows/ + optional + + + Stages 1 and 2 are the base. Take only the optional stages your tool needs. + The tool reaches Controls hosts with autodeploy. + diff --git a/docs/3._Knowledge_Center/02_explanations/04_rundeck.md b/docs/3._Knowledge_Center/02_explanations/04_rundeck.md index 4eb764ab..6f3b87a8 100644 --- a/docs/3._Knowledge_Center/02_explanations/04_rundeck.md +++ b/docs/3._Knowledge_Center/02_explanations/04_rundeck.md @@ -67,7 +67,7 @@ Some actions also do work on cas-ansible-00 itself. `ioc.install` and `ioc.migra ## What can be run -Only the catalogued actions can be run. No `cas` code path accepts a playbook path or an ad-hoc command, and Rundeck denies ad-hoc execution. To add an action, you add a playbook and a catalogue entry, both reviewed in `cas_infrastructure`. +Only the catalogued actions can be run. No `cas` code path accepts a playbook path or an ad-hoc command, and Rundeck denies ad-hoc execution. To add an action, you add a playbook and a catalogue entry, both reviewed in `cas_infrastructure`. How to write, test and add one is in [How-To: Use Ansible](../03_how_to/17_ansible.md). | Action | What it does | Destructive | Check mode | |---|---|---|---| diff --git a/docs/3._Knowledge_Center/03_how_to/08_python_venv.md b/docs/3._Knowledge_Center/03_how_to/08_python_venv.md index 955f391d..52ee26e4 100644 --- a/docs/3._Knowledge_Center/03_how_to/08_python_venv.md +++ b/docs/3._Knowledge_Center/03_how_to/08_python_venv.md @@ -8,3 +8,195 @@ tags: --- # How-To: Manage Virtual Python Environments + +Outside the RPM packages, `pip` in a virtual environment (venv) is the main way to install a Python tool for the control system; pixi is an optional alternative. The policy and the requirements of each install route are in [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software). This page gives the commands. Do not build environments in your home on a console, see [Where to keep the environment](#where-to-keep-the-environment). + +## Where to keep the environment + +Decide this before you create anything. Where a Python tool lives depends on how critical it is for production and on who uses it: + +| The tool is | Where it lives | +| --- | --- | +| Critical for production | Installed locally on the console, as installed software: not a venv. See below. | +| A shared tool that other people use | A venv on a network drive (a PSI central storage mount under `/psi.ch`), or autodeployed to the [autodeploy](../../2._Services_Portfolio/Services/11_autodeploy.md) folders | +| A private tool, only for you | A venv in your user folder under `/psi.ch` | + +On the LC machines (`-lc`, `-lca`) and the other development machines, an environment belongs on a `/psi.ch` mount or in the autodeploy folders. **Never keep it locally in your home directory.** On consoles, homes are local to the machine and have limited space, so they should hold nothing at all. + +**Sharing is your responsibility.** Controls IT does not provide a facility for sharing tool installations in venvs. If you put a venv on a network drive for others, you look after it. When other people rely on your tool for their work and it has a problem, you are treated as the service provider for that tool. + +**Critical tools** are not run from a venv. They are installed locally on the consoles as part of the installed software: ask for the tool as an RPM, and the package is added to the package list of the host type, see [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software) and [Request a change to an existing machine](../../2._Services_Portfolio/Services/02_computingandboot.md#request-a-change-to-an-existing-machine). How to package your own tool as an RPM is in [How-To: Build and Deploy RPMs](07_build_deploy_rpms.md). How you package a tool (a package for the index, an RPM or another form) is your choice. + +The examples on this page keep environments in the folder `$VENVS`. Set it once to the place you chose, for example in your user folder under `/psi.ch`: + + export VENVS=/psi.ch//venvs + mkdir -p $VENVS + +On your own laptop or desktop, any folder will do. + +## Create and activate a virtual environment + +1. Create the environment. Use `$VENVS/` for a tool, or `.venv` inside a project directory: + + python3 -m venv $VENVS/mytool + +2. Activate it in your shell: + + source $VENVS/mytool/bin/activate + +3. Upgrade pip before you install anything: + + pip install --upgrade pip + + The pip that comes with a new venv on RHEL9 (Python 3.9) is too old: it installs packages with legacy `setup.py` data files, such as `cas-iocutils`, through `setup.py install` and fails with "Permission denied" on `/etc/bash_completion.d`. + +Check that it worked: `which python` and `which pip` print paths inside `$VENVS/mytool/bin/`, and `pip --version` shows the new version. `deactivate` leaves the environment. + +## Install a Controls Python tool + +Example: the IOC utilities (`ioc` command, package `cas-iocutils`). Cloning needs access to the Gitea repository. + +1. Clone the repository and change into it: + + git clone https://gitea.psi.ch/ctrl_packages/cas-iocutils.git + cd cas-iocutils + +2. Create and activate the environment and upgrade pip, as above: + + python3 -m venv $VENVS/iocutils + source $VENVS/iocutils/bin/activate + pip install --upgrade pip + +3. Install the tool from the checkout: + + pip install . + +Check that it worked: `which ioc` prints `$VENVS/iocutils/bin/ioc`, and `ioc --help` lists the commands. The dependencies (`PyYAML`, `requests`, `python-dateutil`, `click`) come from the package index. + +The commands of the tool are on the [IOC Utils](../../2._Services_Portfolio/Tools/01_ioc_utils.md) page. + +A tool must state all of its requirements properly, so that installing it is enough to make it work: every dependency is declared in the package itself (`dependencies` in `pyproject.toml`, `install_requires` in `setup.py`, `Requires:` in an RPM), and the install pulls them in. Nobody should have to install something extra by hand afterwards. Requirements that a package cannot pull in, such as the Python version or a system library, are stated in the README for each install route. + +## Install your own project for development + +In an editable install, the environment uses your source files directly, so a change in the code takes effect without reinstalling. + +1. In your project directory (with `pyproject.toml` or `setup.py`; keep the project itself on a `/psi.ch` mount too, not in your home directory), create and activate `.venv` and upgrade pip: + + cd ~/git/myproject + python3 -m venv .venv + source .venv/bin/activate + pip install --upgrade pip + +2. Install the project in editable mode: + + pip install -e . + +3. Add `.venv/` to the project's `.gitignore`. + +Check that it worked: `pip list --editable` shows your project with its location. What your project must provide to be installable this way is in [Delivering your own Python software](../../2._Services_Portfolio/Services/03_devops.md#delivering-your-own-python-software). + +## Reproduce the environment on another machine + +![What goes into Git and what is rebuilt: the project repository holds the source, pyproject.toml or setup.py and requirements.txt (or pixi.toml and pixi.lock); on each machine the virtual environment is recreated from them with python3 -m venv and pip install -r requirements.txt, never committed and never copied](images/08_venv_git_vs_rebuilt.svg) + +A venv cannot be moved or copied: its scripts start with the absolute path of its own interpreter, and Python on the target machine may differ. A moved venv fails with `bad interpreter: No such file or directory`. Recreate it instead. + +1. In the working environment, write the exact versions to a requirements file in your project and commit it to the project's Git repository. Leave out the project itself, which `pip freeze` lists with a local path: + + pip freeze --exclude myproject > requirements.txt + +2. On the other machine, clone the project, create and activate a new venv, upgrade pip, then install: + + pip install -r requirements.txt + pip install . + +Check that it worked: `pip freeze` on both machines prints the same versions. + +## Run it from a service or a timer + +A service, timer or cron job does not activate anything. Call the interpreter or the script inside the environment by its full path; this runs in the environment without activation: + + /home//venvs/mytool/bin/mytool --option + /home//venvs/mytool/bin/python /path/to/script.py + +In a systemd unit, put that path in `ExecStart=`, and the user in `User=` must be able to read the environment. Let the service write to stdout and stderr so its output reaches the journal, see [Logging](../../2._Services_Portfolio/Services/03_devops.md#what-your-software-must-do). How to run software as a service in a container is in [How-To: Use Containers](09_containers.md). The repository [example-systemd-service](https://gitea.psi.ch/controls_it/example-systemd-service) contains an example service unit, a timer that runs it every minute, and an Ansible playbook that installs both. + +## Start it from the Launcher + +The Launcher is the menu application on the consoles. Its menus are JSON files in your group's launcher configuration repository; [autodeploy](../../2._Services_Portfolio/Services/11_autodeploy.md) puts them into `///config/launcher` on every push. A menu item of type `cmd` runs a command. To start a Python program from a virtual environment, reference the Python executable in the environment's `bin` folder directly. Nothing has to be activated. + +1. Keep the environment where every console can reach it under the same path: a network drive or the autodeploy folders, see [Where to keep the environment](#where-to-keep-the-environment). +2. Test the exact command in a terminal on a console, with full paths: + + /psi.ch//venvs/mytool/bin/python -m mytool + +3. Add a `cmd` item to the `menu` list of your launcher menu file. Arguments go into the same `command` string: + + {"type": "cmd", "text": "My tool", "tip": "Start my tool", "command": "/psi.ch//venvs/mytool/bin/python -m mytool"} + + To run a script file instead of a module, give its full path after the interpreter: + + {"type": "cmd", "text": "My script", "tip": "", "command": "/psi.ch//venvs/mytool/bin/python /psi.ch//mytool/main.py"} + + If the tool installs a command of its own, you can reference that command in the same `bin` folder: `/psi.ch//venvs/mytool/bin/mytool`. + +4. Commit and push the menu file. Autodeploy updates the launcher folder; open the menu again and start the tool from it. + +Use full paths in the `command`: variables from your shell, such as `$VENVS`, do not exist in the Launcher. A tool started this way by other people is a shared tool, and you are its service provider, see [Where to keep the environment](#where-to-keep-the-environment). + +## Rebuild, remove, or change the Python version + +Remove an environment by deleting its directory; only services or timers that call it by path refer to it: + + deactivate + rm -rf $VENVS/mytool + +Rebuild one when it is broken or its requirements changed: remove it, create it again, upgrade pip and run `pip install -r requirements.txt`. + +A venv keeps the Python version that created it. To use another version, create a new environment with that interpreter: + + python3.12 -m venv $VENVS/mytool-py312 + +Which Python versions exist on RHEL9 hosts, according to the Puppet configuration: + +- `python3` is Python 3.9 on every RHEL9 host. RPM-delivered tools run with it. +- Hosts of the `controls` environment, including the Controls consoles, define no further version. +- Host types of the SLS, SwissFEL and HIPA environments with the package group `controls_devl`, among them their LC machines, install `python3.12-devel`, so `python3.12` is there. +- SLS beamline consoles and workstations install Python 3.11 and 3.12, the consoles also 3.14, with 3.9 as the default. + +Check what a host has with `ls /usr/bin/python3*`. The package lists per host type are in [Host Types and Packages](../06_references/04_host_types.md). + +## Alternative: pixi + +Use pixi when a project wants its Python version and all packages pinned in a manifest (`pixi.toml`) and a lock file (`pixi.lock`). `pixi` is installed on the Controls consoles; on other hosts and your own machine, check with `pixi --version`. The commands below are as documented by pixi: + +1. Create the project and add Python and the packages: + + pixi init myproject + cd myproject + pixi add "python=" + pixi add + pixi add --pypi + +2. Run commands in the environment: + + pixi run python + +3. Commit `pixi.toml` and `pixi.lock`. On another machine, `pixi install` in a checkout recreates the locked environment. + +pixi itself is provided and supported by AIT. Controls-curated standard pixi environments are planned, see [What Controls delivers](../../2._Services_Portfolio/Services/03_devops.md#what-controls-delivers). + +## What not to do + +- No `sudo pip install` into the system Python. A host changed by hand leaves its standard and is re-created. +- No conda. It is not supported, and the `paulscherrerinstitute` conda channel and the central conda Pythons are no longer maintained. The one exception: `ioc install` still builds the environment of a Python IOC with conda, see [IOC Utils](../../2._Services_Portfolio/Tools/01_ioc_utils.md) and [Python IOCs](../../2._Services_Portfolio/Services/03_devops.md#python-iocs). +- Do not copy a venv to another directory or machine, and do not commit it to Git. + +## Troubleshooting + +**`error: could not create '/etc/bash_completion.d': Permission denied`**, after `Using legacy 'setup.py install'`: pip in the environment is too old. Run `pip install --upgrade pip` in the activated environment and install again. + +**`command not found` after the install**: the environment is not active in this shell. Run `source $VENVS//bin/activate`, or call `$VENVS//bin/` by its path. After `pip install --user`, the scripts are in `~/.local/bin`, which must be on your `PATH`. + +**pip cannot reach the package index**: on Puppet-managed PSI hosts, `/etc/pip.conf` points pip to the PSI PyPI cache, `https://pypi.psi.ch/simple`, or `https://pypi-dmz.psi.ch/simple` in the DMZ, extranet and tier3 zones. `pip config list` shows the setting that applies. Hosts in the machine networks reach this index too, so `pip install` works there. If a host still cannot reach it, contact Controls IT. diff --git a/docs/3._Knowledge_Center/03_how_to/09_containers.md b/docs/3._Knowledge_Center/03_how_to/09_containers.md index aec75f4a..dcca6422 100644 --- a/docs/3._Knowledge_Center/03_how_to/09_containers.md +++ b/docs/3._Knowledge_Center/03_how_to/09_containers.md @@ -8,3 +8,232 @@ tags: --- # How-To: Use Containers + +To run your service in a container on Controls infrastructure, you package it as an image, publish the image to a registry, and a **container host** pulls it and runs it with Podman under systemd. This page is mostly about the first two steps; running the image is the short last section. + +![From the source repository to a container host: podman build turns the Containerfile and code into an image, podman tag gives it a version, podman push or Gitea Actions on a version tag publishes it to gitea.psi.ch, and the container host pulls it](images/09_containers_path.svg) + +## What is in place and what is planned + +| | Today | Planned | +|---|---|---| +| Build and registry | Podman on your machine or Gitea Actions; the Gitea registry `gitea.psi.ch` | | +| Container hosts | 12 hosts for web applications; containers run as root systemd units with `podman run` | Rootless Podman, Quadlet units, deployment through the catalogue | +| Soft IOCs | On soft IOC hosts, not in containers | Rootless Podman for soft IOCs that suit it | + +## 1. Package your application as an image + +### What goes into the image + +An image holds your code and everything it needs to run: the Python version, the packages from `requirements.txt`, system libraries. It does **not** hold passwords, tokens, host-specific settings or data. Those come from the host when the container starts (environment variables, mounted files and directories), so the same image runs unchanged on a test host and on the production host. + +One image runs one process. If your application needs a database or a cache, that is a separate container from its own image. + +A small project looks like this: + + myapp/ + Containerfile + .containerignore + requirements.txt + app.py + +Podman reads `Containerfile` or `Dockerfile`, and `.containerignore` or `.dockerignore`; use one of each. + +### The Containerfile + +A Containerfile for a Python service: + + FROM python:3.11-slim + WORKDIR /app + COPY requirements.txt . + RUN pip install --no-cache-dir -r requirements.txt + COPY app.py . + ENV PYTHONUNBUFFERED=1 + RUN useradd --create-home --uid 10001 appuser + USER appuser + EXPOSE 8000 + CMD ["python", "app.py"] + +Line by line: + +- `FROM python:3.11-slim` is the base image: Debian slim with Python 3.11. Name the Python version in the tag, never `python:latest`, so a rebuild next year gives the same Python. The `-slim` variant keeps the image small. +- `WORKDIR /app` is the directory the following lines and the program work in. +- `COPY requirements.txt .` and `RUN pip install --no-cache-dir -r requirements.txt` install the dependencies before the code is copied. Podman reuses this layer while `requirements.txt` is unchanged, so a code change rebuilds in seconds. `--no-cache-dir` keeps pip's download cache out of the image. Pin versions in `requirements.txt`. +- `COPY app.py .` copies the code. Copy only what the program needs at run time. +- `ENV PYTHONUNBUFFERED=1` makes Python write its output immediately. Without it, print output waits in a buffer and reaches the journal late or not at all when the process dies. +- `RUN useradd --create-home --uid 10001 appuser` and `USER appuser` run the program as an ordinary user with a fixed uid. A fixed uid lets you give a mounted data directory the right owner. +- `EXPOSE 8000` documents the port the program listens on; it opens nothing by itself. +- `CMD ["python", "app.py"]` starts the program. Use this list (exec) form: Python is then the main process of the container and receives the stop signal directly. The plain string form starts a shell in between, and the program is killed after the stop timeout instead of ending cleanly. + +Settings that change between hosts are read from environment variables in `app.py` (for example `os.environ["DATABASE_URL"]`), not written into the Containerfile. + +### The ignore file + +`.containerignore` keeps files out of the build. Everything not listed is sent to the build and may end up in the image through a `COPY`. From the [gfa-monitoring](https://gitea.psi.ch/controls_it/gfa_monitoring) project: + + .git + .venv + venv + __pycache__ + *.pyc + *.log + tests + .env + +`.env` is in the list because it holds secrets on a developer's machine. + +### Build and test locally + +1. Build the image. The container hosts are x86_64 machines; on a Mac with Apple Silicon Podman builds for arm64 unless you name the platform, and that image does not start on the host: + + podman build --platform linux/amd64 -t myapp:dev . + +2. Run it in the foreground; `Ctrl-C` stops it: + + podman run --rm --name myapp -p 8000:8000 myapp:dev + +3. In a second terminal, look at it while it runs: + + podman ps + podman logs -f myapp + +4. Check that it stops cleanly. `podman stop` sends the stop signal and kills the process after 10 seconds: + + time podman stop myapp + + If this takes 10 seconds, the program does not end on the stop signal: check the `CMD` form and that your program handles `SIGTERM`. + +5. Check the size in the SIZE column: + + podman image ls myapp + +Check that it worked: the application answers on `http://localhost:8000` (or prints its output), its messages appear in `podman logs`, and `podman stop` returns at once. + +## 2. Publish the image to the registry + +Controls images are published to the container registry built into Gitea, `gitea.psi.ch`. + +### Name and tags + +A published image is named after the Gitea organisation and repository it belongs to, in lower case: + + gitea.psi.ch//: + +One image gets several tags. The gfa-monitoring release workflow gives each release: + +| Tag | Example | Meaning | +|---|---|---| +| full version | `1.4.0` | This exact release. Never moves. Use it to deploy. | +| minor version | `1.4` | Moves to the newest `1.4.x`. | +| `latest` | `latest` | Moves to the newest release. | +| commit | `sha-3f2a9c1` | The commit the image was built from. | + +Raise the version for every image you publish: the last number for a fix, the middle one for a new function, the first one for a change that needs a new configuration or breaks something for its users. Do not push a published full version again with different content. + +### Log in + +1. In Gitea, open **Settings → Applications → Access Tokens** and create a token. Scope `write:package` to push (it includes reading), `read:package` for a machine that only pulls. +2. Log in and give the token when asked for the password: + + podman login gitea.psi.ch -u + + In a script, pass the token on standard input with `--password-stdin` so it does not appear in the command line. + +### Push by hand + + podman tag myapp:dev gitea.psi.ch//myapp:1.0.0 + podman push gitea.psi.ch//myapp:1.0.0 + +Push further tags of the same image the same way (`1.0`, `latest`). + +### Publish automatically on a version tag + +The gfa-monitoring repository builds and publishes its image in Gitea Actions whenever a version tag is pushed (`.gitea/workflows/release.yml`). It works in two jobs: + +1. **guard** checks that the tag points at a commit on `master`, because a tag can be pushed from any commit. A tag elsewhere is refused. +2. **publish** logs in to `gitea.psi.ch` with a token from the repository secret `REGISTRY_TOKEN`, derives the four tags from the version tag, builds for `linux/amd64` and pushes. + +The built-in token of Gitea Actions has no package scope, so the push needs a token of its own: create one with `write:package` and store it in the repository under **Settings → Actions → Secrets** as `REGISTRY_TOKEN`. The publish job, trimmed to what a Python service needs: + + on: + push: + tags: ["v*"] + jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: gitea.psi.ch + username: ${{ gitea.actor }} + password: ${{ secrets.REGISTRY_TOKEN }} + - id: meta + uses: docker/metadata-action@v5 + with: + images: gitea.psi.ch/${{ gitea.repository }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=sha,prefix=sha-,format=short + type=raw,value=latest + - uses: docker/build-push-action@v5 + with: + context: . + push: true + platforms: linux/amd64 + tags: ${{ steps.meta.outputs.tags }} + +Copy the guard job from the gfa-monitoring workflow as well if releases must come from `master` only. A release is then: + + git tag -a v1.0.0 -m "Release 1.0.0" + git push origin v1.0.0 + +### Check the published image + +1. In Gitea, open the organisation and its **Packages** tab (`https://gitea.psi.ch//-/packages`). The image is listed with its tags. +2. On another machine, pull it and start it once: + + podman pull gitea.psi.ch//myapp:1.0.0 + podman run --rm gitea.psi.ch//myapp:1.0.0 + +### When build or push fails + +- **`unauthorized` on push or pull**: not logged in, or the token lacks `write:package` / `read:package`. In Gitea Actions: `REGISTRY_TOKEN` is not set; the built-in token cannot push. +- **`exec format error` when the container starts on the host**: the image was built for arm64. Build with `--platform linux/amd64`. +- **`invalid reference format`**: the image name contains upper-case letters. Use lower case. +- **Image too large, slow push and pull**: use a `-slim` base, `--no-cache-dir`, and a `.containerignore` that keeps `.git`, virtual environments and data out. +- **`(already exists)` when you push the Git tag `v1.0.0`**: that version has been released already. Raise the version. + +## 3. Run it on a container host + +A container host is a Controls server that runs containers; you get one by [requesting a server](../../2._Services_Portfolio/Services/02_computingandboot.md#how-to-request-a-machine-or-a-change) for your service. The pattern in use today: + +- Each container is a systemd unit that pulls the image and starts it with `podman run`, so it starts at boot and restarts when it stops. +- The unit file is kept in Git; Puppet installs it in `/etc/systemd/system/` through a [change to the machine](../../2._Services_Portfolio/Services/02_computingandboot.md#request-a-change-to-an-existing-machine). Nothing is started by hand. +- Ports with `-p`, data that must survive in a host directory with `-v`, secrets in an environment file on the host (`--env-file`), never in Git or the image. +- The unit names a full version tag. Updating is a new tag in the unit and a restart; rolling back is the previous tag. +- The output goes to the journal and from there to Elastic: read it with `journalctl -u myapp` on the host and in Kibana ([Logging](../../2._Services_Portfolio/Services/03_devops.md#logging)). + +A compact example unit: + + [Unit] + Description=myapp + After=network-online.target + + [Service] + ExecStartPre=-/usr/bin/podman rm -f myapp + ExecStartPre=/usr/bin/podman pull gitea.psi.ch//myapp:1.0.0 + ExecStart=/usr/bin/podman run --rm --name myapp --init -p 8000:8000 \ + -v /data/myapp:/app/data --env-file /etc/myapp/myapp.env \ + gitea.psi.ch//myapp:1.0.0 + ExecStop=/usr/bin/podman stop myapp + Restart=always + + [Install] + WantedBy=multi-user.target + +Today these units run as root. Planned: rootless Podman under a service account, Quadlet unit files, and deployment through the catalogue (`cas container deploy`, not implemented yet). Controls IT owns the container host, your group owns the image and what runs in it ([who is responsible for what](../../2._Services_Portfolio/Services/02_computingandboot.md#who-is-responsible-for-what)). + +Soft IOCs are planned to run as rootless Podman containers under systemd where they suit it, once Channel Access in containers has been validated. Until then they run on [soft IOC hosts](../../2._Services_Portfolio/Services/02_computingandboot.md#soft-ioc-hosts-and-hardware-bound-ioc-hosts). diff --git a/docs/3._Knowledge_Center/03_how_to/17_ansible.md b/docs/3._Knowledge_Center/03_how_to/17_ansible.md new file mode 100644 index 00000000..8a1726d6 --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/17_ansible.md @@ -0,0 +1,269 @@ +--- +title: Use Ansible +tags: + - SLS + - PROSCAN + - SwissFEL + - HIPA +--- + +# How-To: Use Ansible + +To automate a task you keep doing by hand on several Controls machines, write it as an Ansible playbook, keep it in Git, and test it with check mode on one test host. Once reviewed, it becomes an action in the catalogue and lives in [Rundeck](../02_explanations/04_rundeck.md): it runs from one place, with access control and a record of every run. + +![From a playbook to a Rundeck job: write the playbook in Git, test it with ansible-playbook --check --diff on one test host, review it in a pull request in cas_infrastructure, add a catalogue entry, configure_rundeck.yml imports the job cas/ on cas-ansible-00, and cas run starts it on the hosts as cas-ansible, recorded in the execution history](images/17_ansible_path.svg) + +## Why Rundeck + +- **Everyone in Controls can run an action without knowing anything about it.** Rundeck is the interface that you, as the developer, offer to Controls and to Pikett for interacting with your system. Whoever starts an action picks it and the hosts. They do not need to know Ansible or the playbook behind it. +- **Automation for Pikett.** A procedure that on-call staff need becomes an action they start, instead of instructions they follow by hand ([Pikett access and support](../../2._Services_Portfolio/Services/02_computingandboot.md#pikett-access-and-support)). +- **One central place to see everything that is done on hosts.** Every run is recorded: who started which action, on which hosts, when, and how it ended. + +How the instance works is explained in [Rundeck: Running Tasks on Hosts](../02_explanations/04_rundeck.md). + +## What is in place and what is planned + +| | Today | Planned | +|---|---|---| +| Write and test | Ansible is installed on all Controls machines; you run playbooks as yourself | | +| Catalogue | `catalog.yaml` in `cas_infrastructure`, 11 actions; a new action is a pull request reviewed by Controls IT | A staging and canary step for catalogue changes | +| Into Rundeck | Whoever merges runs `configure_rundeck.yml` by hand | A merge pipeline that imports the jobs | +| Who runs actions | Everyone in Controls, in Rundeck; from the command line, Controls IT through `cas` on cas-ansible-00 | Expert groups from other groups: one pilot group first, then all, on their own hosts, with their Kerberos login | +| Login on the hosts | One shared account, `cas-ansible`, on hosts with the Puppet class `cas_access` | Per-user SSH certificates | + +## Ansible or Puppet? + +Ansible on Controls machines is for operations that act **now**. The configuration of a machine is Puppet's job. + +| You want to | Use | +|---|---| +| Restart, deploy, register, check, report something now | An Ansible playbook, then a catalogue action | +| Install or remove a package, add a mount, give someone power-user rights | A pull request on the host's hiera data; Puppet applies it ([request a change](../../2._Services_Portfolio/Services/02_computingandboot.md#request-a-change-to-an-existing-machine)) | + +A playbook that installs packages or edits configuration files on a Puppet-managed host fights Puppet: the next Puppet run puts the old state back. + +## 1. Write a playbook + +### Where you can run Ansible + +Ansible is installed on all Controls machines; Rundeck on cas-ansible-00 runs Ansible 9. Use only modules from `ansible.builtin` unless you have agreed with Controls IT that a collection is added on cas-ansible-00. + +### A read-only playbook + +A catalogue playbook is one file at the root of `cas_infrastructure`, next to `catalog.yaml`, `ansible.cfg` and `inventory.py`; its inputs are variables. Start with something that changes nothing. This is the playbook behind the catalogue action `epics.status`, `install_status.yml`: + + --- + # Read-only: report whether an EPICS base package is installed on the + # targeted hosts. + # + # ansible-playbook install_status.yml --limit my-host.psi.ch -e epics_base=epics-base-7.0.8 + - name: Install Status + hosts: all + gather_facts: false + tasks: + - name: Check the request + ansible.builtin.assert: + that: epics_base is defined and epics_base | length > 0 + fail_msg: "epics_base (an RPM package name) is required" + + - name: Check EPICS base package status + ansible.builtin.package_facts: + manager: auto + + - name: Report status + ansible.builtin.debug: + msg: "EPICS base package {{ epics_base }} is {{ 'installed' if epics_base in ansible_facts.packages else 'not installed' }}" + +What makes it a good model: it checks its input first and fails with a clear message, it reads the package database with a module instead of piping `rpm -qa` through `grep`, it needs no root, and `gather_facts: false` saves a round trip per host. + +### A playbook that changes something + +An example, not in the catalogue: restart one systemd service and check that it stays up. Save it as `service_restart.yml`: + + --- + # Restart one systemd service on the targeted hosts and check that it stays up. + # ansible-playbook service_restart.yml -i , -e service_unit= --check --diff + - name: Restart a service + hosts: all + gather_facts: false + vars: + service_unit: "" + service_settle_seconds: 10 + tasks: + - name: Check the request + ansible.builtin.assert: + that: service_unit is match('^[A-Za-z0-9@._-]{1,128}[.]service$') + fail_msg: "service_unit must be a systemd service name, e.g. myapp.service" + + - name: Restart the service + ansible.builtin.systemd: + name: "{{ service_unit }}" + state: restarted + become: true + + - name: Give it time to start + ansible.builtin.pause: + seconds: "{{ service_settle_seconds }}" + when: not ansible_check_mode + + - name: Read its state + ansible.builtin.command: systemctl is-active {{ service_unit }} + register: service_state + changed_when: false + check_mode: false + failed_when: service_state.stdout != "active" and not ansible_check_mode + + - name: Report + ansible.builtin.debug: + msg: "{{ service_unit }} is {{ service_state.stdout }}" + +### The rules that matter here + +- **Idempotent.** Running it twice gives the same result. Describe the state you want (`state: started`, `state: absent`), not the steps to get there. A restart is the exception that is meant to act every time. +- **Modules instead of `shell`.** Use `ansible.builtin.systemd`, `package_facts`, `copy`, `file`, `lineinfile` where one exists. They report "changed" correctly and support check mode; `command` and `shell` do neither by themselves. +- **Make `--check` mean something.** A `command` task is skipped in check mode. If it only reads, give it `check_mode: false` and `changed_when: false`, as the "Read its state" task does. Skip waits and follow-up checks with `when: not ansible_check_mode`. +- **Set `changed_when` and `failed_when`** whenever a command's exit code does not mean what Ansible assumes. The catalogue's Puppet run treats exit code 2 ("changes applied") as success: `changed_when: puppet_result.rc == 2`, `failed_when: puppet_result.rc != 0 and puppet_result.rc != 2`. +- **Variables with defaults, checked with `assert`.** Every input has a default in `vars:` and is checked before anything happens. A missing parameter then stops the run with your message, not halfway through. +- **No secrets in Git**, not in the playbook, not in `vars:`, not in a comment. A credential the action needs is stored on cas-ansible-00 and reaches the job from there (see step 4). +- **`hosts: all`** in a catalogue playbook. The targets come from `--limit`, which `cas` builds from the inventory. +- **`become: true` only on the tasks that need root.** A task that reads, reports or waits runs as the login account. +- **No `vars_prompt`.** Rundeck runs playbooks with standard input closed; a prompt fails at once. Confirmation comes from the catalogue (`destructive: true`). + +## 2. Run it by hand against one test host + +Test as yourself, on a machine where your account has sudo, for example your group's [development machine](../../2._Services_Portfolio/Services/02_computingandboot.md#development-machines). Never test against a production IOC host, a gateway or a console. + +1. Check the syntax; this needs no host: + + ansible-playbook --syntax-check -i localhost, service_restart.yml + +2. Run it in check mode on the one host. The trailing comma after the host name makes it a one-host inventory; `-K` asks for your sudo password: + + ansible-playbook service_restart.yml -i .psi.ch, -K \ + -e service_unit=myapp.service --check --diff + +3. Read the result. Each task prints `ok` (nothing to do), `changed` (would change, or changed), `skipping` or `failed`; the `PLAY RECAP` line counts them per host. In check mode "Restart the service" should say `changed` and nothing should fail. A misspelt unit fails here, before anything was restarted. +4. Run it for real: + + ansible-playbook service_restart.yml -i .psi.ch, -K -e service_unit=myapp.service + +Check that it worked: the real run ends with `failed=0` and reports `myapp.service is active`, and on the host `systemctl status myapp.service` shows a start time from your run. For a playbook that sets a state rather than restarting, run it a second time: it must report `changed=0`. + +Your own account is only for testing. Through Rundeck the same playbook logs in as `cas-ansible`, an account the Puppet class `cas_access` creates on each host together with its sudo rule and the authorised key ([how a task runs](../02_explanations/04_rundeck.md#how-a-task-runs)). + +## 3. Put it in Git and have it reviewed + +Catalogue playbooks live in [cas_infrastructure](https://gitea.psi.ch/controls_it/cas_infrastructure), a private repository: ask Controls IT for access. Work on a branch and open a pull request against `main` ([working with Git and Gitea](12_git_gitea.md)). The pull request holds the playbook and its catalogue entry (step 4) together. + +The repository's CI runs on every pull request: the tests (`pytest`) and `ansible-playbook --syntax-check` for each playbook in a list in `.gitea/workflows/ci.yml`. Add your playbook to that list. To run the tests yourself first: + + pip install -e cas-core -e cas-cli -e cas-server pytest + pytest -q + +What the reviewer looks for: + +- the rules above: idempotent, check mode meaningful, inputs checked, no secrets, `become` only where needed; +- that the description says truthfully what the action changes and what it interrupts; +- that each parameter's `pattern` lets through only what the playbook can handle; +- that it is an operation, not configuration that belongs in hiera. + +Check that it worked: CI is green on the pull request, and a reviewer from Controls IT has approved it. + +## 4. Make it an action in the catalogue + +### The catalogue entry + +Add the entry to `catalog.yaml` **and** to its copy `cas-core/cas_core/data/catalog.yaml`; a test fails while the two differ. The entry for the example, modelled on `epics.status` and `machine.restart`: + + - name: service.restart + title: Restart a service + summary: Restart one systemd service on the targeted hosts and check that it stays up. + description: > + Restarts the named systemd service on every targeted host, waits + ten seconds and fails when it is not active then. It interrupts the + service. Check mode reports which hosts would restart it and changes + nothing. + playbook: service_restart.yml + hosts: all + targetable: true + supports_check: true + destructive: true + risk: high + parameters: + - name: unit + extra_var: service_unit + description: The systemd service to restart, e.g. myapp.service. + required_when_live: true + pattern: '^[A-Za-z0-9@._-]{1,128}[.]service$' + secret: false + requires: + - SSH reachability of the targets with privilege escalation. + - The cas_access Puppet class applied on the targets. + +Field by field: + +- `name`: the action id, `.`. It becomes the Rundeck job `cas/service.restart` with the uuid `cas-service-restart`. Renaming it later breaks everyone who calls it. +- `title`, `summary`, `description`: what `cas catalog` and `cas catalog show service.restart` print, and the job description in Rundeck. +- `playbook`: the file, relative to `catalog.yaml`. That directory is also where the playbook runs, so its `ansible.cfg` applies. +- `hosts`: the play's own `hosts:` value. `targetable: false` only for a play on localhost that ignores `--on`. +- `supports_check`: `true` only if `--check` is meaningful. Without it the job has no check option. +- `destructive`: `true` makes `cas` ask for confirmation (or `--yes`), and the job description starts with `DESTRUCTIVE`. +- `risk`: `low`, `medium` or `high`; without it, `high` for destructive actions, otherwise `low`. +- `parameters`: each becomes a job option and reaches the playbook as the variable `extra_var`. `required_when_live` makes the option required in Rundeck. Rundeck refuses a value that does not match `pattern`, so give every parameter one, anchored with `^…$`. +- `secret: true` with `storage_path: keys/cas/…`: a credential Rundeck reads from its key storage. It is never logged and never typed by the caller. The owner stores it on cas-ansible-00 by hand. +- `requires`: prerequisites in plain words, shown before a run so that a failure can be explained. +- `portal`: leave it out; Controls IT sets it. + +### Into Rundeck + +After the merge, Controls IT runs, from an up-to-date checkout of `main`: + + ansible-playbook -i rundeck/inventory rundeck/configure_rundeck.yml + +It copies the checkout to `/opt/cas_infrastructure` on cas-ansible-00, generates one job per catalogue action, imports them (updating existing ones in place) and deletes jobs the catalogue no longer has ([keeping it current](../02_explanations/04_rundeck.md#keeping-it-current)). Rundeck runs exactly that copy: a change that is merged but not imported does not run yet. + +### Run it + +Everyone in Controls can start the action in Rundeck: open the job `cas/` in the project `cas`, fill in the hosts and the parameters, and run it. From the command line, today on cas-ansible-00 as a member of `cas-operators` (`sudo cas …`), with `cas` pointed at Rundeck ([using it](../02_explanations/04_rundeck.md#using-it)): + + cas catalog show service.restart + cas run service.restart --on --param unit=myapp.service --check --follow + cas run service.restart --on --param unit=myapp.service --follow + +Check that it worked: the job log starts with the Rundeck execution number and a permalink, `http://cas-ansible-00.psi.ch:4440/project/cas/execution/show/`. Open it: the run is in the execution history of job `cas/service.restart`, with its output and who started it. `cas job show ` shows the same record. + +### Who may do what + +| | Today | Planned | +|---|---|---| +| Propose an action | Anyone with access to `cas_infrastructure`, by pull request | | +| Review, merge, import into Rundeck | Controls IT | Import by a merge pipeline | +| Run actions | Everyone in Controls, including Pikett, in Rundeck. From the command line: members of `cas-operators` on cas-ansible-00, through `sudo cas` | Expert groups through `cas` and the planned web hub, each on its own hosts, decided by LDAP and Unix groups ([who uses it](../02_explanations/04_rundeck.md#who-uses-it)) | + +## 5. Keep it healthy + +- **Every change is a pull request.** Change the playbook and the entry together, then have the jobs imported again. +- **Keep the `name`.** Add a parameter with a default rather than changing what an existing one means; callers keep working. +- **Remove an action** by deleting its entry from both copies of `catalog.yaml` and its playbook. The next `configure_rundeck.yml` deletes the job. +- **Read your action's runs** in Rundeck now and then. A job that fails on some hosts every time usually points at one of these: + - a host without `cas_access`, or whose `cas_access::control_nodes` does not list cas-ansible-00: `Permission denied (publickey)`, nothing changed; + - a target `cas` cannot find in the inventory: `'' is neither an inventoried host, a group, nor a matching pattern`; + - a value that does not match the parameter's `pattern`: Rundeck refuses the run before Ansible starts. + +## What not to do + +- Do not run a playbook by hand against production hosts. That is what the catalogue is for: one place, one record. +- Do not write playbooks that install packages or change files Puppet manages. That is a hiera change. +- Do not set `host_key_checking = False` in a new repository's `ansible.cfg`. It accepts any machine that answers under the host's name. +- Do not use `state: present` for software you mean to update: it installs once and never upgrades. Use `state: latest` deliberately, or pin a version. +- Do not copy older playbooks from other repositories without reading them. Some are out of date or wrong. +- Do not leave a job's host list empty in the Rundeck web interface. An empty limit means the play's `hosts: all`. + +## When it fails + +- **`Permission denied (publickey)` on the first task:** the host has no `cas_access`, or cas-ansible-00 is not in its `control_nodes`. A hiera pull request and a Puppet run on the host fix it; `cas access verify --on ` tells which link is broken. +- **`sudo: a password is required`:** the host's sudo rule for `cas-ansible` is missing; again `cas_access`. +- **`playbook … could not be found`:** the jobs were imported, but the copy on cas-ansible-00 is older. Run `configure_rundeck.yml` again from an up-to-date checkout. +- **`couldn't resolve module/action`:** the playbook uses a collection that is not installed on cas-ansible-00. Use `ansible.builtin`, or ask Controls IT to add it. +- **Check mode says `ok` but the real run changes things:** a `command` or `shell` task without `check_mode: false` was skipped in check mode. +- **Exit code `1` from `cas` with no detail:** Rundeck does not pass Ansible's own exit code on; read the job log. diff --git a/docs/3._Knowledge_Center/03_how_to/images/08_venv_git_vs_rebuilt.svg b/docs/3._Knowledge_Center/03_how_to/images/08_venv_git_vs_rebuilt.svg new file mode 100644 index 00000000..f0361bd8 --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/images/08_venv_git_vs_rebuilt.svg @@ -0,0 +1,60 @@ + + What goes into Git and what is rebuilt + Left: the project repository in Gitea holds the source code, pyproject.toml or setup.py, and requirements.txt from pip freeze, or for pixi the files pixi.toml and pixi.lock. Right: on each machine the virtual environment, for example $VENVS/mytool or .venv in the project directory, is created from these files with python3 -m venv and pip install -r requirements.txt. The environment is never committed and never copied to another machine; it is recreated. + + + + + + + + + + + + + + + + In Git + your project repository in Gitea + source code + pyproject.tomlorsetup.py + requirements.txtfrom pip freeze + + with pixi instead: + pixi.tomlandpixi.lock + + + + + recreate + on each machine + + + + + + Rebuilt, not in Git + the virtual environment + $VENVS/mytool + or .venv in the project directory + + python3 -m venv ... + pip install -r requirements.txt + + never committed, never copied + + diff --git a/docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg b/docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg new file mode 100644 index 00000000..ec853592 --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/images/09_containers_path.svg @@ -0,0 +1,126 @@ + + Build and publish a container image + Step 1, source repository: Containerfile, .containerignore, requirements.txt and code in Git. Step 2, build: podman build --platform linux/amd64 makes the image. Step 3, tag: the image gets the name gitea.psi.ch/org/myapp with the tags 1.0.0, 1.0, latest and sha-commit. Step 4, push to the registry gitea.psi.ch, by hand with podman push or by Gitea Actions on a version tag v1.0.0. Last, a container host pulls the image and runs it with Podman under systemd. + + + + + + + + + + + + + BUILD AND PUBLISH + RUN + + + + + + + + 1 + 2 + 3 + 4 + + + + + + + + Source + Git repository + + Containerfile + .containerignore + requirements.txt + app.py + No secrets, + no host settings + + + + + + + + Build + Code + dependencies + become an image + + podman build + --platform + linux/amd64 + Test locally: + podman run + podman logs + podman stop + + + + + + + + Tag + Name and versions + gitea.psi.ch/ + <org>/myapp + + :1.0.0 + :1.0 + :latest + :sha-<commit> + + + + + + + + Push + Token: write:package + + By hand + podman push + + Gitea Actions + on git tag v1.0.0 + + Registry + gitea.psi.ch + + + + + + + + Container host + podman pull + podman run + in a systemd unit + Output goes to + the journal + + diff --git a/docs/3._Knowledge_Center/03_how_to/images/17_ansible_path.svg b/docs/3._Knowledge_Center/03_how_to/images/17_ansible_path.svg new file mode 100644 index 00000000..e26105e8 --- /dev/null +++ b/docs/3._Knowledge_Center/03_how_to/images/17_ansible_path.svg @@ -0,0 +1,139 @@ + + From a playbook to a Rundeck job + Step 1, write: a playbook in Git with defaults for its variables and checked inputs, no secrets, modules instead of shell. Step 2, test: ansible-playbook with --limit on one test host, first with --check --diff, as yourself with sudo on that host. Step 3, review: a pull request in cas_infrastructure; CI runs the tests and a syntax check; Controls IT reviews. Step 4, catalogue: an action entry in catalog.yaml with its parameters and their patterns. Step 5, Rundeck: configure_rundeck.yml on cas-ansible-00 imports the job cas/action. Last, on the hosts: cas run action --on host; the job logs in as cas-ansible and every run is in the execution history. + + + + + + + + + + + + + + WRITE, TEST, REVIEW + LIVES IN RUNDECK + + + + + + + + + 1 + 2 + 3 + 4 + 5 + + + + + + + + Write + Playbook in Git + + myaction.yml + vars: defaults + assert inputs + No secrets; + modules, not shell + + + + + + + + Test + One test host + + ansible-playbook + --limit <host> + --check --diff + Your account, + sudo on that host + + + + + + + + Review + Pull request + + cas_infrastructure + CI: tests and + syntax check + Controls IT + reviews and merges + + + + + + + + Catalogue + Action entry + + catalog.yaml + name: res.verb + parameters + pattern + Only catalogued + actions can run + + + + + + + + Rundeck job + cas/<action> + + configure_ + rundeck.yml + imports the jobs + + cas-ansible-00 + + + + + + + + On the hosts + cas run + <action> + --on <host> + Logs in as + cas-ansible + Every run in the + execution history + + diff --git a/docs/3._Knowledge_Center/06_references/01_it_infrastructure.md b/docs/3._Knowledge_Center/06_references/01_it_infrastructure.md index 0207e20f..ba23f8d5 100644 --- a/docs/3._Knowledge_Center/06_references/01_it_infrastructure.md +++ b/docs/3._Knowledge_Center/06_references/01_it_infrastructure.md @@ -81,6 +81,50 @@ Run it as a systemd unit and write to stdout and stderr; both go to the journal - **rsyslog** (`log_client::legacy_logs: true`): on EL7/EL8 Puppet writes `/etc/rsyslog.conf` and forwards `*.*` to each `log_client::forward_to` server over UDP; on EL9 only the max-open-files setting is managed. In the hiera data only `gfa-smtp-relay` (`data-cocos`) sets it. `role::log_server` (rsyslog plus `systemd-journal-remote`) is used by `xbl-log` in `data-cocos`. - **Logstash and Beats** (repository `controls_it/gfa_ansible_elastic`, Ansible, last change 2021): Logstash 7.9.2 on `gfa-logstash` receives syslog, RF logs, CA put logs and PCO logs and writes indices `logstash-gfa_-`; the CA put log is searched in Kibana with the index pattern `logstash-gfa_caputlog*`. Journalbeat 7.9.1 on the CA gateways ships selected units to the space `gfa` (alias `journalbeat-gfa_7.9.1`); the gateway logs are in the saved Kibana view on `https://kibana.psi.ch/s/gfa/`, filtered on `agent.hostname`. +## iocinfo + +iocinfo collects the information that IOCs send when they start and serves it through a REST API. It is the backend of the `ioc search`, `ioc records`, `ioc libraries`, `ioc boots` and `ioc duplicates` commands (formerly `findrecord`, `bootinfo` and `libversionShow`), it tells `ioc shell`, `ioc restart` and `ioc connect` where an IOC runs, and gfa-monitoring imports its list of IOCs from it. Users see it through [IOC Utils](../../2._Services_Portfolio/Tools/01_ioc_utils.md) and [Monitoring Tools](../../2._Services_Portfolio/Tools/08_monitoring_tools.md). + +### How the data gets in + +- An IOC loads the EPICS module `iocinfo`, which sends the IOC's boot information, its loaded libraries and its records to the server at startup. The server's upload endpoint is `POST /api/v2/upload`. +- For older IOCs the server also offers the API of the former bootinfo server (`upload-libinfo.ashx`, `records.aspx`, `bootnotify.aspx`), which upload scripts on the boot PCs call during IOC startup. +- Each IOC is assigned to a facility by the rules in `facility_mapping.csv`. + +### Query API + +Base address: `http://iocinfo.psi.ch/api/v2`. The full description is at [http://iocinfo.psi.ch/swagger-ui.html](http://iocinfo.psi.ch/swagger-ui.html); use the base address given here, not the one shown there. The v1 API is deprecated. + +| `GET` | Returns | Used by | +|---|---|---| +| `/ioc` | names of IOCs; filters `pattern`, `facility`, `library`, `libraryVersion` (regular expressions) | `ioc search` | +| `/ioc/{name}` | everything known about one IOC: boot, libraries, records, shell host and port | `ioc shell`, `ioc restart` | +| `/ioc/{name}/history` | the boot history of one IOC | `ioc boots -i` | +| `/boots` | boots of IOCs | `ioc boots` | +| `/records` | records, filtered by name, IOC or facility | `ioc records` | +| `/records/duplicates` | record names defined on more than one IOC | `ioc duplicates` | +| `/search` | IOCs with their boot and library data | `ioc libraries`, the gfa-monitoring import | +| `/cablings`, `/cabling/{ioc}` | port server cabling of IOC consoles | `ioc connect` | +| `/facilities` | the facilities known to the server | | + +If another application needs the data, or you need another format such as CSV, call the API directly and do not parse the output of the `ioc` command. Examples with `curl` and `jq`: + + # channel names of one IOC + curl http://iocinfo.psi.ch/api/v2/ioc/ | jq -r .records[].name + + # libraries and versions of one IOC + curl http://iocinfo.psi.ch/api/v2/ioc/ | jq -r '.libraries[] | .name + " " + .version' + + # all records of one facility + curl "http://iocinfo.psi.ch/api/v2/records?facility=swissfel" + +### Operation + +- The service runs as a container (`iocinfo.service`) on `iocinfo.psi.ch`. +- Its data is on NFS, mounted at `/data/iocinfo`: uploaded information in `infos`, the content of failed uploads in `upload_errors`. +- To change the facility mapping, update `facility_mapping.csv` in the repository, copy it to `/data/iocinfo` on the server and restart `iocinfo.service`. `facility_update.py` re-assigns the IOCs already stored; it can run for hours. +- Source and build instructions: [controls_it/iocinfo](https://gitea.psi.ch/controls_it/iocinfo) (access needed). + ## Host types and packages The host types from the Puppet hiera data, with the package groups and packages Puppet installs on each: [Host Types and Packages](04_host_types.md). diff --git a/zensical.toml b/zensical.toml index 8856ce77..f0f8945a 100644 --- a/zensical.toml +++ b/zensical.toml @@ -471,6 +471,7 @@ logo = "cas_03_sp" "3._Knowledge_Center/03_how_to/14_caqtdm_panels.md", "3._Knowledge_Center/03_how_to/15_ioc_platforms.md", "3._Knowledge_Center/03_how_to/16_configure_MOXA.md", + "3._Knowledge_Center/03_how_to/17_ansible.md", ]}, { "Troubleshooting" = [ "3._Knowledge_Center/04_troubleshooting/index.md",