Metadata-Version: 2.5
Name: trident-undertow
Version: 0.2.0
Summary: Python library and command line interface for the Trident dataspace server.
Project-URL: Homepage, https://git.ift.tuwien.ac.at/pub/pypi/trident-undertow
Project-URL: Source, https://git.ift.tuwien.ac.at/pub/pypi/trident-undertow
Project-URL: Issues, https://git.ift.tuwien.ac.at/pub/pypi/trident-undertow/-/issues
Author: TU Wien, IFT
License: MIT
License-File: LICENSE
Keywords: compute-to-data,dataspace,pontus-x,trident
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: coloredlogs>=15.0.1
Requires-Dist: python-dotenv>=1.2.2
Requires-Dist: pyyaml>=6.0
Requires-Dist: requests>=2.33
Requires-Dist: rich>=13.0
Requires-Dist: tabulate>=0.9
Requires-Dist: typer>=0.12.5
Provides-Extra: dev
Requires-Dist: pytest-mock>=3.14; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Provides-Extra: hdf5
Requires-Dist: h5py>=3.0; extra == 'hdf5'
Description-Content-Type: text/markdown

# undertow

Python library and command line tool for a Trident dataspace server: files, publishing in the dataspace, the
catalogue, compute jobs and their results, master data and provisioning.

```python
import undertow

trident = undertow.connect("https://trident.example.org/tti")   # login from UNDERTOW_USERNAME / UNDERTOW_PASSWORD
f = trident.files.upload("measurements.csv")
service = trident.services.create(f, name="Measurements")
offering = trident.offerings.create(service, name="Measurements", license="CC-BY-4.0", access="compute")
print(offering.wait())     # the DID once it is published
```

## Install

```sh
pip install trident-undertow    # the command and the Python package are `undertow`
pip install "trident-undertow[hdf5]"   # adds h5py for reading HDF5 metadata (files inspect, sync)
```

Python 3.10 or newer.

## Configure

Settings are read from the command line options, then the environment (also from a `.env` file in the working
directory, see `.env.example`), then the `--tenant` section of the settings file (see below), then
`~/.undertow/credentials`.

| Variable | Meaning |
|---|---|
| `UNDERTOW_URL` | Trident server URL including its path prefix, e.g. `https://trident.example.org/tti` |
| `UNDERTOW_USERNAME`, `UNDERTOW_PASSWORD` | password login |
| `UNDERTOW_AUTH` | `password` (default), `device` or `client_credentials` |
| `UNDERTOW_OIDC_ISSUER` | issuer URL of the OIDC provider, e.g. `https://id.example.org` (the same one Trident trusts) |
| `UNDERTOW_OIDC_CLIENT_ID` | OIDC client, default `undertow` |
| `UNDERTOW_OIDC_CLIENT_SECRET` | secret of a confidential client (`client_credentials`) |
| `UNDERTOW_OIDC_SCOPE` | optional scope |
| `UNDERTOW_TOKEN_CACHE` | token cache of the device flow, default `~/.undertow/tokens.json`; `none` turns it off |
| `UNDERTOW_SECRETS_FILE` | secrets file for provisioning (see below) |
| `UNDERTOW_TENANT` | dataspace in `.undertow.yaml` to take the server and OIDC settings from (`--tenant`) |
| `UNDERTOW_SETTINGS` | settings file of the tenant for `undertow.connect()` (default `./.undertow.yaml`; the command uses `--settings`) |
| `UNDERTOW_LOG_LEVEL` | `DEBUG`, `INFO`, `WARNING` (default), ... |
| `UNDERTOW_API_VERSION` | Trident version of the server: `auto` (default, probed), `v1` or `v2` (see Trident v1 servers) |

The options `--url`, `--username/-u`, `--password-stdin`, `--auth`, `--tenant`, `--settings`, `--api-version`,
`--output/-o table|json|yaml` and `--log/-l` come before the command, e.g. `undertow -o json files list`.
`--password/-p` puts the password into the process list and the shell history.

`~/.undertow/` (mode 0700) holds `credentials` (written by `system login`, never a password), `tokens.json` (device
flow) and optionally `secrets.yaml`; undertow writes its files with mode 0600 and ignores a `credentials` file that
others can read.

