Merge branch 'origin/main' into 'next-release/main'

This commit is contained in:
oauth committed 2026-11-24 15:15:09 +00:00
commit bd6bde91ad
19 files changed
+2031 -5

No files matched your search

+3
View File
@@ -121,6 +121,9 @@ the command is aborted with an error before performing any scanning.`,
// We want to initialize the driver but disable scanfs on boot, so we can trigger it manually afterwards
drivers := revaconfig.StorageProviderDrivers(cfg)
drivers["posix"] = revaconfig.Posix(cfg, false, false)
// Clean up revisions without background workers: the command could exit before
// they are done, and stop the cleanup of a file midway.
drivers["posix"].(map[string]any)["revisions_cleanup_async"] = false
var fsStream events.Stream
var err error
+33 -1
View File
@@ -547,6 +547,7 @@ var testCases = []struct {
Event: events.SpaceDeleted{
Executant: userID("uid-123"),
ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
SpaceName: "test-space",
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -554,10 +555,41 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' (storage: 'storage-1')", "space_deleted")
checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name 'test-space' (storage: 'storage-1')", "space_deleted")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
}, {
Alias: "Space deleted - unicode name",
SystemEvent: events.Event{
Event: events.SpaceDeleted{
Executant: userID("uid-123"),
ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
SpaceName: "Prüfung 📁 空间",
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
ev := types.AuditEventSpaceDeleted{}
require.NoError(t, json.Unmarshal(b, &ev))
checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name 'Prüfung 📁 空间' (storage: 'storage-1')", "space_deleted")
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
}, {
Alias: "Space deleted - empty name",
SystemEvent: events.Event{
Event: events.SpaceDeleted{
Executant: userID("uid-123"),
ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
ev := types.AuditEventSpaceDeleted{}
require.NoError(t, json.Unmarshal(b, &ev))
checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name '' (storage: 'storage-1')", "space_deleted")
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
},
{
Alias: "ScienceMesh - InviteTokenGenerated",
+1 -1
View File
@@ -378,7 +378,7 @@ func SpaceEnabled(ev events.SpaceEnabled) AuditEventSpaceEnabled {
// SpaceDeleted converts a SpaceDeleted event to an AuditEventSpaceDeleted
func SpaceDeleted(ev events.SpaceDeleted) AuditEventSpaceDeleted {
sid := ev.ID.GetOpaqueId()
base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDeleted(ev.Executant.GetOpaqueId(), sid), ActionSpaceDeleted)
base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDeleted(ev.Executant.GetOpaqueId(), sid, ev.SpaceName), ActionSpaceDeleted)
return AuditEventSpaceDeleted{
AuditEventSpaces: SpacesAuditEvent(base, sid),
}
+2 -2
View File
@@ -166,9 +166,9 @@ func MessageSpaceEnabled(executant, spaceID string) string {
}
// MessageSpaceDeleted returns the human-readable string that describes the action
func MessageSpaceDeleted(executant, spaceID string) string {
func MessageSpaceDeleted(executant, spaceID, name string) string {
storagID, spaceID := storagespace.SplitStorageID(spaceID)
return fmt.Sprintf("user '%s' deleted the space '%s' (storage: '%s')", executant, spaceID, storagID)
return fmt.Sprintf("user '%s' deleted the space '%s' with name '%s' (storage: '%s')", executant, spaceID, name, storagID)
}
// MessageSpaceShared returns the human-readable string that describes the action
+135 -1
View File
@@ -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 <command>
@@ -333,6 +333,140 @@ 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.
The server must learn about the revisions the command deletes, so its file metadata cache must be shared between processes, e.g. with `STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv` (see [Caching](#caching); `OC_CACHE_STORE` would set the cache store of all services). With a cache that each process keeps in its own memory, `memory` (the default) or `ocmem`, the server doesn't learn about them. It lists the versions of a file from disk all the same, so a new list is right, but a list that is already open, for example in the Versions panel, keeps showing the deleted versions, and downloading or restoring one of them fails. The command therefore refuses to run with such a cache, unless `--allow-local-cache` is given. A dry run deletes nothing the server would have to learn about: it always keeps a cache of its own in its memory, whatever is configured, so that it doesn't fill the shared cache with the metadata of every file it looks at.
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` |
A restore keeps the revision of the content it replaced as long as the file has the restored content: the strategy doesn't apply to that one revision, not even an age limit like `30d`, until the file is changed again, by an upload, another restore or, with `posix`, a change on disk.
Note that the age of a revision is the time it was created, i.e. when the file was changed and its previous content became the revision, by the clock of the server. The revisions are also ordered by it, e.g. for a number of revisions to keep. It is not the modification time of the content of the revision, which is the date the version list shows for it, as clients can set that to any time. A document that was unchanged for two months gets a revision that is a few seconds old when it is changed, and e.g. `30d` keeps that revision for 30 days. `auto` keeps the oldest revision of each time slot, which holds the content the file had when the slot began. Revisions created before OpenCloud recorded the time of their creation get an estimate: the time they were replaced, as far as it can be told from the dates of the newer revisions and of the file.
#### Selecting the Files
Exactly one of these selects the files to clean up:
* `--space <id>`: all files of a space. It can be given several times. The space IDs are accepted as the APIs show them, e.g. `<storage id>$<space id>`. The ID of a file or folder within the space (`<storage id>$<space id>!<node id>`) is rejected: give the space with `--space` and the file or folder with `--path`.
* `--space <id> --path <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 <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. |
| `--allow-local-cache` | off | Run even though the file metadata cache is kept in the memory of each process, see above. |
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. The time is when the revision was created, see above, which can differ from the date the version list shows for it:
```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:
@@ -0,0 +1,757 @@
package command
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/signal"
"os/user"
"slices"
"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"
"github.com/opencloud-eu/reva/v3/pkg/store"
)
// 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 <id> all files of a space, repeatable; with --path, only that file or
folder within the space
--all all files of all spaces
--fs-path <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.
The server must learn about the revisions the command deletes: its file metadata cache must
be shared between processes, e.g. with STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv.
With a cache kept in the memory of each process ('memory', the default, or 'ocmem'), the
server lists the versions of a file from disk all the same, but a list of versions that is
already open keeps showing the deleted ones, and downloading or restoring one of them fails.
The command therefore refuses to run with such a cache, unless --allow-local-cache is given.
A dry run always keeps a cache of its own in its memory: it deletes nothing the server would
have to learn about, and leaves the shared cache alone.
--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 <space id> --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")
flags.BoolVar(&f.allowLocalCache, "allow-local-cache", false, "run even though the file metadata cache is kept in the memory of each process, so that the server doesn't learn about the deleted revisions")
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
// run even with a file metadata cache local to each process, see checkFileMetadataCache
allowLocalCache bool
}
// 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. <storage id>$<space id>
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)
}
// a dry run deletes nothing, so the server's cache can't go stale
if !r.DryRun && !f.allowLocalCache {
if err := checkFileMetadataCache(cfg.FilemetadataCache.Store); err != nil {
return o, err
}
}
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
}
// localCacheStores are the cache stores that keep the cache in the memory of each process.
var localCacheStores = []string{store.TypeMemory, store.TypeOCMem}
// checkFileMetadataCache returns an error if the file metadata cache of the storage is kept in the
// memory of each process. The command runs in a process of its own, so the server doesn't learn
// about the revisions it deletes. The server lists the revisions of a file from disk, so a new
// list is right, but a list that is already open, e.g. in the Versions panel, keeps showing the
// deleted ones, and downloading or restoring one of them fails with "not found", as they are gone
// from disk.
func checkFileMetadataCache(storeType string) error {
if !slices.Contains(localCacheStores, storeType) {
return nil
}
return fmt.Errorf("the file metadata cache of the storage-users service is kept in the memory of each process (store %q): "+
"the server doesn't learn about the revisions this command deletes, so a list of versions that is already open keeps showing them, "+
"and downloading or restoring one of them fails. "+
"Share the cache by setting STORAGE_USERS_FILEMETADATA_CACHE_STORE to 'nats-js-kv' "+
"(OC_CACHE_STORE would set the cache store of all services), or run the command anyway with --allow-local-cache", storeType)
}
// 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, o.request.DryRun, &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.
//
// A dry run gets a file metadata cache of its own, in its memory, whatever is configured, see
// dryRunFileMetadataCache.
func revisionsCleanupDriverConfig(cfg *config.Config, dryRun bool) (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
if dryRun {
if err := dryRunFileMetadataCache(driverConfig); err != nil {
return "", nil, err
}
}
return driver, driverConfig, nil
}
// dryRunFileMetadataCache makes the driver keep its file metadata cache in the memory of the
// process. A dry run reads the metadata of every file it looks at: with a cache shared with the
// server, e.g. 'nats-js-kv', it would fill that cache with entries for all of them, for a run that
// changes nothing. It doesn't need the shared cache either, as it deletes nothing that the server
// would have to see, and a cache of its own starts empty, so that it reads the metadata from disk.
// That a command walking a whole space should not fill the shared cache is one of the open points
// of https://github.com/opencloud-eu/opencloud/issues/4064, which proposes 'nats-js-kv' as the
// default.
func dryRunFileMetadataCache(driverConfig map[string]any) error {
cache, ok := driverConfig["filemetadatacache"].(map[string]any)
if !ok {
return errors.New("the storage driver has no file metadata cache configuration")
}
cache["cache_store"] = store.TypeMemory
return nil
}
// revisionsCleanupDriver creates the storage driver, see revisionsCleanupDriverConfig.
func revisionsCleanupDriver(ctx context.Context, cfg *config.Config, dryRun bool, log *zerolog.Logger) (revisioncleanup.OnDemand, error) {
driver, driverConfig, err := revisionsCleanupDriverConfig(cfg, dryRun)
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, false)
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])
}
@@ -0,0 +1,458 @@
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",
FilemetadataCache: config.FilemetadataCache{Store: "nats-js-kv"},
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 file metadata cache local to each process", func(t *testing.T) {
for _, storeType := range []string{"memory", "ocmem"} {
cfg := revisionsCleanupConfig()
cfg.FilemetadataCache.Store = storeType
_, err := revisionsCleanupOptionsFor(t, cfg, "--all")
require.Error(t, err, storeType)
require.Contains(t, err.Error(), "'nats-js-kv'", "the error names the fix")
require.Contains(t, err.Error(), "--allow-local-cache", "the error names the override")
_, err = revisionsCleanupOptionsFor(t, cfg, "--all", "--allow-local-cache")
require.NoError(t, err, "with the override, %s", storeType)
_, err = revisionsCleanupOptionsFor(t, cfg, "--all", "--dry-run")
require.NoError(t, err, "a dry run deletes nothing, %s", storeType)
}
for _, storeType := range []string{"nats-js-kv", "redis-sentinel", "noop"} {
cfg := revisionsCleanupConfig()
cfg.FilemetadataCache.Store = storeType
_, err := revisionsCleanupOptionsFor(t, cfg, "--all")
require.NoError(t, err, storeType)
}
})
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), false)
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"), false)
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("a dry run keeps a file metadata cache of its own", func(t *testing.T) {
for _, driver := range []string{"decomposed", "decomposeds3", "posix"} {
cfg := newConfig(driver)
cfg.FilemetadataCache.Store = "nats-js-kv"
_, driverConfig, err := revisionsCleanupDriverConfig(cfg, true)
require.NoError(t, err, driver)
require.Equal(t, "memory", driverConfig["filemetadatacache"].(map[string]any)["cache_store"], driver)
_, driverConfig, err = revisionsCleanupDriverConfig(cfg, false)
require.NoError(t, err, driver)
require.Equal(t, "nats-js-kv", driverConfig["filemetadatacache"].(map[string]any)["cache_store"], "a real run uses the configured cache, %s", driver)
}
})
t.Run("unknown driver", func(t *testing.T) {
_, _, err := revisionsCleanupDriverConfig(newConfig("nonexistent"), false)
require.EqualError(t, err, `unknown storage driver "nonexistent"`)
})
}
@@ -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),
@@ -117,6 +117,9 @@ func ListUploadSessions(cfg *config.Config) *cobra.Command {
fmt.Fprintf(os.Stderr, "No configuration found for filesystem driver '%s'\n", cfg.Driver)
os.Exit(1)
}
// Clean up revisions without background workers: the command could exit before
// they are done, and stop the cleanup of a file midway.
driverConf["revisions_cleanup_async"] = false
fs, err := f(driverConf, fsStream, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize filesystem driver '%s'\n", cfg.Driver)
@@ -30,6 +30,7 @@ type Config struct {
Events Events `yaml:"events"`
FilemetadataCache FilemetadataCache `yaml:"filemetadata_cache"`
IDCache IDCache `yaml:"id_cache"`
RevisionsCleanup RevisionsCleanup `yaml:"revisions_cleanup"`
MountID string `yaml:"mount_id" env:"STORAGE_USERS_MOUNT_ID" desc:"Mount ID of this storage." introductionVersion:"1.0.0"`
ReadOnly bool `yaml:"readonly" env:"STORAGE_USERS_READ_ONLY" desc:"Set this storage to be read-only." introductionVersion:"1.0.0"`
UploadExpiration int64 `yaml:"upload_expiration" env:"STORAGE_USERS_UPLOAD_EXPIRATION" desc:"Duration in seconds after which uploads will expire. Note that when setting this to a low number, uploads could be cancelled before they are finished and return a 403 to the user." introductionVersion:"1.0.0"`
@@ -226,6 +227,16 @@ type Events struct {
// TODO use TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OC_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"1.0.0"`
}
// RevisionsCleanup configures the deletion of old revisions, for the 'decomposed', 'decomposeds3' and 'posix' storage drivers
type RevisionsCleanup struct {
Strategy string `yaml:"strategy" env:"STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY" desc:"Which old revisions (versions) of a file to delete whenever the file gets a new revision. 'disabled' keeps all revisions. A strategy is a comma-separated list of up to three parts: a number of revisions, which counts from the newest one (e.g. '10'), a duration with one of the units 'w', 'd', 'h', 'm' or 's' (e.g. '30d'; with the uppercase units 'D' and 'W', days and weeks count from midnight, e.g. '1D'), and 'auto', which thins out revisions the older they get. 'X' deletes everything beyond X, e.g. '10', '30d', or '0' to delete all revisions. 'X, auto' keeps everything within X and thins out the older revisions, e.g. '14d, auto'. 'auto, X' deletes everything beyond X and thins out the rest, e.g. 'auto, 90d'. 'X1, X2' keeps everything within X1 and deletes everything beyond X2, e.g. '5, 30d'. 'X1, auto, X2' also thins out in between, e.g. '7d, auto, 90d'. The age of a revision is the time it was created, i.e. when the file was changed and its previous content became the revision, not the modification time of that content, which the version list shows. Only files that get a new revision are cleaned up, including revisions created from changes on disk with posix. An invalid value makes the storage driver fail at startup." introductionVersion:"%%NEXT%%"`
Async bool `yaml:"async" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC" desc:"Run the revision cleanup in background workers, so that it does not slow down the upload, restore or change that created the new revision. When set to false, the cleanup runs right away." introductionVersion:"%%NEXT%%"`
AsyncWorkers int `yaml:"async_workers" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS" desc:"Number of background workers for the revision cleanup. A value of 0 determines it automatically: half the available CPUs, respecting container CPU limits, but at least 2." introductionVersion:"%%NEXT%%"`
AsyncQueueSize int `yaml:"async_queue_size" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE" desc:"Number of files that can wait for a background revision cleanup. A value of 0 determines it automatically: 64 per worker." introductionVersion:"%%NEXT%%"`
AsyncQueueFull string `yaml:"async_queue_full" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL" desc:"What happens when a file gets a new revision while the revision cleanup queue is full. 'drop' skips the cleanup of that file, which is cleaned up with its next revision. 'block' waits for room, up to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT." introductionVersion:"%%NEXT%%"`
AsyncQueueFullTimeout time.Duration `yaml:"async_queue_full_timeout" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT" desc:"How long 'block' (see STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL) waits for room in the revision cleanup queue at most, after which the cleanup of that file is skipped as with 'drop'. A value of 0 waits as long as it takes, so that no cleanup is ever skipped, but then writes can slow down without bound under heavy load. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
}
// FilemetadataCache holds cache config
type FilemetadataCache struct {
Store string `yaml:"store" env:"OC_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"1.0.0"`
@@ -173,6 +173,12 @@ func DefaultConfig() *config.Config {
Nodes: []string{"127.0.0.1:9233"},
Database: "ids-storage-users",
},
RevisionsCleanup: config.RevisionsCleanup{
Strategy: "disabled",
Async: true,
AsyncQueueFull: "drop",
AsyncQueueFullTimeout: 5 * time.Second,
},
Tasks: config.Tasks{
PurgeTrashBin: config.PurgeTrashBin{
ProjectDeleteBefore: 30 * 24 * time.Hour,
@@ -104,6 +104,13 @@ func Posix(cfg *config.Config, enableFSScan, enableFSWatch bool) map[string]any
"metadata_prefix": cfg.Drivers.Posix.MetadataPrefix,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"propagator": cfg.Drivers.Posix.Propagator,
"revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
"revisions_cleanup_async": cfg.RevisionsCleanup.Async,
"revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
"revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
"revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
"revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"async_propagator_options": map[string]any{
"propagation_delay": cfg.Drivers.Posix.AsyncPropagatorOptions.PropagationDelay,
},
@@ -209,6 +216,13 @@ func Decomposed(cfg *config.Config) map[string]any {
"max_quota": cfg.Drivers.Decomposed.MaxQuota,
"disable_versioning": cfg.Drivers.Decomposed.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
"revisions_cleanup_async": cfg.RevisionsCleanup.Async,
"revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
"revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
"revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
"revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -269,6 +283,13 @@ func DecomposedNoEvents(cfg *config.Config) map[string]any {
"max_quota": cfg.Drivers.Decomposed.MaxQuota,
"disable_versioning": cfg.Drivers.Decomposed.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
"revisions_cleanup_async": cfg.RevisionsCleanup.Async,
"revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
"revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
"revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
"revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -334,6 +355,13 @@ func DecomposedS3(cfg *config.Config) map[string]any {
"disable_versioning": cfg.Drivers.DecomposedS3.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"asyncfileuploads": cfg.Drivers.DecomposedS3.AsyncUploads,
"revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
"revisions_cleanup_async": cfg.RevisionsCleanup.Async,
"revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
"revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
"revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
"revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -398,6 +426,13 @@ func DecomposedS3NoEvents(cfg *config.Config) map[string]any {
"disable_versioning": cfg.Drivers.DecomposedS3.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"lock_cycle_duration_factor": cfg.Drivers.DecomposedS3.LockCycleDurationFactor,
"revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
"revisions_cleanup_async": cfg.RevisionsCleanup.Async,
"revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
"revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
"revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
"revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -1,8 +1,11 @@
package revaconfig
import (
"errors"
"testing"
"time"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options"
"github.com/test-go/testify/require"
"github.com/opencloud-eu/opencloud/pkg/config/envdecode"
@@ -60,3 +63,53 @@ func TestLegacyDriverAliases(t *testing.T) {
})
}
}
func TestRevisionsCleanupReachesAllDrivers(t *testing.T) {
drivers := func(t *testing.T) map[string]map[string]any {
cfg := defaults.FullDefaultConfig()
cfg.Commons = &shared.Commons{GRPCClientTLS: &shared.GRPCClientTLS{}}
if err := envdecode.Decode(cfg); !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) {
require.NoError(t, err)
}
return map[string]map[string]any{
"posix": Posix(cfg, false, false),
"decomposed": Decomposed(cfg),
"decomposed no events": DecomposedNoEvents(cfg),
"decomposeds3": DecomposedS3(cfg),
"decomposeds3 no events": DecomposedS3NoEvents(cfg),
}
}
t.Run("defaults keep all revisions", func(t *testing.T) {
for name, driver := range drivers(t) {
o, err := options.New(driver)
require.NoError(t, err, name)
require.Equal(t, "disabled", o.RevisionsCleanupStrategy, name)
require.True(t, o.RevisionsCleanupAsync, name)
require.Equal(t, 0, o.RevisionsCleanupAsyncWorkers, name)
require.Equal(t, 0, o.RevisionsCleanupAsyncQueueSize, name)
require.Equal(t, "drop", o.RevisionsCleanupAsyncQueueFull, name)
require.Equal(t, 5*time.Second, o.RevisionsCleanupAsyncQueueFullTimeout, name)
}
})
t.Run("environment variables", func(t *testing.T) {
t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY", "7d, auto, 90d")
t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC", "false")
t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS", "3")
t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE", "42")
t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL", "block")
t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT", "1m")
for name, driver := range drivers(t) {
// decoded by reva, so that a key it does not know would show up as a default value
o, err := options.New(driver)
require.NoError(t, err, name)
require.Equal(t, "7d, auto, 90d", o.RevisionsCleanupStrategy, name)
require.False(t, o.RevisionsCleanupAsync, name)
require.Equal(t, 3, o.RevisionsCleanupAsyncWorkers, name)
require.Equal(t, 42, o.RevisionsCleanupAsyncQueueSize, name)
require.Equal(t, "block", o.RevisionsCleanupAsyncQueueFull, name)
require.Equal(t, time.Minute, o.RevisionsCleanupAsyncQueueFullTimeout, name)
}
})
}
+162
View File
@@ -336,6 +336,168 @@ class CliContext implements Context {
$this->featureContext->setResponse(CliHelper::runCommand($body));
}
/**
* runs the revisions cleanup command with the files to clean up and further flags
*
* @param string $scope the flags that select the files, e.g. "--all"
* @param string $flags e.g. "--strategy 1 --dry-run"
*
* @return void
*/
private function cleanUpFileVersions(string $scope, string $flags): void {
// The test server keeps its file metadata cache in memory, the default, which the command
// refuses unless it is allowed: the scenarios check the versions through the API, which
// lists them from disk, so the cache of the server going stale doesn't matter here.
$command = \trim("storage-users revisions cleanup --allow-local-cache $scope $flags");
$body = [
"command" => $command
];
$this->featureContext->setResponse(CliHelper::runCommand($body));
}
/**
*
* @param string $flags
*
* @return void
*/
#[When('the administrator cleans up the file versions using the CLI with flags :flags')]
public function theAdministratorCleansUpTheFileVersionsUsingTheCliWithFlags(string $flags): void {
$this->cleanUpFileVersions("", $flags);
}
/**
*
* @param string $flags
*
* @return void
*/
#[When('the administrator cleans up the file versions of all spaces using the CLI with flags :flags')]
public function theAdministratorCleansUpTheFileVersionsOfAllSpacesUsingTheCliWithFlags(string $flags): void {
$this->cleanUpFileVersions("--all", $flags);
}
/**
*
* @param string $space
* @param string $user
* @param string $flags
*
* @return void
*/
#[When('the administrator cleans up the file versions of space :space of user :user using the CLI with flags :flags')]
public function theAdministratorCleansUpTheFileVersionsOfSpaceUsingTheCliWithFlags(
string $space,
string $user,
string $flags
): void {
$spaceId = $this->spacesContext->getSpaceIdByName($user, $space);
$this->cleanUpFileVersions("--space $spaceId", $flags);
}
/**
*
* @param string $path
* @param string $space
* @param string $user
* @param string $flags
*
* @return void
*/
#[When('the administrator cleans up the file versions of :path in space :space of user :user using the CLI with flags :flags')]
public function theAdministratorCleansUpTheFileVersionsOfPathInSpaceUsingTheCliWithFlags(
string $path,
string $space,
string $user,
string $flags
): void {
$spaceId = $this->spacesContext->getSpaceIdByName($user, $space);
$this->cleanUpFileVersions("--space $spaceId --path $path", $flags);
}
/**
*
* @param string $path
* @param string $user
* @param string $flags
*
* @return void
*/
#[When('the administrator cleans up the file versions of :path of user :user by its path on the POSIX filesystem using the CLI with flags :flags')]
public function theAdministratorCleansUpTheFileVersionsByPathOnPosixUsingTheCliWithFlags(
string $path,
string $user,
string $flags
): void {
$userUuid = $this->featureContext->getAttributeOfCreatedUser($user, 'id');
$fsPath = $this->getUsersStoragePath() . "/$userUuid/" . \ltrim($path, '/');
$this->cleanUpFileVersions("--fs-path $fsPath", $flags);
}
/**
*
* @param int $exitCode
*
* @return void
*/
#[Then('the command should exit with code :exitCode')]
public function theCommandShouldExitWithCode(int $exitCode): void {
$response = $this->featureContext->getResponse();
$this->featureContext->theHTTPStatusCodeShouldBe(200, '', $response);
$jsonResponse = $this->featureContext->getJsonDecodedResponse($response);
Assert::assertSame(
$exitCode,
$jsonResponse["exitCode"],
"Expected exit code $exitCode, but got " . $jsonResponse["exitCode"]
. ". Message: " . $jsonResponse["message"]
);
}
/**
* checks the output of a command that prints JSON objects, one per line, e.g. with --json,
* for an object with a "type" and the given values
*
* @param string $type
* @param TableNode $table with the columns "key" and "value"
*
* @return void
*/
#[Then('the JSON output of the command should contain an object of type :type with:')]
public function theJsonOutputOfTheCommandShouldContainAnObjectOfTypeWith(string $type, TableNode $table): void {
$response = $this->featureContext->getResponse();
$message = $this->featureContext->getJsonDecodedResponse($response)["message"];
$expected = [];
foreach ($table->getHash() as $row) {
$expected[$row['key']] = $this->featureContext->substituteInLineCodes($row['value']);
}
// other lines, e.g. log messages, are not JSON objects
foreach (\preg_split('/\r?\n/', $message) as $line) {
$object = \json_decode(\trim($line), true);
if (!\is_array($object) || ($object["type"] ?? null) !== $type) {
continue;
}
$matches = true;
foreach ($expected as $key => $value) {
$actual = $object[$key] ?? null;
if (\is_bool($actual)) {
$actual = $actual ? "true" : "false";
}
if ((string)$actual !== $value) {
$matches = false;
break;
}
}
if ($matches) {
return;
}
}
Assert::fail(
"No JSON object of type '$type' with " . \json_encode($expected) . " in the output:\n$message"
);
}
/**
*
* @return void
@@ -84,6 +84,36 @@ class FilesVersionsContext implements Context {
$this->featureContext->setResponse($this->getFileVersions($user, $file));
}
/**
* for changes that happen in the background, e.g. the revision cleanup after postprocessing
*
* @param string $file
* @param string $user
* @param int $number
*
* @return void
* @throws Exception
*/
#[Then('the number of versions of file :file for user :user should eventually be :number')]
public function theNumberOfVersionsOfFileForUserShouldEventuallyBe(string $file, string $user, int $number): void {
$actualNumber = null;
for ($attempt = 0; $attempt < 20; $attempt++) {
$response = $this->getFileVersions($user, $file);
$this->featureContext->theHTTPStatusCodeShouldBe(207, '', $response);
$responseXmlObject = HttpRequestHelper::getResponseXml($response, __METHOD__);
$actualNumber = \count($responseXmlObject->xpath("//d:getlastmodified"));
if ($actualNumber === $number) {
return;
}
\usleep(500000);
}
Assert::assertEquals(
$number,
$actualNumber,
"Expected number of versions of file '$file' was '$number', but got '$actualNumber' after 10 seconds"
);
}
/**
*
* @param string $file
+30
View File
@@ -2371,6 +2371,36 @@ trait WebDav {
$this->setResponse($response);
}
/**
*
* @param string $user
* @param string|null $content
* @param string $mtime e.g. "-60 days", anything DateTime accepts
* @param string $destination
*
* @return void
* @throws Exception
*/
#[Given('user :user has uploaded a file with content :content and mtime :mtime to :destination')]
public function userHasUploadedAFileWithContentAndMtimeTo(
string $user,
?string $content,
string $mtime,
string $destination
): void {
$user = $this->getActualUsername($user);
$mtime = new DateTime($mtime);
$mtime = $mtime->format('U');
$response = $this->makeDavRequest(
$user,
"PUT",
$destination,
["X-OC-Mtime" => $mtime],
$content
);
$this->theHTTPStatusCodeShouldBe(["201", "204"], "", $response);
}
/**
* @param string $user
* @param string $checksum
+1
View File
@@ -493,6 +493,7 @@ default:
- OcConfigContext:
- SharingNgContext:
- PublicWebDavContext:
- FilesVersionsContext:
coreApiMain:
paths:
@@ -0,0 +1,255 @@
@env-config
Feature: clean up old file versions according to a cleanup strategy
As an administrator
I want to delete old file versions according to a cleanup strategy
So that files that are not changed anymore don't keep all their old versions
# The strategies are written without spaces, as the CLI wrapper splits commands on spaces;
# "2,auto,10" is the same as "2, auto, 10".
Background:
Given user "Alice" has been created with default attributes
Scenario: keep only the newest version of every file in all spaces
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
And user "Alice" has uploaded file with content "version 1" to "anotherFile.txt"
And user "Alice" has uploaded file with content "version 2" to "anotherFile.txt"
When the administrator cleans up the file versions of all spaces using the CLI with flags "--strategy 1"
Then the command should be successful
And the command output should contain "/textfile.txt: deleted 2 of 3 revisions"
And the command output should not contain "/anotherFile.txt"
And the command output should contain "deleted 2 revisions"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
When user "Alice" gets the number of versions of file "anotherFile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
And the content of file "textfile.txt" for user "Alice" should be "version 4"
Scenario: a dry run only prints what would be deleted
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0 --dry-run"
Then the command should be successful
And the command output should contain "/textfile.txt: would delete 2 of 2 revisions"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "2"
Scenario: clean up only a folder within the personal space
Given user "Alice" has created folder "folder"
And user "Alice" has uploaded file with content "version 1" to "folder/inFolder.txt"
And user "Alice" has uploaded file with content "version 2" to "folder/inFolder.txt"
And user "Alice" has uploaded file with content "version 3" to "folder/inFolder.txt"
And user "Alice" has uploaded file with content "version 1" to "outside.txt"
And user "Alice" has uploaded file with content "version 2" to "outside.txt"
And user "Alice" has uploaded file with content "version 3" to "outside.txt"
When the administrator cleans up the file versions of "/folder" in space "Personal" of user "Alice" using the CLI with flags "-s 0"
Then the command should be successful
And the command output should contain "/folder/inFolder.txt: deleted 2 of 2 revisions"
When user "Alice" gets the number of versions of file "folder/inFolder.txt"
Then the HTTP status code should be "207"
And the number of versions should be "0"
When user "Alice" gets the number of versions of file "outside.txt"
Then the HTTP status code should be "207"
And the number of versions should be "2"
Scenario: clean up only a project space
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And using spaces DAV path
And user "Alice" has created a space "projectSpace" with the default quota using the Graph API
And user "Alice" has uploaded file with content "version 1" to "personal.txt"
And user "Alice" has uploaded file with content "version 2" to "personal.txt"
And user "Alice" has uploaded file with content "version 3" to "personal.txt"
And user "Alice" has uploaded a file inside space "projectSpace" with content "version 1" to "project.txt"
And user "Alice" has uploaded a file inside space "projectSpace" with content "version 2" to "project.txt"
And user "Alice" has uploaded a file inside space "projectSpace" with content "version 3" to "project.txt"
And we save it into "PROJECT_FILEID"
When the administrator cleans up the file versions of space "projectSpace" of user "Alice" using the CLI with flags "-s 0"
Then the command should be successful
And the command output should contain "/project.txt: deleted 2 of 2 revisions"
When user "Alice" gets the number of versions of file "project.txt" using file-id "<<PROJECT_FILEID>>"
Then the HTTP status code should be "207"
And the number of versions should be "0"
When user "Alice" gets the number of versions of file "personal.txt"
Then the HTTP status code should be "207"
And the number of versions should be "2"
Scenario: print the results as JSON
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0 --json"
Then the command should be successful
And the JSON output of the command should contain an object of type "file" with:
| key | value |
| path | /textfile.txt |
| dry_run | false |
| revisions | 2 |
| deleted | 2 |
| failed | 0 |
And the JSON output of the command should contain an object of type "summary" with:
| key | value |
| deleted | 2 |
| failed | 0 |
Scenario: a cleanup without a strategy fails when the configured one is disabled
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
When the administrator cleans up the file versions using the CLI with flags "--all"
Then the command should exit with code "1"
And the command output should contain "no strategy"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
Scenario: a cleanup stopped by its timeout exits with code 2
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0 --timeout 1ns"
Then the command should exit with code "2"
And the command output should contain "stopped after the timeout of 1ns"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
Scenario: a strategy without spaces after its commas
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
When the administrator cleans up the file versions of all spaces using the CLI with flags "-s auto,1"
Then the command should be successful
And the command output should contain "/textfile.txt: deleted 2 of 3 revisions"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
@skipOnOpencloud-decomposed-Storage @skipOnOpencloud-decomposeds3-Storage
Scenario: clean up a folder given by its path on the POSIX filesystem
Given user "Alice" has created folder "folder"
And user "Alice" has uploaded file with content "version 1" to "folder/inFolder.txt"
And user "Alice" has uploaded file with content "version 2" to "folder/inFolder.txt"
And user "Alice" has uploaded file with content "version 3" to "folder/inFolder.txt"
And user "Alice" has uploaded file with content "version 1" to "outside.txt"
And user "Alice" has uploaded file with content "version 2" to "outside.txt"
And user "Alice" has uploaded file with content "version 3" to "outside.txt"
When the administrator cleans up the file versions of "folder" of user "Alice" by its path on the POSIX filesystem using the CLI with flags "-s 0"
Then the command should be successful
And the command output should contain "/folder/inFolder.txt: deleted 2 of 2 revisions"
When user "Alice" gets the number of versions of file "folder/inFolder.txt"
Then the HTTP status code should be "207"
And the number of versions should be "0"
When user "Alice" gets the number of versions of file "outside.txt"
Then the HTTP status code should be "207"
And the number of versions should be "2"
Scenario: the configured strategy cleans up a file whenever it gets a new version
Given the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 2 |
| STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
And user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
And user "Alice" has uploaded file with content "version 5" to "textfile.txt"
Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
And the content of file "textfile.txt" for user "Alice" should be "version 5"
Scenario: the configured strategy cleans up in the background by default
Given the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 2 |
And user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
And user "Alice" has uploaded file with content "version 5" to "textfile.txt"
Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
And the content of file "textfile.txt" for user "Alice" should be "version 5"
Scenario: the configured strategy cleans up a file uploaded with TUS
Given the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 2 |
And user "Alice" has uploaded a file with content "version 1" to "textfile.txt" via TUS inside of the space "Personal"
And user "Alice" has uploaded a file with content "version 2" to "textfile.txt" via TUS inside of the space "Personal"
And user "Alice" has uploaded a file with content "version 3" to "textfile.txt" via TUS inside of the space "Personal"
And user "Alice" has uploaded a file with content "version 4" to "textfile.txt" via TUS inside of the space "Personal"
And user "Alice" has uploaded a file with content "version 5" to "textfile.txt" via TUS inside of the space "Personal"
Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
And the content of file "textfile.txt" for user "Alice" should be "version 5"
# The age of a version is the time it was created, i.e. when its content was replaced, not
# the modification time of its content, which the client chooses: "version 1" and "version 2"
# are only seconds old as versions, although their content is dated 60 and 50 days ago.
Scenario: the configured strategy measures the age of a version by the time it was created
Given the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 30d |
| STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
And user "Alice" has uploaded a file with content "version 1" and mtime "-60 days" to "textfile.txt"
And user "Alice" has uploaded a file with content "version 2" and mtime "-50 days" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "2"
And the content of file "textfile.txt" for user "Alice" should be "version 3"
# The versions are ordered by the time they were created as well: a version whose content
# is dated years ahead doesn't count as the newest one, so "1" keeps the version created
# last, "version 2", and not "version 1".
Scenario: a version with content dated in the future doesn't take the place of the newest one
Given the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 1 |
| STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
And user "Alice" has uploaded a file with content "version 1" and mtime "+10 years" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
And the content of version index "1" of file "textfile.txt" for user "Alice" should be "version 2"
And the content of file "textfile.txt" for user "Alice" should be "version 3"
# A restore makes the content from before the restore a version, which the cleanup keeps
# whatever the strategy, so that the restore can be undone. The restored version itself
# becomes the current content and is no longer a version.
Scenario: restoring a version keeps the content from before the restore, so that the restore can be undone
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
And the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 0 |
| STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
When user "Alice" restores version index "1" of file "textfile.txt" using the WebDAV API
Then the HTTP status code should be "204"
And the content of file "textfile.txt" for user "Alice" should be "version 2"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
When user "Alice" restores version index "1" of file "textfile.txt" using the WebDAV API
Then the HTTP status code should be "204"
And the content of file "textfile.txt" for user "Alice" should be "version 3"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "1"
@@ -0,0 +1,55 @@
@env-config @skipOnOpencloud-decomposed-Storage @skipOnOpencloud-decomposeds3-Storage
Feature: clean up old file versions that changes on the POSIX filesystem created
As an administrator
I want versions created by changes on the POSIX filesystem to be cleaned up like any other version
So that files that are changed directly on disk don't keep all their old versions
# With STORAGE_USERS_POSIX_ENABLE_FS_REVISIONS, a change on disk turns the previous content into a
# version. That needs a copy of the previous content, which posix only keeps of content it wrote
# or picked up while the setting was on, so it is set before the files are uploaded.
Background:
Given the following configs have been set:
| config | value |
| STORAGE_USERS_POSIX_WATCH_FS | true |
| STORAGE_USERS_POSIX_ENABLE_FS_REVISIONS | true |
And user "Alice" has been created with default attributes
# The strategy is only set after the uploads, so that the file has 3 versions when it is changed
# on disk: only the cleanup that the change on disk triggers can bring it down to 1.
Scenario Outline: the configured strategy cleans up a file whenever a change on disk creates a version
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
And the following configs have been set:
| config | value |
| STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 1 |
| STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | <async> |
When the administrator puts the content " changed on disk" into the file "textfile.txt" in the POSIX storage folder of user "Alice"
Then the command should be successful
And as "Alice" the final content of file "textfile.txt" should be "version 4 changed on disk"
And the number of versions of file "textfile.txt" for user "Alice" should eventually be "1"
And the content of version index "1" of file "textfile.txt" for user "Alice" should be "version 4"
Examples:
| async |
| true |
| false |
Scenario: the cleanup command deletes versions that changes on disk created
Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
When the administrator puts the content ", changed on disk" into the file "textfile.txt" in the POSIX storage folder of user "Alice"
Then the command should be successful
And as "Alice" the final content of file "textfile.txt" should be "version 1, changed on disk"
When the administrator puts the content ", changed again" into the file "textfile.txt" in the POSIX storage folder of user "Alice"
Then the command should be successful
And as "Alice" the final content of file "textfile.txt" should be "version 1, changed on disk, changed again"
And the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0"
Then the command should be successful
And the command output should contain "/textfile.txt: deleted 2 of 2 revisions"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
And the number of versions should be "0"
And the content of file "textfile.txt" for user "Alice" should be "version 1, changed on disk, changed again"