From 26a7b4f9037d77d4d7f46cb5c001804efe1e48fe Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Thu, 15 Oct 2026 15:27:17 +0200
Subject: [PATCH] feat: 1419: add a command to clean up old revisions on demand
'opencloud storage-users revisions cleanup' deletes old revisions,
according to a cleanup strategy, of:
- the files of spaces (--space, repeatable),
- or of a file or folder within a space (--space with --path),
- or of all spaces (--all),
- or of a file or folder given by its path on disk (--fs-path, posix
only).
The id of a file or folder is rejected as the id of a space, as the
command would otherwise clean up its whole space. So is an id without a
space id, e.g. 'storage$'.
The storage-users service only cleans up the revisions of a file when it
gets a new one. The command also covers the files that are not changed
anymore, and applies a different strategy once.
The strategy and the settings of the background workers default to the
configured ones (STORAGE_USERS_REVISIONS_CLEANUP_*), and can be
overridden with --strategy, --async, --workers and --queue-size. Only
--queue-full defaults to 'block' without a timeout, whatever is
configured: the command finds files faster than the workers clean them
up, so dropping the files that find the queue full, or giving up after
the timeout meant for uploads, would skip most of them.
--queue-full-timeout sets one for the run.
The command uses the storage driver directly, in its own process, like
'uploads sessions': posix neither scans nor watches the file system, and
no driver joins the postprocessing consumer group of the service.
For posix, the driver needs NATS for its event stream. The command waits
for it 10 seconds at most, instead of the 15 minutes the stream retries
for, and ctrl-c also stops that wait: with the single binary, NATS only
runs within the server (opencloud-eu/opencloud#3805). The driver gets
the logger of the command: posix passes it on to the NATS connections
of its id cache, whose handlers would panic on a lost connection
without one. Ctrl-C also stops waiting for the driver, e.g. for the id
cache, which retries for up to 15 minutes as well.
Unless it is a dry run, which changes nothing on disk, the command
warns when the storage belongs to another user than the one it runs as,
e.g. root: the lock files it creates belong to that user, and the
server may not be able to lock these files anymore.
Output: a line for every file whose revisions were deleted, that failed
or that was skipped, with its path within its space, and a summary;
--verbose adds every file and every revision with the decision and its
reason; --json prints the same as JSON objects, one per line, with a
final summary object. --dry-run deletes nothing.
--timeout stops the cleanup gracefully, as does ctrl-c, and a second
ctrl-c ends the command right away, which can leave the blob of a
deleted revision behind; the help says so. Whether the timeout or ctrl-c
stopped the cleanup is told by the contexts of the command, not by the
error: the storage can return context errors of its own. --shuffle walks
the spaces and folders in a random order, so that repeated runs that
are stopped by the timeout, e.g. from a cron job, eventually reach all
files. The help explains that a file waiting for a lock can't be
interrupted, and that a dry run changes nothing on disk, but decides on
a snapshot, as it doesn't keep the files locked while it decides.
The common flags have short forms: -a (--all), -p (--fs-path),
-s (--strategy), -n (--dry-run), -v (--verbose), -j (--json) and
-t (--timeout).
Exit codes:
- 0 when done,
- 1 if the cleanup or any file failed, or if it was interrupted,
- 2 if the timeout stopped the cleanup before all files were cleaned
up.
The storage-users README documents the command, along with the cleanup
strategies and how they relate to the configured cleanup.
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 131 +++-
.../storage-users/pkg/command/revisions.go | 692 ++++++++++++++++++
.../pkg/command/revisions_test.go | 417 +++++++++++
services/storage-users/pkg/command/root.go | 1 +
4 files changed, 1240 insertions(+), 1 deletion(-)
create mode 100644 services/storage-users/pkg/command/revisions.go
create mode 100644 services/storage-users/pkg/command/revisions_test.go
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index a7194a707c..470eb0fcd6 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -266,7 +266,7 @@ opencloud storage-users blobstore get --space-id=b19ec764-5398-458a-8ff1-1925bd9
### Manage Trash-Bin Items
-This command set provides commands to get an overview of trash-bin items, restore items and purge old items of `personal` spaces and `project` spaces (spaces that have been created manually). `trash-bin` commands require a `spaceID` as parameter.
+This command set provides commands to get an overview of trash-bin items, restore items and purge old items of `personal` spaces and `project` spaces (spaces that have been created manually). `trash-bin` commands require a `spaceID` as parameter.
```bash
opencloud storage-users trash-bin
@@ -333,6 +333,135 @@ When the CLI tool restores the item with the `replace` option, the existing item
opencloud storage-users trash-bin restore [command options] ['spaceID' required] ['itemID' required]
```
+### Clean Up Old Revisions
+
+Every change to a file keeps its previous content as a revision (version). With `STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY`, the `storage-users` service deletes old revisions according to a cleanup strategy, whenever a file gets a new revision.
+
+The `decomposed`, `decomposeds3` and `posix` storage drivers are supported, with `posix` also for the revisions created from changes on disk.
+
+The default strategy `disabled` keeps all revisions and, as one would expect, does not perform any cleanup process for revisions at all.
+
+The service only cleans up a file when it gets a new revision, so files that are never changed again keep their revisions.
+
+The `revisions cleanup` command cleans up the revisions of whole spaces, folders or files on demand, to cover those files as well, or to apply a different strategy once, e.g. after changing the strategy or to free storage.
+
+```bash
+opencloud storage-users revisions cleanup [flags]
+```
+
+The command uses the storage directly, with the configuration of the `storage-users` service, and can run while the service is running. It needs access to the storage and, for the `posix` driver, to NATS. With the single binary, NATS runs within the server: without a running server, the command gives up after 10 seconds. It needs no service account.
+
+Run the command as the user that OpenCloud runs as, e.g. with `sudo -u opencloud` on a server where OpenCloud runs as the user `opencloud`, or with `docker exec` in its container. The lock files the command creates belong to the user that runs it, with permissions only for that user, so OpenCloud may not be able to lock these files anymore if it was run as another user, e.g. as `root`. Unless it is a dry run, which changes nothing on disk, the command warns when the storage belongs to another user.
+
+#### Strategies
+
+A strategy is a comma-separated list of up to three parts.
+
+Each `X` is either
+* a number, which is a number of revisions, always counting from the newest one,
+* or a duration with one of the units `w` (weeks), `d` (days), `h` (hours), `m` (minutes) or `s` (seconds).
+
+Durations in days or weeks can use an uppercase unit, `D` or `W`, to count from midnight (server time) instead of from now: `1d` means the last 24 hours, `1D` since yesterday 00:00.
+
+| Strategy | Meaning | Examples |
+|---|---|---|
+| `auto` | Thin out revisions the older they get: one per 10 seconds in the last minute, one per minute in the last hour, one per hour in the last 24 hours, one per day in the last 30 days, one per week beyond | `auto` |
+| `X` | Delete everything beyond `X` | `10`, `30d`, `0` deletes all revisions |
+| `X, auto` | Keep everything within `X`, thin out the older revisions | `14d, auto` |
+| `auto, X` | Delete everything beyond `X`, thin out the rest | `auto, 90d`, `auto, 50` |
+| `X1, X2` | Keep everything within `X1`, delete everything beyond `X2`; one must be a number, the other a duration | `5, 30d`, `7d, 10` |
+| `X1, auto, X2` | Keep everything within `X1`, delete everything beyond `X2`, thin out in between | `7d, auto, 90d`, `1D, auto, 30d` |
+| `disabled` | Never delete revisions | `disabled` |
+
+Note that the age of a revision is the time its content was written, i.e. the modification time the file had before it was changed, which is also the date the version list shows for it. It is not the time the file was changed, which turned that content into a revision. A document that was unchanged for two months gets a revision that is two months old when it is changed, and e.g. `30d` deletes that revision right away. Combine a duration with a number of revisions, e.g. `5, 30d`, to always keep the newest ones.
+
+#### Selecting the Files
+
+Exactly one of these selects the files to clean up:
+
+* `--space `: all files of a space. It can be given several times. The space IDs are accepted as the APIs show them, e.g. `$`. The ID of a file or folder within the space (`$!`) is rejected: give the space with `--space` and the file or folder with `--path`.
+* `--space --path `: only a file or a folder (recursively) within one space, e.g. `--path /Documents`.
+* `--all` (`-a`): all files of all spaces, including disabled spaces, which are skipped.
+* `--fs-path ` (`-p`): a file or a folder (recursively) by its path on disk. Only supported by the `posix` driver.
+
+#### Options
+
+The strategy and the settings of the background workers default to the configured ones and can be overridden for a run. Only `--queue-full` defaults to `block` without a timeout, whatever is configured: the command finds files faster than the workers clean them up, so dropping the files that find the queue full would skip most of them.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--strategy`, `-s` | `STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY` | The strategy, see above. The command fails if there is none. |
+| `--async` | `STORAGE_USERS_REVISIONS_CLEANUP_ASYNC` | Clean up files in background workers while looking for more. |
+| `--workers` | `STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS` | The number of background workers, `0` for half the available CPUs, at least 2. |
+| `--queue-size` | `STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE` | The number of files that can wait for a worker, `0` for 64 per worker. |
+| `--queue-full` | `block` | `block` waits for room in a full queue, `drop` skips the file. |
+| `--queue-full-timeout` | `0` | With `block`, skip a file after waiting this long for room, e.g. `10s`. `0` waits as long as it takes. |
+| `--dry-run`, `-n` | off | Delete nothing, only print what would be deleted. |
+| `--verbose`, `-v` | off | Print every file and every revision, with what was decided about it and why. |
+| `--json`, `-j` | off | Print JSON objects, one per line, instead of text. |
+| `--timeout`, `-t` | none | Stop the cleanup gracefully after this time, e.g. `30m` or `2h`. |
+| `--shuffle` | off | Clean up the spaces, and the files within each folder, in a random order. |
+
+By default, the command prints a line for every file whose revisions it deleted, that it could not clean up or that it skipped, with the space ID and the path of the file within the space, and a summary:
+
+```plaintext
+25b69780-5f39-43be-a7ac-a9b9e9fe4230 /Documents/report.odt: deleted 3 of 12 revisions (4.2 MiB)
+25b69780-5f39-43be-a7ac-a9b9e9fe4230 /Photos/holiday.jpg: skipped: an upload to the file is still being processed
+1520 files in 3 spaces: deleted 3 revisions (4.2 MiB) of 1 file, 1 skipped, 0 failed
+```
+
+With `--verbose`, every revision is listed with the decision (`deleted`, `kept` or `protected`), its time, its size and the reason:
+
+```plaintext
+25b69780-5f39-43be-a7ac-a9b9e9fe4230 /dir1/file1 (node 43ca5408-c77b-4d9a-8a3b-d4470b1253b8): would delete 1 of 3 revisions (1.2 KiB)
+ protected 2026-10-15T13:24:35+02:00 1.2 KiB protected by "1": one of the 1 newest
+ kept 2026-10-13T15:24:35+02:00 1.2 KiB kept by "30d": not older than 2026-09-15T15:24:35+02:00
+ deleted 2026-03-29T15:24:35+02:00 1.2 KiB deleted by "30d": older than 2026-09-15T15:24:35+02:00
+```
+
+With `--json`, every file is an object of the `type` `file`, with the revisions in `details` when `--verbose` is set, and the last line is an object of the `type` `summary`. The sizes are in bytes. The same run as above:
+
+```json
+{"type":"file","space_id":"25b69780-5f39-43be-a7ac-a9b9e9fe4230","node_id":"8a1c0e2f-6b4d-4f7a-9c3e-2d5b7f1a0c94","path":"/Documents/report.odt","dry_run":false,"revisions":12,"deleted":3,"deleted_bytes":4404019,"failed":0}
+{"type":"file","space_id":"25b69780-5f39-43be-a7ac-a9b9e9fe4230","node_id":"f3e9d2c1-0a7b-4c8e-b6d5-9e4f1a2b3c7d","path":"/Photos/holiday.jpg","dry_run":false,"skipped":"an upload to the file is still being processed","revisions":0,"deleted":0,"deleted_bytes":0,"failed":0}
+{"type":"summary","dry_run":false,"spaces":3,"files":1520,"cleaned":1,"deleted":3,"deleted_bytes":4404019,"skipped":1,"failed":0}
+```
+
+With `--verbose` as well, a file object lists its revisions in `details`, here from the dry run above:
+
+```json
+{"type":"file","space_id":"25b69780-5f39-43be-a7ac-a9b9e9fe4230","node_id":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8","path":"/dir1/file1","dry_run":true,"revisions":3,"deleted":1,"deleted_bytes":1234,"failed":0,"details":[{"key":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8.REV.2026-10-15T11:24:35.118424081Z","time":"2026-10-15T11:24:35.118424081Z","size":1234,"decision":"protected","reason":"protected by \"1\": one of the 1 newest"},{"key":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8.REV.2026-10-13T13:24:35.118424081Z","time":"2026-10-13T13:24:35.118424081Z","size":1234,"decision":"kept","reason":"kept by \"30d\": not older than 2026-09-15T15:24:35+02:00"},{"key":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8.REV.2026-03-29T13:24:35.118424081Z","time":"2026-03-29T13:24:35.118424081Z","size":1234,"decision":"deleted","reason":"deleted by \"30d\": older than 2026-09-15T15:24:35+02:00"}]}
+```
+
+A file that failed has an `error`, and so has a revision in `details` that could not be deleted. When `--timeout` stopped the cleanup, the summary has a `stopped` field with the reason.
+
+Things to keep in mind:
+
+* **A dry run changes nothing on disk.** It doesn't keep the files locked while it decides, so its decisions are a snapshot: a real run may decide differently for files that change in the meantime.
+* **`--timeout` stops the cleanup gracefully:** the files being cleaned up are finished, the files still waiting for a worker are skipped. It can't interrupt a file that waits for a lock held by another process, though, so the command can run longer than the timeout. Ctrl-C (or `SIGTERM`) stops the cleanup the same way, but counts as a failure, see the exit codes below. A second Ctrl-C ends the command right away, e.g. when it waits for a lock. Use it only when the first one doesn't help: a revision is deleted in two steps, first its entry, then its content (the blob), and if the command ends between them, the blob stays on the storage, unused.
+* **Every run starts over from the beginning.** For regular runs with a timeout, e.g. by a cron job, add `--shuffle`, so that every run starts in a different place and the runs eventually reach all files, also in spaces too large for a single run.
+
+The exit code is `0` when the cleanup is done, `1` if the cleanup or any file failed, or if Ctrl-C (or `SIGTERM`) interrupted it, and `2` if `--timeout` stopped the cleanup before all files were cleaned up, and nothing failed.
+
+#### Command Examples
+
+```bash
+# show what a strategy would delete in all spaces, with the reason for every revision
+opencloud storage-users revisions cleanup --all --strategy "auto, 90d" --dry-run --verbose
+
+# keep only the 10 newest revisions of the files in a folder of a space
+opencloud storage-users revisions cleanup --space 25b69780-5f39-43be-a7ac-a9b9e9fe4230 --path /Documents --strategy 10
+
+# clean up a folder by its path on disk, with the posix driver
+opencloud storage-users revisions cleanup --fs-path /var/lib/opencloud/storage/users/projects/25b69780-5f39-43be-a7ac-a9b9e9fe4230/Documents
+
+# a nightly cron job: the configured strategy, at most one hour, in a random order
+opencloud storage-users revisions cleanup --all --timeout 1h --shuffle
+
+# the same with the short flags
+opencloud storage-users revisions cleanup -a -t 1h --shuffle
+```
+
## Caching
The `storage-users` service caches stat, metadata and uuids of files and folders via the configured store in `STORAGE_USERS_FILEMETADATA_CACHE_STORE` and `STORAGE_USERS_ID_CACHE_STORE`. Possible stores are:
diff --git a/services/storage-users/pkg/command/revisions.go b/services/storage-users/pkg/command/revisions.go
new file mode 100644
index 0000000000..def373cb41
--- /dev/null
+++ b/services/storage-users/pkg/command/revisions.go
@@ -0,0 +1,692 @@
+package command
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "os/user"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/rs/zerolog"
+ "github.com/spf13/cobra"
+
+ "github.com/opencloud-eu/opencloud/pkg/config/configlog"
+ opencloudstorage "github.com/opencloud-eu/opencloud/pkg/storage"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/parser"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/event"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/revaconfig"
+ "github.com/opencloud-eu/reva/v3/pkg/events"
+ "github.com/opencloud-eu/reva/v3/pkg/storage"
+ "github.com/opencloud-eu/reva/v3/pkg/storage/fs/registry"
+ "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup"
+ "github.com/opencloud-eu/reva/v3/pkg/storagespace"
+)
+
+// The exit codes of the revisions cleanup command
+const (
+ exitFailed = 1 // the cleanup or some of its files failed, or it was interrupted
+ exitStopped = 2 // stopped by --timeout before all files were cleaned up
+)
+
+// Revisions wraps the commands for the revisions (versions) of files.
+func Revisions(cfg *config.Config) *cobra.Command {
+ revisionsCmd := &cobra.Command{
+ Use: "revisions",
+ Short: "manage the revisions (versions) of files",
+ }
+ revisionsCmd.AddCommand(RevisionsCleanup(cfg))
+ return revisionsCmd
+}
+
+// RevisionsCleanup deletes old revisions of the files of whole spaces, folders or files.
+func RevisionsCleanup(cfg *config.Config) *cobra.Command {
+ cmd, _ := revisionsCleanupCommand(cfg)
+ return cmd
+}
+
+// revisionsCleanupCommand returns the revisions cleanup command, and the values of its flags.
+func revisionsCleanupCommand(cfg *config.Config) (*cobra.Command, *revisionsCleanupFlags) {
+ f := &revisionsCleanupFlags{}
+ cmd := &cobra.Command{
+ Use: "cleanup",
+ Short: "Delete old revisions according to a cleanup strategy",
+ Long: `Delete old revisions (versions) of files according to a cleanup strategy.
+
+The storage-users service cleans up the revisions of a file whenever it gets a new one,
+with the strategy configured in STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY. This command
+cleans up the revisions of files that are not changed anymore, or applies a different
+strategy once, e.g. after the strategy was changed or to free storage.
+
+Exactly one of these selects the files to clean up:
+ --space all files of a space, repeatable; with --path, only that file or
+ folder within the space
+ --all all files of all spaces
+ --fs-path a file or folder by its path on disk ('posix' driver only)
+
+The strategy and the settings of the background workers default to the configured
+ones (STORAGE_USERS_REVISIONS_CLEANUP_*) and can be overridden for this run. See the
+description of STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY for the strategies, e.g. '30d',
+'10' or '7d, auto, 90d'. Only --queue-full defaults to 'block' without a timeout,
+whatever is configured: the command finds files faster than the workers clean them up,
+so dropping the files that find the queue full would skip most of them.
+
+The command uses the storage directly, with the configuration of the storage-users
+service, and can run while the service is running. It needs access to the storage and,
+for the 'posix' driver, to NATS. With the single binary, NATS runs within the server:
+without a running server, the command gives up after 10 seconds. Run it as the user
+that OpenCloud runs as, e.g. with 'sudo -u': the lock files it creates belong to the
+user that runs it, and OpenCloud may not be able to open them otherwise. Unless it is a
+dry run, the command warns when the storage belongs to another user.
+
+By default, it prints a line for every file it deleted revisions of, could not clean
+up or skipped, and a summary. --verbose prints every file with every revision, what
+was decided about it and why. --json prints the same as JSON objects, one per line.
+
+--dry-run deletes nothing and prints what would be deleted. It changes nothing on
+disk, and doesn't keep the files locked while it decides: its decisions are a
+snapshot, and a real run may decide differently for files that change meanwhile.
+
+--timeout stops the cleanup gracefully: the files being cleaned up are finished, the
+files still waiting are skipped. It can't interrupt a file that waits for the lock of
+another process, though, so the command can run longer than the timeout. As every run
+starts over from the beginning, combine --timeout with --shuffle for regular runs, e.g.
+by a cron job, so that every run starts in a different place.
+
+Ctrl-C stops the cleanup like --timeout. A second ctrl-c ends the command right away,
+e.g. when it waits for a lock: that can leave the content of a deleted revision on the
+storage, unused, so use it only when the first one doesn't help.
+
+Exit codes: 0 when done, 1 if the cleanup or any file failed, or if it was interrupted
+(ctrl-c, SIGTERM), 2 if --timeout stopped the cleanup before all files were cleaned up
+(and nothing failed).`,
+ Example: ` opencloud storage-users revisions cleanup --all --strategy "auto, 90d" --dry-run
+ opencloud storage-users revisions cleanup --space --path /Documents --strategy 10
+ opencloud storage-users revisions cleanup --all --timeout 1h --shuffle`,
+ PreRunE: func(_ *cobra.Command, _ []string) error {
+ return configlog.ReturnFatal(parser.ParseConfig(cfg))
+ },
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ code, err := runRevisionsCleanup(cmd, cfg, f)
+ if err != nil {
+ return err
+ }
+ if code != 0 {
+ os.Exit(code)
+ }
+ return nil
+ },
+ }
+ flags := cmd.Flags()
+ flags.StringSliceVar(&f.spaces, "space", nil, "the id of a space to clean up, repeatable")
+ flags.StringVar(&f.o.request.Path, "path", "", "a file or folder within the space given by --space, to clean up only that")
+ flags.StringVarP(&f.o.request.FSPath, "fs-path", "p", "", "a file or folder to clean up, by its path on disk ('posix' driver only)")
+ flags.BoolVarP(&f.o.request.All, "all", "a", false, "clean up all spaces")
+ flags.StringVarP(&f.strategy, "strategy", "s", "", "the cleanup strategy, defaults to STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY")
+ flags.BoolVarP(&f.o.request.DryRun, "dry-run", "n", false, "delete nothing, only print what would be deleted")
+ flags.BoolVarP(&f.o.verbose, "verbose", "v", false, "print every file and every revision, with the decision and its reason")
+ flags.BoolVarP(&f.o.json, "json", "j", false, "print JSON objects, one per line, instead of text")
+ flags.DurationVarP(&f.o.timeout, "timeout", "t", 0, "stop the cleanup gracefully after this time, e.g. 30m or 2h; 0 never stops it")
+ flags.BoolVar(&f.o.request.Shuffle, "shuffle", false, "clean up the spaces and the files within each folder in a random order")
+ flags.BoolVar(&f.async, "async", false, "clean up files in background workers, while looking for more, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC")
+ flags.IntVar(&f.workers, "workers", 0, "the number of background workers, 0 for automatic, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS")
+ flags.IntVar(&f.queueSize, "queue-size", 0, "the number of files that can wait for a worker, 0 for automatic, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE")
+ flags.StringVar(&f.queueFull, "queue-full", string(revisioncleanup.QueueFullBlock), "'block' (wait for room) or 'drop' (skip) files when the queue is full")
+ flags.DurationVar(&f.queueFullTimeout, "queue-full-timeout", 0, "with --queue-full block, skip a file after waiting this long for room, e.g. 10s; 0 waits as long as it takes")
+ return cmd, f
+}
+
+// revisionsCleanupFlags holds the values of the flags of the revisions cleanup command: in o
+// the ones that are used as they are, the others are turned into options by options.
+type revisionsCleanupFlags struct {
+ o revisionsCleanupOptions
+ spaces []string
+ strategy string
+ async bool
+ workers int
+ queueSize int
+ queueFull string
+ // the settings of a full queue, which, unlike the others, don't default to the configured
+ // ones, see the help of the command
+ queueFullTimeout time.Duration
+}
+
+// revisionsCleanupOptions are the settings of a run of the revisions cleanup command
+type revisionsCleanupOptions struct {
+ request revisioncleanup.Request
+ timeout time.Duration
+ verbose bool
+ json bool
+}
+
+// options builds the options of a run from the flags, with the configured strategy and async
+// settings unless the flags override them; changed tells whether a flag was given.
+func (f *revisionsCleanupFlags) options(cfg *config.Config, changed func(name string) bool) (revisionsCleanupOptions, error) {
+ o := f.o
+ r := &o.request
+
+ for _, space := range f.spaces {
+ // accept the ids as the APIs show them, e.g. $
+ id, err := storagespace.ParseID(space)
+ if err != nil {
+ return o, fmt.Errorf("invalid space id %q: %w", space, err)
+ }
+ if id.GetSpaceId() == "" {
+ return o, fmt.Errorf("invalid space id %q: it has no space id", space)
+ }
+ // a resource id of a file or folder within the space would clean up the whole space
+ if node := id.GetOpaqueId(); node != "" && node != id.GetSpaceId() {
+ return o, fmt.Errorf("invalid space id %q: it is the id of a file or folder within space %q, give the space with --space and the file or folder with --path", space, id.GetSpaceId())
+ }
+ r.SpaceIDs = append(r.SpaceIDs, id.GetSpaceId())
+ }
+ if r.Path != "" && len(r.SpaceIDs) == 0 {
+ return o, errors.New("--path requires --space")
+ }
+ err := r.Validate()
+ if err != nil {
+ return o, err
+ }
+ if r.FSPath != "" && cfg.Driver != "posix" {
+ return o, fmt.Errorf("--fs-path is only supported by the 'posix' driver, not by %q", cfg.Driver)
+ }
+
+ r.Strategy = cfg.RevisionsCleanup.Strategy
+ if changed("strategy") {
+ r.Strategy = f.strategy
+ }
+ // check the strategy before the storage is opened
+ switch cleaner, err := revisioncleanup.New(r.Strategy); {
+ case err != nil:
+ return o, fmt.Errorf("invalid strategy %q: %w", r.Strategy, err)
+ case !cleaner.Enabled():
+ return o, errors.New("no strategy: the revisions cleanup is disabled, give one with --strategy or configure STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY")
+ }
+
+ async := revisioncleanup.AsyncOptions{
+ Enabled: cfg.RevisionsCleanup.Async,
+ Workers: cfg.RevisionsCleanup.AsyncWorkers,
+ QueueSize: cfg.RevisionsCleanup.AsyncQueueSize,
+ // not the configured ones, see revisionsCleanupFlags.queueFullTimeout
+ QueueFull: revisioncleanup.QueueFullPolicy(f.queueFull),
+ QueueFullTimeout: f.queueFullTimeout,
+ }
+ if changed("async") {
+ async.Enabled = f.async
+ }
+ if changed("workers") {
+ async.Workers = f.workers
+ }
+ if changed("queue-size") {
+ async.QueueSize = f.queueSize
+ }
+ r.Async = &async
+
+ if o.timeout < 0 {
+ return o, fmt.Errorf("invalid timeout %s", o.timeout)
+ }
+ return o, nil
+}
+
+// runRevisionsCleanup runs the revisions cleanup command and returns its exit code.
+func runRevisionsCleanup(cmd *cobra.Command, cfg *config.Config, f *revisionsCleanupFlags) (int, error) {
+ o, err := f.options(cfg, cmd.Flags().Changed)
+ if err != nil {
+ return 0, err
+ }
+
+ // stop gracefully on ctrl-c as well, also while waiting for NATS
+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ go func() {
+ <-ctx.Done()
+ // Make sure that a second ctrl-c ends the process right away, e.g. when a file
+ // waits for the lock of another process: this context and the one of the root
+ // command keep listening to the signals otherwise. That can leave the blob of a
+ // deleted revision behind, which the help says.
+ signal.Reset()
+ }()
+
+ // warnings, e.g. about revisions dated in the future or a lost connection to NATS;
+ // errors of the cleanup are reported
+ logger := zerolog.New(zerolog.ConsoleWriter{Out: cmd.ErrOrStderr(), TimeFormat: time.RFC3339, NoColor: true}).
+ With().Timestamp().Logger().Level(zerolog.WarnLevel)
+ ctx = logger.WithContext(ctx)
+
+ // a dry run changes nothing on disk, so it may run as any user
+ if !o.request.DryRun {
+ warnAboutStorageOwner(cfg, &logger)
+ }
+ onDemand, err := revisionsCleanupDriver(ctx, cfg, &logger)
+ if err != nil {
+ return 0, err
+ }
+
+ return cleanupRevisions(ctx, onDemand, o, cmd.OutOrStdout())
+}
+
+// cleanupRevisions runs the cleanup with the given options, prints its results to w and
+// returns the exit code of the command.
+func cleanupRevisions(ctx context.Context, onDemand revisioncleanup.OnDemand, o revisionsCleanupOptions, w io.Writer) (int, error) {
+ interrupted := ctx
+ if o.timeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, o.timeout)
+ defer cancel()
+ }
+
+ out := newRevisionsCleanupOutput(w, o)
+ err := onDemand.CleanupRevisionsUnchecked(ctx, o.request, out.report)
+ // Tell the timeout and an interruption by the contexts, not by the error: the storage
+ // can return context errors of its own, e.g. when NATS doesn't answer in time.
+ switch {
+ case err != nil && interrupted.Err() != nil:
+ out.summary("interrupted")
+ return exitFailed, nil
+ case err != nil && ctx.Err() != nil:
+ out.summary(fmt.Sprintf("stopped after the timeout of %s", o.timeout))
+ if out.failed() {
+ return exitFailed, nil
+ }
+ return exitStopped, nil
+ case err != nil:
+ out.summary("")
+ return 0, err
+ }
+ out.summary("")
+ if out.err != nil {
+ return 0, fmt.Errorf("could not write the output: %w", out.err)
+ }
+ if out.failed() {
+ return exitFailed, nil
+ }
+ return 0, nil
+}
+
+// revisionsCleanupDriverConfig returns the name and the configuration of the storage
+// driver to create, without the parts of the storage-users service that would
+// interfere with the running service.
+func revisionsCleanupDriverConfig(cfg *config.Config) (string, map[string]any, error) {
+ // The deprecated driver names "ocis" and "s3ng" are aliases of "decomposed" and
+ // "decomposeds3" since https://github.com/opencloud-eu/opencloud/pull/3859: there
+ // are no driver entries of their own anymore, and StorageProviderDrivers sets the
+ // legacy metadata prefix on the entry of the driver they resolve to. Resolve the
+ // alias like the other storage-users commands (uploads, blobstore) do. When the
+ // aliases are removed, so is storage.EffectiveDriver, and this resolution with it.
+ driver := opencloudstorage.EffectiveDriver(cfg.Driver)
+ drivers := revaconfig.StorageProviderDrivers(cfg)
+ if driver == "posix" {
+ // neither scan nor watch the file system, that is the service's job: e.g. a second
+ // inotifywait would stop the one of the service
+ drivers["posix"] = revaconfig.Posix(cfg, false, false)
+ }
+ driverConfig, ok := drivers[driver].(map[string]any)
+ if !ok {
+ return "", nil, fmt.Errorf("unknown storage driver %q", cfg.Driver)
+ }
+ // Without async uploads, the driver doesn't join the postprocessing consumer group of the
+ // service: the events delivered to this short-lived process would be lost.
+ driverConfig["asyncfileuploads"] = false
+ return driver, driverConfig, nil
+}
+
+// revisionsCleanupDriver creates the storage driver, see revisionsCleanupDriverConfig.
+func revisionsCleanupDriver(ctx context.Context, cfg *config.Config, log *zerolog.Logger) (revisioncleanup.OnDemand, error) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(cfg)
+ if err != nil {
+ return nil, err
+ }
+ newFS, ok := registry.NewFuncs[driver]
+ if !ok {
+ return nil, fmt.Errorf("unknown storage driver %q", cfg.Driver)
+ }
+ var stream events.Stream
+ if driver == "posix" {
+ // posix refuses to start without an event stream
+ stream, err = newEventStream(ctx, cfg, eventStreamTimeout, event.NewStream)
+ if err != nil {
+ return nil, fmt.Errorf("could not create the event stream for the posix driver: %w", err)
+ }
+ }
+
+ // The driver can't be interrupted: e.g. the id cache of the 'posix' driver waits for
+ // NATS for up to 15 minutes. It keeps trying in the background until the command exits.
+ fs, err := interruptible(ctx, func() (storage.FS, error) { return newFS(driverConfig, stream, log) })
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return nil, fmt.Errorf("interrupted while initializing the storage driver %q: %w", cfg.Driver, err)
+ case err != nil:
+ return nil, fmt.Errorf("could not initialize the storage driver %q: %w", cfg.Driver, err)
+ }
+ onDemand, ok := fs.(revisioncleanup.OnDemand)
+ if !ok {
+ return nil, fmt.Errorf("the %q driver can't clean up revisions", cfg.Driver)
+ }
+ return onDemand, nil
+}
+
+// eventStreamTimeout is how long the command waits for NATS. The event stream retries
+// for up to 15 minutes, which suits the service, but not a command: with the single
+// binary, NATS only runs within the server, see
+// https://github.com/opencloud-eu/opencloud/issues/3805
+const eventStreamTimeout = 10 * time.Second
+
+// newEventStream creates the event stream with newStream, but gives up after timeout, or
+// when ctx is done (e.g. on ctrl-c), as newStream itself waits for NATS for up to 15
+// minutes and can't be interrupted. newStream then keeps trying in the background until
+// the command exits.
+func newEventStream[S any](ctx context.Context, cfg *config.Config, timeout time.Duration, newStream func(*config.Config) (S, error)) (S, error) {
+ connect, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ stream, err := interruptible(connect, func() (S, error) { return newStream(cfg) })
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return stream, fmt.Errorf("interrupted while connecting to NATS at %s: %w", cfg.Events.Addr, ctx.Err())
+ case err != nil && connect.Err() != nil:
+ return stream, fmt.Errorf("could not connect to NATS at %s within %s: the command needs NATS, i.e. a running OpenCloud server or a separate NATS", cfg.Events.Addr, timeout)
+ }
+ return stream, err
+}
+
+// interruptible returns what f returns, or the error of ctx when ctx is done first. f
+// then keeps running in the background until the command exits.
+func interruptible[T any](ctx context.Context, f func() (T, error)) (T, error) {
+ type result struct {
+ value T
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ value, err := f()
+ done <- result{value, err}
+ }()
+
+ select {
+ case r := <-done:
+ return r.value, r.err
+ case <-ctx.Done():
+ var none T
+ return none, ctx.Err()
+ }
+}
+
+// userName returns the name of the user with the id uid, or uid if it has no name.
+func userName(uid string) string {
+ u, err := user.LookupId(uid)
+ if err != nil {
+ return uid
+ }
+ return u.Username
+}
+
+// warnAboutStorageOwner logs the warning of storageOwnerWarning for the storage of the driver
+// that the command creates, if there is one.
+func warnAboutStorageOwner(cfg *config.Config, log *zerolog.Logger) {
+ _, driverConfig, err := revisionsCleanupDriverConfig(cfg)
+ if err != nil {
+ // revisionsCleanupDriver reports it
+ return
+ }
+ root, _ := driverConfig["root"].(string)
+ if warning := storageOwnerWarning(root, os.Geteuid()); warning != "" {
+ log.Warn().Msg(warning)
+ }
+}
+
+// storageOwnerWarning returns a warning when the storage at root doesn't belong to the
+// user euid, as the files that the command creates belong to that user, with permissions
+// only for that user: the lock files of the files it cleans up. The
+// server may then not be able to lock these files anymore.
+func storageOwnerWarning(root string, euid int) string {
+ info, err := os.Stat(root)
+ if err != nil {
+ // the driver reports it
+ return ""
+ }
+ st, ok := info.Sys().(*syscall.Stat_t)
+ if !ok || int(st.Uid) == euid {
+ return ""
+ }
+ owner := userName(strconv.FormatUint(uint64(st.Uid), 10))
+ runAs := userName(strconv.Itoa(euid))
+ return fmt.Sprintf("the storage %s belongs to the user %s, but the command runs as %s: the lock files it creates belong to %s, and OpenCloud may not be able to lock these files anymore; run the command as %s, e.g. with 'sudo -u %s'", root, owner, runAs, runAs, owner, owner)
+}
+
+// revisionsCleanupOutput prints the results of a revisions cleanup as they come in, and
+// sums them up.
+type revisionsCleanupOutput struct {
+ w io.Writer
+ o revisionsCleanupOptions
+ enc *json.Encoder
+ spaces map[string]struct{}
+ files int
+ cleaned int // files with deleted revisions
+ deleted int
+ bytes uint64
+ skipped int
+ errors int // files that failed, as a whole or for some of their revisions
+ err error // the first error writing the output
+}
+
+func newRevisionsCleanupOutput(w io.Writer, o revisionsCleanupOptions) *revisionsCleanupOutput {
+ out := &revisionsCleanupOutput{w: w, o: o, spaces: map[string]struct{}{}}
+ if o.json {
+ out.enc = json.NewEncoder(w)
+ }
+ return out
+}
+
+// revisionJSON is a revision in the JSON output
+type revisionJSON struct {
+ Key string `json:"key"`
+ Time time.Time `json:"time"`
+ Size uint64 `json:"size"`
+ Decision string `json:"decision"`
+ Reason string `json:"reason,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// fileJSON is a file in the JSON output
+type fileJSON struct {
+ Type string `json:"type"`
+ SpaceID string `json:"space_id"`
+ NodeID string `json:"node_id"`
+ Path string `json:"path,omitempty"`
+ DryRun bool `json:"dry_run"`
+ Skipped string `json:"skipped,omitempty"`
+ Error string `json:"error,omitempty"`
+ Revisions int `json:"revisions"`
+ Deleted int `json:"deleted"`
+ DeletedBytes uint64 `json:"deleted_bytes"`
+ Failed int `json:"failed"`
+ Details []revisionJSON `json:"details,omitempty"`
+}
+
+// summaryJSON is the summary in the JSON output
+type summaryJSON struct {
+ Type string `json:"type"`
+ DryRun bool `json:"dry_run"`
+ Spaces int `json:"spaces"`
+ Files int `json:"files"`
+ Cleaned int `json:"cleaned"`
+ Deleted int `json:"deleted"`
+ DeletedBytes uint64 `json:"deleted_bytes"`
+ Skipped int `json:"skipped"`
+ Failed int `json:"failed"`
+ Stopped string `json:"stopped,omitempty"`
+}
+
+// report prints the Result of a file, it is called one result at a time.
+func (out *revisionsCleanupOutput) report(r revisioncleanup.Result) {
+ deleted, bytes := r.DeletedCount()
+ failedRevisions := 0
+ for _, rev := range r.Revisions {
+ if rev.Err != nil {
+ failedRevisions++
+ }
+ }
+ failed := r.Err != nil || failedRevisions > 0
+
+ out.spaces[r.SpaceID] = struct{}{}
+ out.files++
+ out.deleted += deleted
+ out.bytes += bytes
+ switch {
+ case failed:
+ out.errors++
+ case r.Skipped != "":
+ out.skipped++
+ }
+ if deleted > 0 {
+ out.cleaned++
+ }
+
+ // without --verbose, only what needs attention or changed something
+ if !out.o.verbose && deleted == 0 && !failed && r.Skipped == "" {
+ return
+ }
+ if out.enc != nil {
+ out.printJSON(r, deleted, bytes, failedRevisions)
+ return
+ }
+ out.printText(r, deleted, bytes, failedRevisions)
+}
+
+func (out *revisionsCleanupOutput) printJSON(r revisioncleanup.Result, deleted int, bytes uint64, failedRevisions int) {
+ f := fileJSON{
+ Type: "file",
+ SpaceID: r.SpaceID,
+ NodeID: r.NodeID,
+ Path: r.Path,
+ DryRun: r.DryRun,
+ Skipped: r.Skipped,
+ Revisions: len(r.Revisions),
+ Deleted: deleted,
+ DeletedBytes: bytes,
+ Failed: failedRevisions,
+ }
+ if r.Err != nil {
+ f.Error = r.Err.Error()
+ }
+ if out.o.verbose {
+ for _, rev := range r.Revisions {
+ d := revisionJSON{Key: rev.Key, Time: rev.Time, Size: rev.Size, Decision: string(rev.Decision), Reason: rev.Reason}
+ if rev.Err != nil {
+ d.Error = rev.Err.Error()
+ }
+ f.Details = append(f.Details, d)
+ }
+ }
+ out.write(out.enc.Encode(f))
+}
+
+func (out *revisionsCleanupOutput) printText(r revisioncleanup.Result, deleted int, bytes uint64, failedRevisions int) {
+ file := r.Path
+ if file == "" || out.o.verbose {
+ file = strings.TrimSpace(file + " (node " + r.NodeID + ")")
+ }
+ line := fmt.Sprintf("%s %s: ", r.SpaceID, file)
+ switch {
+ case r.Err != nil:
+ line += "failed: " + r.Err.Error()
+ case r.Skipped != "":
+ line += "skipped: " + r.Skipped
+ default:
+ verb := "deleted"
+ if r.DryRun {
+ verb = "would delete"
+ }
+ line += fmt.Sprintf("%s %d of %s (%s)", verb, deleted, plural(len(r.Revisions), "revision"), formatBytes(bytes))
+ if failedRevisions > 0 {
+ line += fmt.Sprintf(", %d could not be deleted", failedRevisions)
+ }
+ }
+ _, err := fmt.Fprintln(out.w, line)
+ out.write(err)
+
+ if !out.o.verbose {
+ for _, rev := range r.Revisions {
+ if rev.Err != nil {
+ fmt.Fprintf(out.w, " %s: %s\n", rev.Key, rev.Err)
+ }
+ }
+ return
+ }
+ for _, rev := range r.Revisions {
+ // in the server's time zone, like the times in the reasons
+ fmt.Fprintf(out.w, " %-9s %s %9s %s\n", rev.Decision, rev.Time.Local().Format(time.RFC3339), formatBytes(rev.Size), rev.Reason)
+ if rev.Err != nil {
+ fmt.Fprintf(out.w, " %-9s could not be deleted: %s\n", "", rev.Err)
+ }
+ }
+}
+
+// summary prints the totals, stopped tells why the cleanup stopped early, if it did.
+func (out *revisionsCleanupOutput) summary(stopped string) {
+ if out.enc != nil {
+ out.write(out.enc.Encode(summaryJSON{
+ Type: "summary",
+ DryRun: out.o.request.DryRun,
+ Spaces: len(out.spaces),
+ Files: out.files,
+ Cleaned: out.cleaned,
+ Deleted: out.deleted,
+ DeletedBytes: out.bytes,
+ Skipped: out.skipped,
+ Failed: out.errors,
+ Stopped: stopped,
+ }))
+ return
+ }
+ verb := "deleted"
+ if out.o.request.DryRun {
+ verb = "would delete"
+ }
+ fmt.Fprintf(out.w, "%s in %s: %s %s (%s) of %s, %d skipped, %d failed\n",
+ plural(out.files, "file"), plural(len(out.spaces), "space"), verb, plural(out.deleted, "revision"),
+ formatBytes(out.bytes), plural(out.cleaned, "file"), out.skipped, out.errors)
+ if stopped != "" {
+ fmt.Fprintf(out.w, "The cleanup was %s, before all files were cleaned up.\n", stopped)
+ }
+}
+
+// write records the first error writing the output.
+func (out *revisionsCleanupOutput) write(err error) {
+ if out.err == nil {
+ out.err = err
+ }
+}
+
+// failed tells whether the cleanup of any file failed.
+func (out *revisionsCleanupOutput) failed() bool {
+ return out.errors > 0
+}
+
+// plural returns the count with the noun, e.g. "1 file" or "2 files".
+func plural(n int, noun string) string {
+ if n == 1 {
+ return "1 " + noun
+ }
+ return fmt.Sprintf("%d %ss", n, noun)
+}
+
+// formatBytes formats a size in bytes with a binary unit, e.g. 1.5 MiB.
+func formatBytes(b uint64) string {
+ const unit = 1024
+ if b < unit {
+ return fmt.Sprintf("%d B", b)
+ }
+ div, exp := uint64(unit), 0
+ for n := b / unit; n >= unit; n /= unit {
+ div *= unit
+ exp++
+ }
+ return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
+}
diff --git a/services/storage-users/pkg/command/revisions_test.go b/services/storage-users/pkg/command/revisions_test.go
new file mode 100644
index 0000000000..f2202dac73
--- /dev/null
+++ b/services/storage-users/pkg/command/revisions_test.go
@@ -0,0 +1,417 @@
+package command
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup"
+ "github.com/test-go/testify/require"
+
+ "github.com/opencloud-eu/opencloud/pkg/shared"
+ opencloudstorage "github.com/opencloud-eu/opencloud/pkg/storage"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/defaults"
+)
+
+// revisionsCleanupOptionsFor parses the flags of the revisions cleanup command
+func revisionsCleanupOptionsFor(t *testing.T, cfg *config.Config, args ...string) (revisionsCleanupOptions, error) {
+ t.Helper()
+ cmd, f := revisionsCleanupCommand(cfg)
+ require.NoError(t, cmd.ParseFlags(args))
+ return f.options(cfg, cmd.Flags().Changed)
+}
+
+func revisionsCleanupConfig() *config.Config {
+ return &config.Config{
+ Driver: "decomposed",
+ RevisionsCleanup: config.RevisionsCleanup{
+ Strategy: "auto, 90d",
+ Async: true,
+ AsyncWorkers: 4,
+ AsyncQueueSize: 100,
+ AsyncQueueFull: "drop",
+ AsyncQueueFullTimeout: 5 * time.Second,
+ },
+ }
+}
+
+func TestRevisionsCleanupOptions(t *testing.T) {
+ t.Run("the configuration is the default", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "--all")
+ require.NoError(t, err)
+ require.True(t, o.request.All)
+ require.Equal(t, "auto, 90d", o.request.Strategy)
+ // except for a full queue: the command waits for room as long as it takes
+ require.Equal(t, &revisioncleanup.AsyncOptions{Enabled: true, Workers: 4, QueueSize: 100, QueueFull: revisioncleanup.QueueFullBlock}, o.request.Async)
+ require.False(t, o.request.DryRun)
+ require.False(t, o.request.Shuffle)
+ require.Zero(t, o.timeout)
+ })
+
+ t.Run("flags override the configuration", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(),
+ "--space", "storage$space1!space1", "--space", "space2", "--strategy", "10",
+ "--async=false", "--workers", "0", "--queue-size", "7", "--queue-full", "drop", "--queue-full-timeout", "30s",
+ "--dry-run", "--shuffle", "--timeout", "1h", "--verbose", "--json")
+ require.NoError(t, err)
+ require.Equal(t, []string{"space1", "space2"}, o.request.SpaceIDs, "the space ids as the APIs show them are accepted")
+ require.Equal(t, "10", o.request.Strategy)
+ require.Equal(t, &revisioncleanup.AsyncOptions{Enabled: false, Workers: 0, QueueSize: 7, QueueFull: revisioncleanup.QueueFullDrop, QueueFullTimeout: 30 * time.Second}, o.request.Async)
+ require.True(t, o.request.DryRun)
+ require.True(t, o.request.Shuffle)
+ require.Equal(t, time.Hour, o.timeout)
+ require.True(t, o.verbose)
+ require.True(t, o.json)
+ })
+
+ t.Run("short flags", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "-anvj", "-s", "10", "-t", "30m")
+ require.NoError(t, err)
+ require.True(t, o.request.All)
+ require.True(t, o.request.DryRun)
+ require.True(t, o.verbose)
+ require.True(t, o.json)
+ require.Equal(t, "10", o.request.Strategy)
+ require.Equal(t, 30*time.Minute, o.timeout)
+
+ cfg := revisionsCleanupConfig()
+ cfg.Driver = "posix"
+ o, err = revisionsCleanupOptionsFor(t, cfg, "-p", "/var/lib/opencloud/users/einstein")
+ require.NoError(t, err)
+ require.Equal(t, "/var/lib/opencloud/users/einstein", o.request.FSPath)
+ })
+
+ t.Run("a path within a space", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "--space", "space1", "--path", "/Documents")
+ require.NoError(t, err)
+ require.Equal(t, "/Documents", o.request.Path)
+ })
+
+ t.Run("a path on disk with posix", func(t *testing.T) {
+ cfg := revisionsCleanupConfig()
+ cfg.Driver = "posix"
+ o, err := revisionsCleanupOptionsFor(t, cfg, "--fs-path", "/var/lib/opencloud/users/einstein")
+ require.NoError(t, err)
+ require.Equal(t, "/var/lib/opencloud/users/einstein", o.request.FSPath)
+ })
+
+ for _, tc := range []struct {
+ name string
+ strategy string
+ args []string
+ err string
+ }{
+ {name: "nothing to clean up", err: "no space"},
+ {name: "the id of a file as a space", args: []string{"--space", "storage$space1!node1"}, err: "it is the id of a file or folder within space \"space1\""},
+ {name: "a storage id without a space id", args: []string{"--space", "storage$"}, err: "it has no space id"},
+ {name: "a file id without a space id", args: []string{"--space", "storage$!node1"}, err: "it has no space id"},
+ {name: "a path without a space", args: []string{"--path", "/Documents"}, err: "--path requires --space"},
+ {name: "all and a space", args: []string{"--all", "--space", "space1"}, err: "not both"},
+ {name: "a path in two spaces", args: []string{"--space", "space1", "--space", "space2", "--path", "/Documents"}, err: "exactly one space"},
+ {name: "a path on disk and a space", args: []string{"--fs-path", "/data", "--space", "space1"}, err: "can't be combined"},
+ {name: "a path on disk without posix", args: []string{"--fs-path", "/data"}, err: "only supported by the 'posix' driver"},
+ {name: "the cleanup is disabled", strategy: "disabled", args: []string{"--all"}, err: "--strategy"},
+ {name: "an invalid strategy", args: []string{"--all", "--strategy", "whenever"}, err: "invalid strategy"},
+ {name: "a negative timeout", args: []string{"--all", "--timeout", "-1s"}, err: "invalid timeout"},
+ } {
+ t.Run("rejects "+tc.name, func(t *testing.T) {
+ cfg := revisionsCleanupConfig()
+ if tc.strategy != "" {
+ cfg.RevisionsCleanup.Strategy = tc.strategy
+ }
+ _, err := revisionsCleanupOptionsFor(t, cfg, tc.args...)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), tc.err)
+ })
+ }
+}
+
+// fakeOnDemand reports the given results, and then waits for the end of ctx if wait is set
+type fakeOnDemand struct {
+ results []revisioncleanup.Result
+ wait bool
+ err error
+ request revisioncleanup.Request
+}
+
+func (f *fakeOnDemand) CleanupRevisionsUnchecked(ctx context.Context, req revisioncleanup.Request, report func(revisioncleanup.Result)) error {
+ f.request = req
+ for _, r := range f.results {
+ r.DryRun = req.DryRun
+ report(r)
+ }
+ if f.wait {
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ return f.err
+}
+
+var (
+ revisionsCleanupTime = time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC)
+ // a file with a deleted and a kept revision
+ cleanedFile = revisioncleanup.Result{SpaceID: "space1", NodeID: "node1", Path: "/Documents/report.odt", Revisions: []revisioncleanup.RevisionResult{
+ {Key: "node1.REV.1", Time: revisionsCleanupTime, Size: 1536, Decision: revisioncleanup.Kept, Reason: "kept by \"auto\""},
+ {Key: "node1.REV.2", Time: revisionsCleanupTime.Add(-100 * 24 * time.Hour), Size: 2048, Decision: revisioncleanup.Deleted, Reason: "deleted by \"90d\""},
+ }}
+ // a file with nothing to delete
+ untouchedFile = revisioncleanup.Result{SpaceID: "space1", NodeID: "node2", Path: "/notes.txt", Revisions: []revisioncleanup.RevisionResult{
+ {Key: "node2.REV.1", Time: revisionsCleanupTime, Size: 10, Decision: revisioncleanup.Kept, Reason: "kept by \"auto\""},
+ }}
+ skippedFile = revisioncleanup.Result{SpaceID: "space2", NodeID: "node3", Path: "/upload.bin", Skipped: "an upload to the file is still being processed"}
+ failedFile = revisioncleanup.Result{SpaceID: "space2", NodeID: "node4", Path: "/broken.txt", Err: errors.New("could not list revisions")}
+)
+
+func runFakeRevisionsCleanup(t *testing.T, f *fakeOnDemand, o revisionsCleanupOptions) (int, string, error) {
+ t.Helper()
+ if o.request.Async == nil {
+ o.request = revisioncleanup.Request{All: true, Strategy: "auto, 90d", DryRun: o.request.DryRun}
+ }
+ var out bytes.Buffer
+ code, err := cleanupRevisions(context.Background(), f, o, &out)
+ return code, out.String(), err
+}
+
+func TestRevisionsCleanupOutput(t *testing.T) {
+ t.Run("only the files that changed or need attention, and a summary", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, untouchedFile, skippedFile}}, revisionsCleanupOptions{})
+ require.NoError(t, err)
+ require.Equal(t, 0, code)
+ require.Equal(t, `space1 /Documents/report.odt: deleted 1 of 2 revisions (2.0 KiB)
+space2 /upload.bin: skipped: an upload to the file is still being processed
+3 files in 2 spaces: deleted 1 revision (2.0 KiB) of 1 file, 1 skipped, 0 failed
+`, out)
+ })
+
+ t.Run("a dry run", func(t *testing.T) {
+ o := revisionsCleanupOptions{request: revisioncleanup.Request{DryRun: true}}
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile}}, o)
+ require.NoError(t, err)
+ require.Equal(t, 0, code)
+ require.Contains(t, out, "space1 /Documents/report.odt: would delete 1 of 2 revisions")
+ require.Contains(t, out, "would delete 1 revision (2.0 KiB) of 1 file")
+ })
+
+ t.Run("every file and revision with --verbose", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, untouchedFile}}, revisionsCleanupOptions{verbose: true})
+ require.NoError(t, err)
+ require.Equal(t, 0, code)
+ // the times are in the local time zone, like the ones in the reasons
+ local := func(t time.Time) string { return t.Local().Format(time.RFC3339) }
+ require.Equal(t, `space1 /Documents/report.odt (node node1): deleted 1 of 2 revisions (2.0 KiB)
+ kept `+local(revisionsCleanupTime)+` 1.5 KiB kept by "auto"
+ deleted `+local(revisionsCleanupTime.Add(-100*24*time.Hour))+` 2.0 KiB deleted by "90d"
+space1 /notes.txt (node node2): deleted 0 of 1 revision (0 B)
+ kept `+local(revisionsCleanupTime)+` 10 B kept by "auto"
+2 files in 1 space: deleted 1 revision (2.0 KiB) of 1 file, 0 skipped, 0 failed
+`, out)
+ })
+
+ t.Run("JSON lines", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, untouchedFile, failedFile}}, revisionsCleanupOptions{json: true})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ lines := strings.Split(strings.TrimSpace(out), "\n")
+ require.Len(t, lines, 3, "the untouched file is left out without --verbose")
+
+ var file fileJSON
+ require.NoError(t, json.Unmarshal([]byte(lines[0]), &file))
+ require.Equal(t, fileJSON{Type: "file", SpaceID: "space1", NodeID: "node1", Path: "/Documents/report.odt", Revisions: 2, Deleted: 1, DeletedBytes: 2048}, file)
+ require.NoError(t, json.Unmarshal([]byte(lines[1]), &file))
+ require.Equal(t, "could not list revisions", file.Error)
+
+ var summary summaryJSON
+ require.NoError(t, json.Unmarshal([]byte(lines[2]), &summary))
+ require.Equal(t, summaryJSON{Type: "summary", Spaces: 2, Files: 3, Cleaned: 1, Deleted: 1, DeletedBytes: 2048, Failed: 1}, summary)
+ })
+
+ t.Run("JSON lines with the revisions with --verbose", func(t *testing.T) {
+ _, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile}}, revisionsCleanupOptions{json: true, verbose: true})
+ require.NoError(t, err)
+ var file fileJSON
+ require.NoError(t, json.Unmarshal([]byte(strings.Split(out, "\n")[0]), &file))
+ require.Len(t, file.Details, 2)
+ require.Equal(t, revisionJSON{Key: "node1.REV.2", Time: revisionsCleanupTime.Add(-100 * 24 * time.Hour), Size: 2048, Decision: "deleted", Reason: "deleted by \"90d\""}, file.Details[1])
+ })
+}
+
+func TestRevisionsCleanupExitCodes(t *testing.T) {
+ t.Run("a failed file", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, failedFile}}, revisionsCleanupOptions{})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ require.Contains(t, out, "space2 /broken.txt: failed: could not list revisions")
+ })
+
+ t.Run("a revision that could not be deleted", func(t *testing.T) {
+ file := cleanedFile
+ file.Revisions = append([]revisioncleanup.RevisionResult{}, cleanedFile.Revisions...)
+ file.Revisions[1].Err = errors.New("permission denied")
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{file}}, revisionsCleanupOptions{})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ require.Contains(t, out, "deleted 0 of 2 revisions (0 B), 1 could not be deleted\n node1.REV.2: permission denied\n")
+ })
+
+ t.Run("the cleanup could not run", func(t *testing.T) {
+ code, _, err := runFakeRevisionsCleanup(t, &fakeOnDemand{err: errors.New("could not find space space1")}, revisionsCleanupOptions{})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "could not find space")
+ require.Equal(t, 0, code, "the error itself makes the command fail")
+ })
+
+ t.Run("stopped by the timeout", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile}, wait: true}, revisionsCleanupOptions{timeout: 10 * time.Millisecond})
+ require.NoError(t, err)
+ require.Equal(t, exitStopped, code)
+ require.Contains(t, out, "The cleanup was stopped after the timeout of 10ms, before all files were cleaned up.")
+ })
+
+ t.Run("a context error of the storage is an error, not the timeout", func(t *testing.T) {
+ // e.g. NATS that doesn't answer in time
+ storageErr := fmt.Errorf("could not get the id: %w", context.DeadlineExceeded)
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{err: storageErr}, revisionsCleanupOptions{timeout: time.Hour})
+ require.True(t, errors.Is(err, storageErr), "expected the error of the storage, got %v", err)
+ require.Equal(t, 0, code, "the error itself makes the command fail")
+ require.NotContains(t, out, "timeout")
+ })
+
+ t.Run("interrupted while a timeout is set", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ time.AfterFunc(10*time.Millisecond, cancel)
+ var out bytes.Buffer
+ o := revisionsCleanupOptions{timeout: time.Hour, request: revisioncleanup.Request{All: true, Strategy: "auto"}}
+ code, err := cleanupRevisions(ctx, &fakeOnDemand{wait: true}, o, &out)
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ require.Contains(t, out.String(), "interrupted")
+ })
+
+ t.Run("stopped by the timeout, with a failed file", func(t *testing.T) {
+ code, _, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{failedFile}, wait: true}, revisionsCleanupOptions{timeout: 10 * time.Millisecond})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ })
+}
+
+func TestFormatBytes(t *testing.T) {
+ for in, want := range map[uint64]string{0: "0 B", 1023: "1023 B", 1024: "1.0 KiB", 1536: "1.5 KiB", 5 << 20: "5.0 MiB", 3 << 40: "3.0 TiB"} {
+ require.Equal(t, want, formatBytes(in))
+ }
+}
+
+func TestNewEventStream(t *testing.T) {
+ cfg := &config.Config{}
+ cfg.Events.Addr = "127.0.0.1:9233"
+
+ // blocked stands for a NATS that doesn't answer: newStream returns only when the test ends
+ blocked := func(t *testing.T) func(*config.Config) (string, error) {
+ release := make(chan struct{})
+ t.Cleanup(func() { close(release) })
+ return func(*config.Config) (string, error) {
+ <-release
+ return "", errors.New("released")
+ }
+ }
+
+ t.Run("returns the stream once connected", func(t *testing.T) {
+ stream, err := newEventStream(context.Background(), cfg, time.Second, func(*config.Config) (string, error) {
+ return "stream", nil
+ })
+ require.NoError(t, err)
+ require.Equal(t, "stream", stream)
+ })
+
+ t.Run("returns the error of the stream", func(t *testing.T) {
+ _, err := newEventStream(context.Background(), cfg, time.Second, func(*config.Config) (string, error) {
+ return "", errors.New("bad credentials")
+ })
+ require.EqualError(t, err, "bad credentials")
+ })
+
+ t.Run("gives up after the timeout, and says what it needs", func(t *testing.T) {
+ start := time.Now()
+ _, err := newEventStream(context.Background(), cfg, 50*time.Millisecond, blocked(t))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "could not connect to NATS at 127.0.0.1:9233 within 50ms")
+ require.Contains(t, err.Error(), "a running OpenCloud server or a separate NATS")
+ require.True(t, time.Since(start) < 5*time.Second, "it should give up long before 5s")
+ })
+
+ t.Run("stops when interrupted", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ time.AfterFunc(50*time.Millisecond, cancel)
+ _, err := newEventStream(ctx, cfg, time.Minute, blocked(t))
+ require.True(t, errors.Is(err, context.Canceled), "expected context.Canceled, got %v", err)
+ require.Contains(t, err.Error(), "interrupted while connecting to NATS")
+ })
+}
+
+func TestStorageOwnerWarning(t *testing.T) {
+ root := t.TempDir()
+
+ t.Run("none for the owner of the storage", func(t *testing.T) {
+ require.Empty(t, storageOwnerWarning(root, os.Geteuid()))
+ })
+
+ t.Run("another user", func(t *testing.T) {
+ warning := storageOwnerWarning(root, os.Geteuid()+1)
+ require.Contains(t, warning, "the storage "+root+" belongs to the user ")
+ require.Contains(t, warning, "sudo -u")
+ })
+
+ t.Run("none without a storage", func(t *testing.T) {
+ require.Empty(t, storageOwnerWarning(filepath.Join(root, "missing"), os.Geteuid()+1))
+ })
+}
+
+// TestRevisionsCleanupDriverConfig doesn't create the drivers: the metadata prefix is
+// process wide, and the legacy prefix of the aliases would clash with the prefix that
+// TestDeleteStaleNodesHonoursMetadataPrefix fixes for the whole package.
+func TestRevisionsCleanupDriverConfig(t *testing.T) {
+ newConfig := func(driver string) *config.Config {
+ cfg := defaults.FullDefaultConfig()
+ cfg.Commons = &shared.Commons{GRPCClientTLS: &shared.GRPCClientTLS{}}
+ cfg.Driver = driver
+ return cfg
+ }
+
+ for _, tc := range []struct{ driver, effective, prefix string }{
+ // the configured prefix, empty by default: then reva uses its own default
+ {"decomposed", "decomposed", ""},
+ {"decomposeds3", "decomposeds3", ""},
+ // the deprecated driver names are aliases, see revisionsCleanupDriverConfig
+ {"ocis", "decomposed", opencloudstorage.LegacyMetadataPrefix()},
+ {"s3ng", "decomposeds3", opencloudstorage.LegacyMetadataPrefix()},
+ } {
+ t.Run(tc.driver, func(t *testing.T) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig(tc.driver))
+ require.NoError(t, err)
+ require.Equal(t, tc.effective, driver)
+ require.Equal(t, tc.prefix, driverConfig["metadata_prefix"])
+ require.Equal(t, false, driverConfig["asyncfileuploads"])
+ })
+ }
+
+ t.Run("posix neither scans nor watches", func(t *testing.T) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig("posix"))
+ require.NoError(t, err)
+ require.Equal(t, "posix", driver)
+ require.Equal(t, false, driverConfig["scan_fs"])
+ require.Equal(t, false, driverConfig["watch_fs"])
+ require.Equal(t, false, driverConfig["asyncfileuploads"])
+ })
+
+ t.Run("unknown driver", func(t *testing.T) {
+ _, _, err := revisionsCleanupDriverConfig(newConfig("nonexistent"))
+ require.EqualError(t, err, `unknown storage driver "nonexistent"`)
+ })
+}
diff --git a/services/storage-users/pkg/command/root.go b/services/storage-users/pkg/command/root.go
index db14b09efb..0b357698db 100644
--- a/services/storage-users/pkg/command/root.go
+++ b/services/storage-users/pkg/command/root.go
@@ -19,6 +19,7 @@ func GetCommands(cfg *config.Config) []*cobra.Command {
Uploads(cfg),
TrashBin(cfg),
Blobstore(cfg),
+ Revisions(cfg),
// infos about this service
Health(cfg),