A command that fails exits with code 1 (2 for a wrong option, a missing server URL or a name that matches nothing),
so scripts and CI see the failure.

## Log in

There are three ways to get a token, chosen with `UNDERTOW_AUTH` or `--auth`:

- `password` (default): username and password, sent to Trident's `POST /auth/login`. Trident gets the token.
- `device`: interactive login in the browser. The tool prints a URL and a code, you log in there (MFA and SSO
  work, the password never reaches the tool). Uses the public client `undertow`.
- `client_credentials`: client id and secret get tokens directly from the OIDC provider. No user, no password, no
  browser; meant for CI, provisioning and other automations.

`device` and `client_credentials` work with any OIDC provider, e.g. Keycloak. The tool finds the provider's
endpoints through `<issuer>/.well-known/openid-configuration`; it stops with an error when this document cannot be
read or, for `device`, has no `device_authorization_endpoint`.

Password:

```sh
undertow --url https://trident.example.org/tti -u alice --password-stdin system login < password.txt
undertow system user
```

`system login` stores URL, username and Trident's refresh token in `~/.undertow/credentials`, never the password.
Later commands use the token until Trident no longer accepts it; then log in again. `system logout` removes it and
the cached tokens.

Device:

```sh
export UNDERTOW_OIDC_ISSUER=https://id.example.org
undertow --url https://trident.example.org/tti --auth device system login
```

Later calls reuse and refresh the cached tokens. The device login asks for `openid offline_access` (set
`UNDERTOW_OIDC_SCOPE` to change it): the offline token keeps the CLI logged in for weeks, independent of browser
sessions; `system logout` deletes it here, the Keycloak account console ("Applications") revokes it. The provider
needs a public client `undertow` with the OAuth 2.0 Device Authorization Grant enabled whose tokens carry Trident's
audience (`trident`); `eks-cli addon trident prepare` creates it.

Client credentials:

```sh
export UNDERTOW_AUTH=client_credentials
export UNDERTOW_OIDC_ISSUER=https://id.example.org
export UNDERTOW_OIDC_CLIENT_ID=ci-client
export UNDERTOW_OIDC_CLIENT_SECRET=...
```

This needs a confidential client with service accounts enabled whose tokens carry Trident's audience (`trident`).

Use the same issuer as Trident, otherwise the token's issuer does not match. The user or service account needs
Trident's roles for the routes it calls.

## Commands

`undertow --help` and `undertow <group> --help` list everything. The main ones:

```sh
# files
undertow files list --search report --all
undertow files upload ./measurement.h5 --name "Measurement A"
undertow files sync --folder ./data              # new and changed files, see "Folder sync"
undertow files download measurement.h5 --to ./downloads/
undertow files inspect ./measurement.h5          # HDF5 metadata, needs trident-undertow[hdf5]

# services and offerings
undertow services create --name "Measurement A" --type dataset --file-id 12
undertow offerings create --name "Measurement A" --service-id 5 --type compute --trust-list-id 2
undertow offerings publish 7
undertow offerings revoke 7                        # `offerings delete` revokes too: Trident never deletes offerings

# dataspace
undertow dataspace list
undertow dataspace wallets                         # the server's wallets (tags); configured on the server
undertow dataspace access did:op:... --wallet lab  # the server orders (with wallet "lab") and downloads it
undertow dataspace fileinfo --mine                 # can the node download every published file? (exit 1 if not)
undertow dataspace compute start -d did:op:dataset -a did:op:algorithm --wallet lab --wait   # --timeout 3600
undertow dataspace groups                          # groups of compute datasets (e.g. one tool life), count, tag
undertow dataspace groups --runs did:op:algorithm   # also the newest run of that algorithm per group
undertow dataspace compute start --group group-ift-tu-wien-0001b -a did:op:algorithm   # a whole group; >10: several jobs
undertow dataspace compute status <job id>
undertow dataspace results list --type compute
undertow dataspace results outputs 42
undertow dataspace results publish 42 --path outputs/model.json            # shows the draft
undertow dataspace results publish 42 --path outputs/model.json --yes      # publishes

# master data
undertow masterdata participants list
undertow masterdata trust-lists ensure --name "Partners" --participant-ids tenant-a,tenant-b
undertow masterdata docker-images ensure --name example/algorithm-base --tag 1.0 --checksum sha256:...
```

## Folder sync

`undertow files sync` (and the `sync_folder` of provisioning with `sync_mode: upload`) compares each local file with
the server file of the same name in the same folder (virtual group) by SHA-256:

| Result | When | What happens |
|---|---|---|
| `new` | no such file on the server | uploaded |
| `unchanged` | same content | skipped |
| `changed` | different content, or `--overwrite` | new content uploaded in place: same file id, services and offerings stay |
| `failed` | the upload or the comparison failed | reported; the command exits with code 1 |

The server's hash is used while it is current. Otherwise undertow uses `.undertow-sync.json`, which it writes into the
synced folder (relative path, SHA-256, size, mtime and file id of what was synced), and else the file size; with
neither the file is uploaded again.

Never uploaded:
- the cache file, `.git`, `__pycache__` and similar;
- files that look like credentials or keys, in every subfolder, each named in a warning: `.env*`, `*secret*.yaml`,
  `*secret*.json`, `.undertow*.yaml`, `*.pem`, `*.key`, `id_rsa*`, `kubeconfig*`, ...;
- names matching a line of `.undertowignore` in the synced folder (glob patterns, `#` comments; a pattern with a `/`
  matches the relative path);
- symbolic links, unless `--follow-symlinks` is given.

A download sync keeps every file inside the target folder: a server name with `..` is skipped and reported. On a server without in-place upload a
changed file is uploaded as a new file and the old one is deleted, unless services or offerings use it: then it is
reported as `changed` with "old version kept (in use)". `undertow files sync` prints a line per file and a summary
(`--output json`: the results and counts).

## Trident v1 servers

On a Trident v1 server undertow handles the **files** commands: list (`--search` filtered here, v1 ignores it),
upload, download (by id and by name), delete, file secrets and `files sync`. v1 differs in a few points that undertow
follows:

| | v1 | v2 |
|---|---|---|
| file list | `{files, total, page, size}` | `{items, files, ...}` |
| `q`, `group` filters | ignored by the server, applied by undertow | server |
| upload | one presigned PUT (at most 5 GiB) | multipart above the server's threshold |
| file secret | `POST files/:id/secret` | `POST files/:id/secrets` |
| SHA-256 of a file | none: sync compares by `.undertow-sync.json`, then by size | server hash |

The version is probed once when it matters (`GET management/files/multipart/config`: 404 = v1); `--api-version v1`,
`UNDERTOW_API_VERSION=v1` or `server.api_version: v1` in the tenant section skip the probe. Without a server hash the
first sync of a folder that is already on the server compares by size only; after it, `.undertow-sync.json` holds the
hashes. Master data, offerings, provisioning and the other v2 routes are not supported on v1 (a 404, logged as such).
The password login works on v1; OIDC tokens only when they carry v1's audience and an RS256 signature.

## Provisioning

```sh
undertow system provision --config provisioning.yaml --dry-run
undertow system provision --config provisioning.yaml
undertow system sync --config provisioning.yaml      # only the folder sync
```

The file format is described in Trident's `docs/PROVISIONING.md`. undertow sends the master data of the file to
`POST /management/provisioning` of every participant with a `server` entry (URL plus username/password or
`server.auth`), then syncs its `sync_folder`. Values like `${tenant-a.server.password}` are taken from a secrets
file: `--secrets-file`, `UNDERTOW_SECRETS_FILE`, `~/.undertow/secrets.yaml`, or `.secrets.yaml` / `secrets.yaml`
next to the provisioning file or in the working directory. `${env:NAME}` reads an environment variable (a bare
`${NAME}` only for `UNDERTOW_*` names, so a provisioning file from someone else cannot read other variables),
`${NAME:-default}` sets a default and `$${...}` keeps a literal `${...}` (e.g. in a template).

```yaml
# secrets.yaml
tenant-a:
  server:
    password: "<password>"
```

## Settings from eks-cli

eks-cli writes two files per dataspace with the same nesting: `.undertow.yaml` (server URL, username, OIDC
issuer and client, wallet; no credentials) and `.undertow.secrets.yaml` (passwords, mode 0600). Whenever undertow
reads a settings or secrets file, it merges the sibling `<name>.secrets.yaml` over it, so the credentials win; a
single combined `.undertow.yaml` works as well, but undertow warns about each credential key in it (key name only).

```yaml
# .undertow.yaml
ift:
  server: {url: https://trident.example.org/tti, username: ift-trident-user}
  oidc: {issuer: https://id.example.org/realms/ift, client_id: undertow}
# .undertow.secrets.yaml
ift:
  server: {password: "<password>"}
```

```sh
undertow system provision -c provisioning.yaml -s .undertow.yaml   # ${ift.server.password} from the secrets file
undertow --tenant ift files list                                    # server, user and OIDC client of "ift"
```

A secrets file encrypted with [SOPS](https://github.com/getsops/sops) (age keys; eks-cli `secrets encrypt`) is
decrypted in memory through the `sops` command when it is read; the age key comes from `SOPS_AGE_KEY_FILE` or
`~/.config/sops/age/keys.txt`.

`--tenant` reads `.undertow.yaml` in the working directory (`--settings PATH` for another one) and uses
`<tenant>.server.url/username/password` and `<tenant>.oidc.issuer/client_id/scope`; `oidc.flow` and
`oidc.client_secret` set the login of a service account (`client_credentials`, written by eks-cli as
`<tag>-<name>`). Options and `UNDERTOW_*` variables win. A missing file, or a tenant that is not in it, stops
with exit code 2 (the error lists the tenants).

## Python

**Connect.** `undertow.connect(target)` takes the same settings as the command (see Configure):

```python
trident = undertow.connect("https://trident.example.org/tti")  # a server URL; user and password from UNDERTOW_*
                                                               # or from `undertow system login`
trident = undertow.connect("tenant-a")                         # a tenant section of ./.undertow.yaml (eks-cli)
trident = undertow.connect()                                   # everything from UNDERTOW_*
```

The argument is a URL when it starts with `http://` or `https://`, otherwise a tenant name; `url=`, `username=`,
`password=`, `tenant=` and `settings=` (another settings file, also `UNDERTOW_SETTINGS`) are the explicit forms.
`connect()` never opens a browser: a device login has to be in the token cache already (log in once with any
`undertow` command).

**Publish in Trident's steps.** A file becomes a service (what it is), the service becomes an offering (how it is
published: license, description, access):

```python
f = trident.files.upload("measurements.csv")
service = trident.services.create(f, name="Measurements", description="Time series as CSV")
offering = trident.offerings.create(service, name="Measurements", license="CC-BY-4.0", access="compute",
                                    template="Measurement report", tags=["milling"], trust_list="Partners")
did = offering.wait()
```

| Call | Result |
| --- | --- |
| `trident.files.upload(path, group=None)` | the new file; `file.wait()` until Trident has it stored. `files.list(search=None, group=None)`, `files.get(file)`, `files.download(file, folder=".")`, `files.delete(file)` |
| `trident.files.sync(folder, dry_run=False)` | one entry per file: `new`, `changed`, `unchanged` or `failed` |
| `trident.services.create(file, name, kind="dataset", description=None, image=None, parameters=None, app=None)` | the new service; `file` may be a local path. An algorithm needs `kind="algorithm", image="name:tag"` (registered when new) and may declare `parameters`, or takes all of it from `app`, the `.dsapp.json` that `pelago build` writes next to the bundle. `services.list()`, `services.get(id)` |
| `trident.offerings.create(service, name, license, access="download", ...)` | an `Offering`, see below; `offerings.list(search=None)`, `offerings.get(id)` |
| `trident.publish(file, name, license, ...)` | the three steps in one call, with the arguments of both; names are checked before anything is created |
| `offering.wait()` | the DID once the server's worker has published it and the catalogue finds it (`indexed=False`: without the catalogue) |
| `offering.revoke()`, `offering.unlist()`, `offering.relist()` | |
| `trident.catalogue.search(text=None, type=None, tags=None)` | assets of all participants (`asset.did`, `.name`, `.type`); `catalogue.get(did)`, `catalogue.algorithms()`, `catalogue.datasets_for(algorithm)` |
| `trident.compute(datasets, algorithm, params=None)` | a `Job`; `job.wait()`, `job.files()`, `job.download(folder)` |
| `job.publish(path, name, license="CC-BY-4.0", access="compute", ...)` | an `Offering` of one output file (e.g. `outputs/result.json`) with the job's provenance; `template`, `tags`, `algorithm_list`, `trust_list` as for offerings |
| `job.stop()` | asks the node to stop the job (admin; the server signs it with the job's wallet): `stopped`, or `stop requested` while the node still lists it |
| `trident.node(fresh=False)` | the serving node's state (admin): health badges, host load, compute environments with booked resources, our jobs on the node with a verdict each; `trident.free_compute()`: whether a free job starts now, else why not |
| `trident.provision(path, secrets=None, dry_run=True)` | the provisioning report (what would change) |

`offerings.create` takes:
- `license`: the key of a license (`trident.licenses`);
- `access`: `download` hands the file out, `compute` only runs it on the node;
- the description: `description="..."` (markdown) or `template="<name>"`, otherwise the server's default template;
- `tags`, `categories`, `info` (additionalInformation);
- `trust_list`, `datatoken` and `algorithm_list` by name, or `algorithms=[DIDs]` for the algorithms a compute
  dataset allows.

**Many at once, re-runnable.** Start everything first, then wait once: `trident.wait(items)` waits for files,
offerings and jobs together with one request per kind and poll. It waits for all of them even when some fail, then
raises one `undertow.WaitError` (`.failed`: item and reason, `.done`).

`files.ensure`, `services.ensure` and `offerings.ensure` take the arguments of upload and create and find by name
first. A script built from them can simply run again after a failure:
- a file with the same name and content is kept; changed content becomes a new version of the same file;
- an existing service or offering is returned unchanged; an offering whose publication failed is published again.

`trident.publish(..., ensure=True)` and `job.publish(...)` behave the same way.

```python
files = [trident.files.ensure(path, group="measurements") for path in paths]
trident.wait(files)                                   # all stored
services = [trident.services.ensure(f, name=f.name) for f in files]
offerings = [trident.offerings.ensure(s, name=s.name, license="CC-BY-4.0", access="compute",
                                      algorithm_list="Allowed algorithms") for s in services]
trident.wait(offerings)                               # all published and in the catalogue
```

**Master data by name.** `trident.licenses`, `trident.templates`, `trident.trust_lists`, `trident.algorithm_lists`,
`trident.images` and `trident.datatokens` each have `list()`, `get(name)` and `ensure(...)` (create, or update
when it differs). Every call that takes master data takes its name: a license by its key, an image as
`name:tag`, a datatoken by name or symbol. An id or a Record works as well; an unknown name raises an error that
lists the known ones.

```python
trident.licenses.ensure("Example-Data-Use-1.0", "Example Data Use Terms 1.0", file="LICENSE.md")  # with its text
trident.templates.ensure("Measurement report", file="report.md")    # Handlebars markdown
trident.trust_lists.ensure("Partners", ["org-a", "org-b"])          # participant tags
trident.images.ensure("example/base:1.0")                           # digest from the registry
```

A license's text is published with the offering: its asset links the text with its hash.

**Results.** Dicts with attribute access (`f.id`, `f["name"]`). Failures raise `undertow.ApiError` (status, message;
signed URLs removed), `AuthError` or `ConfigError`; nothing is printed.

More in [examples/](examples/). Transactions (publish, revoke, compute) are signed by the server's wallet.

Every route of the server is also reachable directly: `trident.client` is a `TridentClient` with
`client.management.*` (one method per route, each returns the `requests.Response`; `undertow.api_data(response)`
gives its JSON or raises `ApiError`), `client.aquarius.*` and `client.nautilus.*`.

## Development

```sh
python3 -m venv .venv && . .venv/bin/activate
make install     # pip install -e ".[dev]"
make test
```

The tests use mocks only and need no server.

## Release

The version is set in `src/undertow/__init__.py` (`__version__`).

```sh
make init        # build tools
make release     # checks PyPI and the git tree, runs the tests, builds, uploads, tags v<version>
```

## License

MIT, see `LICENSE`.
