From 4f093f73f6eac13ec0eb2eb58c654e80dae3e182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn=20Friedrich=20Dreyer?= Date: Wed, 18 Nov 2026 17:38:59 +0100 Subject: [PATCH] build: bump reva to the ocm share permission fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We bump reva to 0093d72f4c9d, the merge of https://github.com/opencloud-eu/reva/pull/1035 on reva main. This brings in the OCM unshare and permission change notifications, the ocm core share events and the fixes to the permissions of OCM shares, on top of the invite and provider fixes already on reva main. It also pulls in the revision cleanup from https://github.com/opencloud-eu/reva/pull/895. Its strategy defaults to empty, which keeps all revisions, so nothing changes until we wire up the option. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Jörn Friedrich Dreyer --- go.mod | 2 +- go.sum | 4 +- .../internal/grpc/services/gateway/ocmcore.go | 2 +- .../grpc/services/gateway/ocmshareprovider.go | 55 ++ .../internal/grpc/services/ocmcore/ocmcore.go | 157 +++- .../ocminvitemanager/ocminvitemanager.go | 6 + .../ocmproviderauthorizer.go | 2 +- .../ocmshareprovider/ocmshareprovider.go | 104 ++- .../http/services/ocmd/notifications.go | 189 ++++- .../internal/http/services/ocmd/protocols.go | 19 +- .../v3/internal/http/services/ocmd/shares.go | 21 +- .../http/services/sciencemesh/token.go | 9 +- .../reva/v3/pkg/events/ocmcore.go | 16 + .../reva/v3/pkg/ocm/client/client.go | 143 ++-- .../reva/v3/pkg/ocm/client/payload.go | 131 ++++ .../pkg/ocm/provider/authorizer/json/json.go | 31 +- .../v3/pkg/ocm/share/repository/json/json.go | 28 +- .../share/repository/nextcloud/nextcloud.go | 6 + .../reva/v3/pkg/ocm/share/share.go | 3 + .../pkg/storage/fs/decomposed/decomposed.go | 4 + .../storage/fs/decomposeds3/decomposeds3.go | 4 + .../v3/pkg/storage/fs/posix/lookup/lookup.go | 45 ++ .../reva/v3/pkg/storage/fs/posix/posix.go | 64 ++ .../pkg/storage/fs/posix/tree/assimilation.go | 36 +- .../v3/pkg/storage/fs/posix/tree/revisions.go | 77 +- .../reva/v3/pkg/storage/fs/posix/tree/tree.go | 95 ++- .../v3/pkg/storage/pkg/decomposedfs/README.md | 368 +++++++++ .../pkg/decomposedfs/aspects/aspects.go | 6 + .../storage/pkg/decomposedfs/commit_upload.go | 29 +- .../storage/pkg/decomposedfs/decomposedfs.go | 73 +- .../decomposedfs/metadata/hybrid_backend.go | 72 +- .../metadata/messagepack_backend.go | 14 +- .../pkg/decomposedfs/metadata/metadata.go | 11 + .../pkg/decomposedfs/metadata/readonly.go | 47 ++ .../decomposedfs/metadata/xattrs_backend.go | 42 +- .../pkg/storage/pkg/decomposedfs/node/node.go | 84 +- .../pkg/decomposedfs/options/options.go | 68 +- .../pkg/decomposedfs/prepare_upload.go | 17 +- .../pkg/decomposedfs/revisioncleanup.go | 243 ++++++ .../decomposedfs/revisioncleanup/README.md | 156 ++++ .../decomposedfs/revisioncleanup/cleanup.go | 723 ++++++++++++++++++ .../decomposedfs/revisioncleanup/metrics.go | 123 +++ .../decomposedfs/revisioncleanup/ondemand.go | 266 +++++++ .../decomposedfs/revisioncleanup/result.go | 66 ++ .../decomposedfs/revisioncleanup/service.go | 698 +++++++++++++++++ .../decomposedfs/revisioncleanup/shared.go | 79 ++ .../pkg/storage/pkg/decomposedfs/revisions.go | 120 ++- .../decomposedfs/spaceidindex/spaceidindex.go | 18 + .../pkg/decomposedfs/tree/revisions.go | 77 +- .../pkg/storage/pkg/decomposedfs/tree/tree.go | 27 +- .../revisions/cleanup_strategy_auto.go | 202 +++++ .../revisions/cleanup_strategy_chain.go | 78 ++ .../cleanup_strategy_count_deletion.go | 67 ++ .../cleanup_strategy_count_retention.go | 44 ++ .../cleanup_strategy_duration_deletion.go | 68 ++ .../cleanup_strategy_duration_retention.go | 74 ++ .../reva/v3/pkg/storage/revisions/model.go | 44 ++ .../v3/pkg/storage/revisions/model_simple.go | 59 ++ .../reva/v3/pkg/storage/revisions/registry.go | 298 ++++++++ .../reva/v3/pkg/storage/revisions/utils.go | 307 ++++++++ .../reva/v3/pkg/storage/uploads.go | 11 + .../storage/utils/middleware/middleware.go | 8 + .../reva/v3/pkg/upload/coordinator.go | 5 + vendor/modules.txt | 4 +- 64 files changed, 5612 insertions(+), 337 deletions(-) create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/payload.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/README.md create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/readonly.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/README.md create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/cleanup.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/metrics.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/ondemand.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/result.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/service.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/shared.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_auto.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_chain.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_deletion.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_retention.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_deletion.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_retention.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model_simple.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/registry.go create mode 100644 vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/utils.go diff --git a/go.mod b/go.mod index f61082d7a0..b2cb25eef1 100644 --- a/go.mod +++ b/go.mod @@ -68,7 +68,7 @@ require ( github.com/open-policy-agent/opa v1.21.1 github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 - github.com/opencloud-eu/reva/v3 v3.0.2-0.20261117134925-37496dc6abd3 + github.com/opencloud-eu/reva/v3 v3.0.2-0.20261119121328-0093d72f4c9d github.com/opensearch-project/opensearch-go/v4 v4.7.3 github.com/orcaman/concurrent-map v1.0.0 github.com/pkg/errors v0.9.1 diff --git a/go.sum b/go.sum index 4d9ac64246..f1ae8516e8 100644 --- a/go.sum +++ b/go.sum @@ -761,8 +761,8 @@ github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 h1:W1ms+l github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89/go.mod h1:vigJkNss1N2QEceCuNw/ullDehncuJNFB6mEnzfq9UI= github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 h1:3ptbiFhSK4fzY/rC3idcYUveiwepMoOov1sBpc7Rg3k= github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346/go.mod h1:lTM8JeGblNpoMySTW7Lui2+c5TTLI95mwxtdUIHHrhU= -github.com/opencloud-eu/reva/v3 v3.0.2-0.20261117134925-37496dc6abd3 h1:fXAGn3HwuyQGRSw64i49FrzoOci6wwgJ57OONGST0fk= -github.com/opencloud-eu/reva/v3 v3.0.2-0.20261117134925-37496dc6abd3/go.mod h1:GYVaPfxKgmER65YvpN0uwYL8QSXnwXbR4Qr3iwsYlPU= +github.com/opencloud-eu/reva/v3 v3.0.2-0.20261119121328-0093d72f4c9d h1:pVqdcXJgDmypBdJChOWJvKL6gPeG3nEGU6lcuwbhv8E= +github.com/opencloud-eu/reva/v3 v3.0.2-0.20261119121328-0093d72f4c9d/go.mod h1:lwylaua29K7ge30pFxzHMh6LeH9bhCQduFdw+qKFzJA= github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4 h1:l2oB/RctH+t8r7QBj5p8thfEHCM/jF35aAY3WQ3hADI= github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmcore.go b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmcore.go index e59cb230d6..9da9c656fd 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmcore.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmcore.go @@ -69,7 +69,7 @@ func (s *svc) DeleteOCMCoreShare(ctx context.Context, req *ocmcore.DeleteOCMCore res, err := c.DeleteOCMCoreShare(ctx, req) if err != nil { - return nil, errors.Wrap(err, "gateway: error calling UpdateOCMCoreShare") + return nil, errors.Wrap(err, "gateway: error calling DeleteOCMCoreShare") } return res, nil diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmshareprovider.go b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmshareprovider.go index b9b0ddfd48..ebac4b42fe 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmshareprovider.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/gateway/ocmshareprovider.go @@ -59,6 +59,9 @@ func (s *svc) CreateOCMShare(ctx context.Context, req *ocm.CreateOCMShareRequest if err != nil { return nil, errors.Wrap(err, "gateway: error calling CreateOCMShare") } + if res.GetStatus().GetCode() != rpc.Code_CODE_OK { + return res, nil + } // add a grant to the storage provider so the share can efficiently be listed // the grant does not grant any permissions. access is granted by the OCM link token @@ -191,10 +194,62 @@ func (s *svc) UpdateOCMShare(ctx context.Context, req *ocm.UpdateOCMShareRequest if err != nil { return nil, errors.Wrap(err, "gateway: error calling UpdateOCMShare") } + if res.GetStatus().GetCode() != rpc.Code_CODE_OK { + return res, nil + } + + gRes, err := c.GetOCMShare(ctx, &ocm.GetOCMShareRequest{ + Ref: req.Ref, + }) + if err != nil { + return nil, errors.Wrap(err, "gateway: error calling GetOCMShare") + } + if gRes.GetStatus().GetCode() != rpc.Code_CODE_OK { + return &ocm.UpdateOCMShareResponse{ + Status: gRes.GetStatus(), + }, nil + } + + creator, ok := ctxpkg.ContextGetUser(ctx) + if !ok { + return nil, errors.New("gateway: user not found in context") + } + + // only webdav access methods carry permissions for the storage grant + perms := webdavPermissions(gRes.GetShare().GetAccessMethods()) + if perms == nil { + return res, nil + } + + grant := &provider.Grant{ + Grantee: gRes.GetShare().GetGrantee(), + Permissions: perms, + Expiration: gRes.GetShare().GetExpiration(), + Creator: creator.GetId(), + } + updateGrantStatus, err := s.updateGrant(ctx, gRes.GetShare().GetResourceId(), grant, nil) + if err != nil { + return nil, errors.Wrap(err, "gateway: error calling updateGrant") + } + if updateGrantStatus.GetCode() != rpc.Code_CODE_OK { + return &ocm.UpdateOCMShareResponse{ + Status: updateGrantStatus, + }, nil + } return res, nil } +// webdavPermissions returns the permissions of the first webdav access method. +func webdavPermissions(ams []*ocm.AccessMethod) *provider.ResourcePermissions { + for _, am := range ams { + if perms := am.GetWebdavOptions().GetPermissions(); perms != nil { + return perms + } + } + return nil +} + func (s *svc) ListReceivedOCMShares(ctx context.Context, req *ocm.ListReceivedOCMSharesRequest) (*ocm.ListReceivedOCMSharesResponse, error) { c, err := pool.GetOCMShareProviderClient(s.c.OCMShareProviderEndpoint) if err != nil { diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmcore/ocmcore.go b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmcore/ocmcore.go index e74b575b0f..067e238ea3 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmcore/ocmcore.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmcore/ocmcore.go @@ -20,35 +20,56 @@ package ocmcore import ( "context" + "errors" "fmt" "time" + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ocmcore "github.com/cs3org/go-cs3apis/cs3/ocm/core/v1beta1" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" providerpb "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/opencloud-eu/reva/v3/pkg/errtypes" + "github.com/opencloud-eu/reva/v3/pkg/events" + "github.com/opencloud-eu/reva/v3/pkg/events/stream" "github.com/opencloud-eu/reva/v3/pkg/ocm/share" "github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/registry" + ocmuser "github.com/opencloud-eu/reva/v3/pkg/ocm/user" "github.com/opencloud-eu/reva/v3/pkg/rgrpc" "github.com/opencloud-eu/reva/v3/pkg/rgrpc/status" + "github.com/opencloud-eu/reva/v3/pkg/utils" "github.com/opencloud-eu/reva/v3/pkg/utils/cfg" "github.com/rs/zerolog" "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/fieldmaskpb" ) func init() { rgrpc.Register("ocmcore", New) } +// EventOptions are the configurable options for events +type EventOptions struct { + Endpoint string `mapstructure:"natsaddress"` + Cluster string `mapstructure:"natsclusterid"` + TLSInsecure bool `mapstructure:"tlsinsecure"` + TLSRootCACertificate string `mapstructure:"tlsrootcacertificate"` + EnableTLS bool `mapstructure:"enabletls"` + AuthUsername string `mapstructure:"authusername"` + AuthPassword string `mapstructure:"authpassword"` +} + type config struct { Driver string `mapstructure:"driver"` Drivers map[string]map[string]interface{} `mapstructure:"drivers"` + Events EventOptions `mapstructure:"events"` } type service struct { - conf *config - repo share.Repository + conf *config + repo share.Repository + eventStream events.Stream + log *zerolog.Logger } func (c *config) ApplyDefaults() { @@ -69,7 +90,7 @@ func getShareRepository(c *config) (share.Repository, error) { } // New creates a new ocm core svc. -func New(m map[string]interface{}, ss *grpc.Server, _ *zerolog.Logger) (rgrpc.Service, error) { +func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.Service, error) { var c config if err := cfg.Decode(m, &c); err != nil { return nil, err @@ -83,6 +104,15 @@ func New(m map[string]interface{}, ss *grpc.Server, _ *zerolog.Logger) (rgrpc.Se service := &service{ conf: &c, repo: repo, + log: log, + } + + if c.Events.Endpoint != "" { + es, err := stream.NatsFromConfig("ocmcore-handler", false, stream.NatsConfig(c.Events)) + if err != nil { + return nil, err + } + service.eventStream = es } return service, nil @@ -93,7 +123,11 @@ func (s *service) Close() error { } func (s *service) UnprotectedEndpoints() []string { - return []string{"/cs3.ocm.core.v1beta1.OcmCoreAPI/CreateOCMCoreShare"} + return []string{ + ocmcore.OcmCoreAPI_CreateOCMCoreShare_FullMethodName, + ocmcore.OcmCoreAPI_UpdateOCMCoreShare_FullMethodName, + ocmcore.OcmCoreAPI_DeleteOCMCoreShare_FullMethodName, + } } // CreateOCMCoreShare is called when an OCM request comes into this reva instance from. @@ -102,7 +136,7 @@ func (s *service) CreateOCMCoreShare(ctx context.Context, req *ocmcore.CreateOCM return nil, errtypes.NotSupported("share type not supported") } - now := &typesv1beta1.Timestamp{ + now := &typespb.Timestamp{ Seconds: uint64(time.Now().Unix()), } @@ -132,6 +166,30 @@ func (s *service) CreateOCMCoreShare(ctx context.Context, req *ocmcore.CreateOCM }, nil } + var permissions *providerpb.ResourcePermissions + for _, p := range req.GetProtocols() { + if p.GetWebdavOptions() != nil { + permissions = p.GetWebdavOptions().GetPermissions().GetPermissions() + break + } + } + + if s.eventStream != nil { + if err := events.Publish(ctx, s.eventStream, events.OCMCoreShareCreated{ + ShareID: share.Id.OpaqueId, + Executant: share.Creator, + Sharer: share.Creator, + GranteeUserID: share.Grantee.GetUserId(), + ItemID: share.RemoteShareId, + ResourceName: share.Name, + CTime: share.Ctime, + Permissions: permissions, + }); err != nil { + s.log.Error().Err(err). + Msg("failed to publish the ocmcore share created event") + } + } + return &ocmcore.CreateOCMCoreShareResponse{ Status: status.NewOK(ctx), Id: share.Id.OpaqueId, @@ -140,9 +198,92 @@ func (s *service) CreateOCMCoreShare(ctx context.Context, req *ocmcore.CreateOCM } func (s *service) UpdateOCMCoreShare(ctx context.Context, req *ocmcore.UpdateOCMCoreShareRequest) (*ocmcore.UpdateOCMCoreShareResponse, error) { - return nil, errtypes.NotSupported("not implemented") + grantee := utils.ReadPlainFromOpaque(req.GetOpaque(), "grantee") + if grantee == "" { + return nil, errtypes.UserRequired("missing remote user id in a metadata") + } + if req == nil || len(req.Protocols) == 0 { + return nil, errtypes.PreconditionFailed("missing protocols in a request") + } + fileMask := &fieldmaskpb.FieldMask{Paths: []string{"protocols"}} + + user := &userpb.User{Id: ocmuser.DecodeRemoteUserFederatedID(&userpb.UserId{OpaqueId: grantee})} + _, err := s.repo.UpdateReceivedShare(ctx, user, &ocm.ReceivedShare{ + Id: &ocm.ShareId{ + OpaqueId: req.GetOcmShareId(), + }, + Protocols: req.Protocols, + }, fileMask) + res := &ocmcore.UpdateOCMCoreShareResponse{} + if err == nil { + res.Status = status.NewOK(ctx) + } else { + var notFound errtypes.NotFound + if errors.As(err, ¬Found) { + res.Status = status.NewNotFound(ctx, "remote ocm share not found") + } else { + res.Status = status.NewInternal(ctx, "error deleting remote ocm share") + } + } + return res, nil } func (s *service) DeleteOCMCoreShare(ctx context.Context, req *ocmcore.DeleteOCMCoreShareRequest) (*ocmcore.DeleteOCMCoreShareResponse, error) { - return nil, errtypes.NotSupported("not implemented") + grantee := utils.ReadPlainFromOpaque(req.GetOpaque(), "grantee") + if grantee == "" { + return nil, errtypes.UserRequired("missing remote user id in a metadata") + } + + share, err := s.repo.GetReceivedShare(ctx, &userpb.User{Id: ocmuser.DecodeRemoteUserFederatedID(&userpb.UserId{OpaqueId: grantee})}, &ocm.ShareReference{ + Spec: &ocm.ShareReference_Id{ + Id: &ocm.ShareId{ + OpaqueId: req.GetId(), + }, + }, + }) + if err != nil { + var notFound errtypes.NotFound + if errors.As(err, ¬Found) { + return &ocmcore.DeleteOCMCoreShareResponse{ + Status: status.NewNotFound(ctx, "remote ocm share not found"), + }, nil + } + return nil, errtypes.InternalError("unable to get share details") + } + + granteeUser := &userpb.User{Id: ocmuser.DecodeRemoteUserFederatedID(&userpb.UserId{OpaqueId: grantee})} + err = s.repo.DeleteReceivedShare(ctx, granteeUser, &ocm.ShareReference{ + Spec: &ocm.ShareReference_Id{ + Id: &ocm.ShareId{ + OpaqueId: req.GetId(), + }, + }, + }) + + res := &ocmcore.DeleteOCMCoreShareResponse{} + if err == nil { + res.Status = status.NewOK(ctx) + + if s.eventStream != nil { + if err := events.Publish(ctx, s.eventStream, events.OCMCoreShareDelete{ + ShareID: share.Id.OpaqueId, + Sharer: share.GetOwner(), + Grantee: ocmuser.DecodeRemoteUserFederatedID(&userpb.UserId{OpaqueId: grantee}), + ResourceName: share.Name, + CTime: &typespb.Timestamp{Seconds: uint64(time.Now().Unix())}, + }); err != nil { + s.log.Error().Err(err). + Msg("failed to publish the ocmcore share deleted event") + } + } + + } else { + var notFound errtypes.NotFound + if errors.As(err, ¬Found) { + res.Status = status.NewNotFound(ctx, "remote ocm share not found") + } else { + res.Status = status.NewInternal(ctx, "error deleting remote ocm share") + } + } + return res, nil } diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocminvitemanager/ocminvitemanager.go b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocminvitemanager/ocminvitemanager.go index 5dfba44030..399571fdc4 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocminvitemanager/ocminvitemanager.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocminvitemanager/ocminvitemanager.go @@ -170,6 +170,12 @@ func (s *service) ForwardInvite(ctx context.Context, req *invitepb.ForwardInvite return nil, err } + if req.GetOriginSystemProvider().Domain == s.conf.ProviderDomain { + return &invitepb.ForwardInviteResponse{ + Status: status.NewInvalid(ctx, "can not accept an invite from the same instance"), + }, nil + } + // Accept the invitation on the remote OCM provider remoteUser, err := s.ocmClient.InviteAccepted(ctx, ocmEndpoint, &client.InviteAcceptedRequest{ Token: req.InviteToken.GetToken(), diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go index ca2843cceb..9cc6a3fa3e 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go @@ -109,7 +109,7 @@ func (s *service) GetInfoByDomain(ctx context.Context, req *ocmprovider.GetInfoB domainInfo, err := s.pa.GetInfoByDomain(ctx, req.Domain) if err != nil { return &ocmprovider.GetInfoByDomainResponse{ - Status: status.NewInternal(ctx, "error getting provider info"), + Status: status.NewInternal(ctx, "error getting provider info: "+err.Error()), }, nil } diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmshareprovider/ocmshareprovider.go b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmshareprovider/ocmshareprovider.go index 3bd3303c59..5528578e1c 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmshareprovider/ocmshareprovider.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/grpc/services/ocmshareprovider/ocmshareprovider.go @@ -20,6 +20,7 @@ package ocmshareprovider import ( "context" + "fmt" "net/url" "path/filepath" "strings" @@ -352,9 +353,19 @@ func (s *service) CreateOCMShare(ctx context.Context, req *ocm.CreateOCMShareReq } func (s *service) RemoveOCMShare(ctx context.Context, req *ocm.RemoveOCMShareRequest) (*ocm.RemoveOCMShareResponse, error) { - // TODO (gdelmont): notify the remote provider using the /notification ocm endpoint - // https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post user := ctxpkg.ContextMustGetUser(ctx) + getShareRes, err := s.GetOCMShare(ctx, &ocm.GetOCMShareRequest{Ref: req.Ref}) + if err != nil { + return &ocm.RemoveOCMShareResponse{ + Status: status.NewInternal(ctx, "error getting ocm share"), + }, nil + } + if getShareRes.Status.Code != rpc.Code_CODE_OK { + return &ocm.RemoveOCMShareResponse{ + Status: getShareRes.GetStatus(), + }, nil + } + if err := s.repo.DeleteShare(ctx, user, req.Ref); err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.RemoveOCMShareResponse{ @@ -362,10 +373,16 @@ func (s *service) RemoveOCMShare(ctx context.Context, req *ocm.RemoveOCMShareReq }, nil } return &ocm.RemoveOCMShareResponse{ - Status: status.NewInternal(ctx, "error removing share"), + Status: status.NewInternal(ctx, "error deleting share"), }, nil } + err = s.notify(ctx, client.SHARE_UNSHARED, getShareRes.GetShare()) + if err != nil { + // Continue even if the notification fails. The share has been removed locally. + appctx.GetLogger(ctx).Err(err).Msg("error notifying ocm remote provider") + } + return &ocm.RemoveOCMShareResponse{ Status: status.NewOK(ctx), }, nil @@ -441,7 +458,20 @@ func (s *service) UpdateOCMShare(ctx context.Context, req *ocm.UpdateOCMShareReq Status: status.NewOK(ctx), }, nil } - _, err := s.repo.UpdateShare(ctx, user, req.Ref, req.Field...) + + getShareRes, err := s.GetOCMShare(ctx, &ocm.GetOCMShareRequest{Ref: req.Ref}) + if err != nil { + return &ocm.UpdateOCMShareResponse{ + Status: status.NewInternal(ctx, "error getting ocm share"), + }, nil + } + if getShareRes.Status.Code != rpc.Code_CODE_OK { + return &ocm.UpdateOCMShareResponse{ + Status: getShareRes.GetStatus(), + }, nil + } + + uShare, err := s.repo.UpdateShare(ctx, user, req.Ref, req.Field...) if err != nil { if errors.Is(err, share.ErrShareNotFound) { return &ocm.UpdateOCMShareResponse{ @@ -453,10 +483,25 @@ func (s *service) UpdateOCMShare(ctx context.Context, req *ocm.UpdateOCMShareReq }, nil } - res := &ocm.UpdateOCMShareResponse{ - Status: status.NewOK(ctx), + err = s.notify(ctx, client.SHARE_CHANGE_PERMISSION, uShare) + if err != nil { + // Disallow update if the remoter provider could not be notified to avoid inconsistencies + // between the local and remote shares. User still can delete the share. + err = fmt.Errorf("error notifying ocm remote provider: %w", err) + appctx.GetLogger(ctx).Err(err).Send() + + // Revert the share changes. + if _, err := s.repo.StoreShare(ctx, getShareRes.GetShare()); err != nil { + appctx.GetLogger(ctx).Err(err).Msg("error reverting ocm share changes") + } + return &ocm.UpdateOCMShareResponse{ + Status: status.NewInternal(ctx, err.Error()), + }, nil } - return res, nil + + return &ocm.UpdateOCMShareResponse{ + Status: status.NewOK(ctx), + }, nil } func (s *service) ListReceivedOCMShares(ctx context.Context, req *ocm.ListReceivedOCMSharesRequest) (*ocm.ListReceivedOCMSharesResponse, error) { @@ -523,3 +568,48 @@ func (s *service) GetReceivedOCMShare(ctx context.Context, req *ocm.GetReceivedO } return res, nil } + +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +func (s *service) notify(ctx context.Context, notificationType string, share *ocm.Share) error { + gatewayClient, err := s.gatewaySelector.Next() + if err != nil { + return err + } + providerInfoResp, err := gatewayClient.GetInfoByDomain(ctx, &ocmprovider.GetInfoByDomainRequest{ + Domain: share.GetGrantee().GetUserId().GetIdp(), + }) + if err != nil { + return err + } + if providerInfoResp.Status.Code != rpc.Code_CODE_OK { + return fmt.Errorf("error getting provider info: %s", providerInfoResp.Status.Message) + } + ocmEndpoint, err := getOCMEndpoint(providerInfoResp.GetProviderInfo()) + if err != nil { + return err + } + + notification := &client.Notification{} + switch notificationType { + case client.SHARE_UNSHARED: + notification.Grantee = share.GetGrantee().GetUserId().GetOpaqueId() + case client.SHARE_CHANGE_PERMISSION: + notification.Grantee = share.GetGrantee().GetUserId().GetOpaqueId() + notification.Protocols = s.getProtocols(ctx, share) + default: + return fmt.Errorf("unknown notification type: %s", notificationType) + } + + newShareReq := &client.NotificationRequest{ + NotificationType: notificationType, + ResourceType: "file", // use type "file" for shared files or folders + ProviderId: share.GetId().GetOpaqueId(), + Notification: notification, + } + err = s.client.NotifyRemote(ctx, ocmEndpoint, newShareReq) + if err != nil { + appctx.GetLogger(ctx).Err(err).Msg("error notifying ocm remote provider") + return err + } + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/notifications.go b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/notifications.go index 60fad445d5..39a0d6978f 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/notifications.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/notifications.go @@ -19,23 +19,74 @@ package ocmd import ( - "io" + "context" + "encoding/json" + "fmt" "mime" "net/http" - "github.com/opencloud-eu/reva/v3/internal/http/services/reqres" + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + ocmcore "github.com/cs3org/go-cs3apis/cs3/ocm/core/v1beta1" + rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + "github.com/go-chi/render" "github.com/opencloud-eu/reva/v3/pkg/appctx" + "github.com/opencloud-eu/reva/v3/pkg/rgrpc/todo/pool" + "github.com/opencloud-eu/reva/v3/pkg/utils" +) + +const ( + SHARE_UNSHARED = "SHARE_UNSHARED" + SHARE_CHANGE_PERMISSION = "SHARE_CHANGE_PERMISSION" ) // var validate = validator.New() type notifHandler struct { + gatewaySelector *pool.Selector[gateway.GatewayAPIClient] } func (h *notifHandler) init(c *config) error { + gatewaySelector, err := pool.GatewaySelector(c.GatewaySvc) + if err != nil { + return err + } + h.gatewaySelector = gatewaySelector + return nil } +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +type notificationRequest struct { + NotificationType string `json:"notificationType" validate:"required"` + ResourceType string `json:"resourceType" validate:"required"` + // Identifier to identify the shared resource at the provider side. This is unique per provider such that if the same resource is shared twice, this providerId will not be repeated. + ProviderId string `json:"providerId" validate:"required"` + // Optional additional parameters, depending on the notification and the resource type. + Notification *notification `json:"notification,omitempty"` +} + +type notification struct { + Owner string `json:"owner,omitempty"` + Grantee string `json:"grantee,omitempty"` + SharedSecret string `json:"sharedSecret,omitempty"` + Expiration uint64 `json:"expiration,omitempty"` + Protocols Protocols `json:"protocol,omitempty" validate:"required"` +} + +// ErrorMessageResponse is the response returned by the OCM API in case of an error. +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +type ErrorMessageResponse struct { + Message string `json:"message"` + ValidationErrors []*ValidationError `json:"validationErrors,omitempty"` +} + +// ValidationError is the payload for the validationErrors field in the ErrorMessageResponse. +type ValidationError struct { + Name string `json:"name"` + Message string `json:"message"` +} + // Notifications dispatches any notifications received from remote OCM sites // according to the specifications at: // https://cs3org.github.io/OCM-API/docs.html?branch=v1.1.0&repo=OCM-API&user=cs3org#/paths/~1notifications/post @@ -44,23 +95,137 @@ func (h *notifHandler) Notifications(w http.ResponseWriter, r *http.Request) { log := appctx.GetLogger(ctx) req, err := getNotification(r) if err != nil { - reqres.WriteError(w, r, reqres.APIErrorInvalidParameter, err.Error(), nil) + renderErrorBadRequest(w, r, http.StatusBadRequest, err.Error()) return } // TODO(lopresti) this is all to be implemented. For now we just log what we got log.Debug().Msgf("Received OCM notification: %+v", req) - // this is to please Nextcloud - w.WriteHeader(http.StatusCreated) + var status *rpc.Status + if req.Notification == nil || req.Notification.Grantee == "" { + renderErrorBadRequest(w, r, http.StatusBadRequest, "grantee is required") + return + } + switch req.NotificationType { + case SHARE_UNSHARED: + status, err = h.handleShareUnshared(ctx, req) + if err != nil { + log.Err(err).Any("notificationRequest", req).Msg("error handling the share unshared notification") + w.WriteHeader(http.StatusInternalServerError) + return + } + case SHARE_CHANGE_PERMISSION: + if req.Notification.Protocols == nil { + renderErrorBadRequest(w, r, http.StatusBadRequest, "protocol is required") + return + } + status, err = h.handleShareChangePermission(ctx, req) + if err != nil { + log.Err(err).Any("notificationRequest", req).Msg("error handling the share change permission notification") + w.WriteHeader(http.StatusInternalServerError) + return + } + default: + renderErrorBadRequest(w, r, http.StatusBadRequest, "NotificationType "+req.NotificationType+" is not supported") + return + } + // parse the response status + switch status.GetCode() { + case rpc.Code_CODE_OK: + w.WriteHeader(http.StatusCreated) + return + case rpc.Code_CODE_NOT_FOUND: + w.WriteHeader(http.StatusNotFound) + return + case rpc.Code_CODE_INVALID_ARGUMENT: + renderErrorBadRequest(w, r, http.StatusBadRequest, status.GetMessage()) + return + case rpc.Code_CODE_UNAUTHENTICATED: + w.WriteHeader(http.StatusUnauthorized) + return + case rpc.Code_CODE_PERMISSION_DENIED: + w.WriteHeader(http.StatusForbidden) + return + default: + log.Error().Str("code", status.GetCode().String()).Str("message", status.GetMessage()).Str("NotificationType", req.NotificationType).Msg("error handling notification") + w.WriteHeader(http.StatusInternalServerError) + } } -func getNotification(r *http.Request) (string, error) { - // var req notificationRequest - contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) - if err == nil && contentType == "application/json" { - bytes, _ := io.ReadAll(r.Body) - return string(bytes), nil +func (h *notifHandler) handleShareUnshared(ctx context.Context, req *notificationRequest) (*rpc.Status, error) { + gatewayClient, err := h.gatewaySelector.Next() + if err != nil { + return nil, fmt.Errorf("error getting gateway client: %w", err) } - return "", nil + + o := &typesv1beta1.Opaque{} + utils.AppendPlainToOpaque(o, "grantee", req.Notification.Grantee) + + res, err := gatewayClient.DeleteOCMCoreShare(ctx, &ocmcore.DeleteOCMCoreShareRequest{ + Id: req.ProviderId, + Opaque: o, + }) + if err != nil { + return nil, fmt.Errorf("error calling DeleteOCMCoreShare: %w", err) + } + return res.GetStatus(), nil +} + +func (h *notifHandler) handleShareChangePermission(ctx context.Context, req *notificationRequest) (*rpc.Status, error) { + gatewayClient, err := h.gatewaySelector.Next() + if err != nil { + return nil, fmt.Errorf("error getting gateway client: %w", err) + } + + if req.Notification == nil || req.Notification.Protocols == nil { + return nil, fmt.Errorf("error getting protocols from notification") + } + + o := &typesv1beta1.Opaque{} + utils.AppendPlainToOpaque(o, "grantee", req.Notification.Grantee) + utils.AppendPlainToOpaque(o, "resourceType", req.ResourceType) + + res, err := gatewayClient.UpdateOCMCoreShare(ctx, &ocmcore.UpdateOCMCoreShareRequest{ + OcmShareId: req.ProviderId, + Protocols: getProtocols(req.Notification.Protocols, o), + Opaque: o, + }) + if err != nil { + return nil, fmt.Errorf("error calling DeleteOCMCoreShare: %w", err) + } + return res.GetStatus(), nil +} + +func getNotification(r *http.Request) (*notificationRequest, error) { + contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + if contentType != "application/json" { + return nil, fmt.Errorf("unsupported content type %q", contentType) + } + n := ¬ificationRequest{} + if err := json.NewDecoder(r.Body).Decode(n); err != nil { + return nil, err + } + return n, nil +} + +func renderJSON(w http.ResponseWriter, r *http.Request, statusCode int, resp any) { + render.Status(r, statusCode) + render.JSON(w, r, resp) +} + +func renderErrorBadRequest(w http.ResponseWriter, r *http.Request, statusCode int, message string) { + resp := &ErrorMessageResponse{ + Message: "BAD_REQUEST", + ValidationErrors: []*ValidationError{ + { + Name: "notification", + Message: message, + }, + }, + } + renderJSON(w, r, statusCode, resp) } diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/protocols.go b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/protocols.go index 89b23e60a7..e19ba359f6 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/protocols.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/protocols.go @@ -27,6 +27,7 @@ import ( ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" ocmshare "github.com/opencloud-eu/reva/v3/pkg/ocm/share" utils "github.com/opencloud-eu/reva/v3/pkg/utils" ) @@ -38,7 +39,7 @@ type Protocols []Protocol // in the OCM share. type Protocol interface { // ToOCMProtocol convert the protocol to a ocm Protocol struct - ToOCMProtocol() *ocm.Protocol + ToOCMProtocol(*typesv1beta1.Opaque) *ocm.Protocol } // protocols supported by the OCM API @@ -81,7 +82,8 @@ func (w *WebDAV) UnmarshalJSON(data []byte) error { } // ToOCMProtocol convert the protocol to a ocm Protocol struct. -func (w *WebDAV) ToOCMProtocol() *ocm.Protocol { +func (w *WebDAV) ToOCMProtocol(o *typesv1beta1.Opaque) *ocm.Protocol { + resourceType := utils.ReadPlainFromOpaque(o, "resourceType") perms := &ocm.SharePermissions{ Permissions: &providerv1beta1.ResourcePermissions{}, } @@ -97,12 +99,11 @@ func (w *WebDAV) ToOCMProtocol() *ocm.Protocol { case "write": perms.Permissions.InitiateFileUpload = true perms.Permissions.RestoreRecycleItem = true - perms.Permissions.CreateContainer = true - perms.Permissions.Delete = true - perms.Permissions.Move = true - perms.Permissions.ListGrants = true - case "share": - perms.Reshare = true + if resourceType == "folder" { + perms.Permissions.Move = true + perms.Permissions.CreateContainer = true + perms.Permissions.Delete = true + } } } @@ -116,7 +117,7 @@ type Webapp struct { } // ToOCMProtocol convert the protocol to a ocm Protocol struct. -func (w *Webapp) ToOCMProtocol() *ocm.Protocol { +func (w *Webapp) ToOCMProtocol(_ *typesv1beta1.Opaque) *ocm.Protocol { return ocmshare.NewWebappProtocol(w.URITemplate, utils.GetAppViewMode(w.ViewMode)) } diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/shares.go b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/shares.go index 96cf04ba2c..28f2634b99 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/shares.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/ocmd/shares.go @@ -27,15 +27,13 @@ import ( "strings" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" - providerpb "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ocmcore "github.com/cs3org/go-cs3apis/cs3/ocm/core/v1beta1" ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" - ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" - rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" + providerpb "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/go-playground/validator/v10" "github.com/opencloud-eu/reva/v3/internal/http/services/reqres" "github.com/opencloud-eu/reva/v3/pkg/appctx" @@ -78,7 +76,7 @@ type createShareRequest struct { Protocols Protocols `json:"protocol" validate:"required"` } -// CreateShare sends all the informations to the consumer needed to start +// CreateShare sends all the information to the consumer needed to start // synchronization between the two services. func (h *sharesHandler) CreateShare(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -156,6 +154,9 @@ func (h *sharesHandler) CreateShare(w http.ResponseWriter, r *http.Request) { return } + o := &types.Opaque{} + utils.AppendPlainToOpaque(o, "resourceType", req.ResourceType) + createShareReq := &ocmcore.CreateOCMCoreShareRequest{ Description: req.Description, Name: req.Name, @@ -165,7 +166,7 @@ func (h *sharesHandler) CreateShare(w http.ResponseWriter, r *http.Request) { ShareWith: userRes.User.Id, ResourceType: getResourceTypeFromOCMRequest(req.ResourceType), ShareType: getOCMShareType(req.ShareType), - Protocols: getProtocols(req.Protocols), + Protocols: getProtocols(req.Protocols, o), } if req.Expiration != 0 { @@ -180,7 +181,7 @@ func (h *sharesHandler) CreateShare(w http.ResponseWriter, r *http.Request) { return } - if userRes.Status.Code != rpc.Code_CODE_OK { + if createShareResp.Status.Code != rpc.Code_CODE_OK { // TODO: define errors in the cs3apis reqres.WriteError(w, r, reqres.APIErrorServerError, "error creating ocm share", errors.New(createShareResp.Status.Message)) return @@ -274,10 +275,10 @@ func getOCMShareType(t string) ocm.ShareType { return ocm.ShareType_SHARE_TYPE_GROUP } -func getProtocols(p Protocols) []*ocm.Protocol { +func getProtocols(p Protocols, o *types.Opaque) []*ocm.Protocol { prot := make([]*ocm.Protocol, 0, len(p)) for _, data := range p { - prot = append(prot, data.ToOCMProtocol()) + prot = append(prot, data.ToOCMProtocol(o)) } return prot } diff --git a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/sciencemesh/token.go b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/sciencemesh/token.go index 2ec49b1b0a..38b1e14d2b 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/sciencemesh/token.go +++ b/vendor/github.com/opencloud-eu/reva/v3/internal/http/services/sciencemesh/token.go @@ -223,13 +223,13 @@ func (h *tokenHandler) AcceptInvite(w http.ResponseWriter, r *http.Request) { reqres.WriteError(w, r, reqres.APIErrorServerError, "error sending a grpc forward invite request", err) return } - if forwardInviteResponse.Status.Code != rpc.Code_CODE_OK { - switch forwardInviteResponse.Status.Code { + if forwardInviteResponse.GetStatus().GetCode() != rpc.Code_CODE_OK { + switch forwardInviteResponse.GetStatus().GetCode() { case rpc.Code_CODE_NOT_FOUND: reqres.WriteError(w, r, reqres.APIErrorNotFound, "token not found", nil) return case rpc.Code_CODE_INVALID_ARGUMENT: - reqres.WriteError(w, r, reqres.APIErrorInvalidParameter, "token has expired", nil) + reqres.WriteError(w, r, reqres.APIErrorInvalidParameter, forwardInviteResponse.GetStatus().GetMessage(), nil) return case rpc.Code_CODE_ALREADY_EXISTS: reqres.WriteError(w, r, reqres.APIErrorAlreadyExist, "user already known", nil) @@ -238,7 +238,8 @@ func (h *tokenHandler) AcceptInvite(w http.ResponseWriter, r *http.Request) { reqres.WriteError(w, r, reqres.APIErrorUnauthenticated, "remote service not trusted", nil) return default: - reqres.WriteError(w, r, reqres.APIErrorServerError, "unexpected error: "+forwardInviteResponse.Status.Message, errors.New(forwardInviteResponse.Status.Message)) + log.Err(errors.New(forwardInviteResponse.GetStatus().GetMessage())).Msg("unexpected error") + reqres.WriteError(w, r, reqres.APIErrorServerError, "unexpected error", nil) return } } diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/events/ocmcore.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/events/ocmcore.go index 16661d535c..1c75e3ad04 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/events/ocmcore.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/events/ocmcore.go @@ -44,3 +44,19 @@ func (OCMCoreShareCreated) Unmarshal(v []byte) (interface{}, error) { err := json.Unmarshal(v, &e) return e, err } + +// OCMCoreShareDelete is emitted when an ocm share is requested for delete +type OCMCoreShareDelete struct { + ShareID string + Sharer *user.UserId + Grantee *user.UserId + ResourceName string + CTime *types.Timestamp +} + +// Unmarshal to fulfill umarshaller interface +func (OCMCoreShareDelete) Unmarshal(v []byte) (interface{}, error) { + e := OCMCoreShareDelete{} + err := json.Unmarshal(v, &e) + return e, err +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/client.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/client.go index 6a6834ef0a..7341ee050d 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/client.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/client.go @@ -19,15 +19,15 @@ package client import ( - "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "net/url" + "strconv" "time" - "github.com/opencloud-eu/reva/v3/internal/http/services/ocmd" "github.com/opencloud-eu/reva/v3/pkg/appctx" "github.com/opencloud-eu/reva/v3/pkg/errtypes" "github.com/opencloud-eu/reva/v3/pkg/rhttp" @@ -75,32 +75,6 @@ func New(c *Config) *OCMClient { } } -// InviteAcceptedRequest contains the parameters for accepting -// an invitation. -type InviteAcceptedRequest struct { - UserID string `json:"userID"` - Email string `json:"email"` - Name string `json:"name"` - RecipientProvider string `json:"recipientProvider"` - Token string `json:"token"` -} - -// User contains the remote user's information when accepting -// an invitation. -type User struct { - UserID string `json:"userID"` - Email string `json:"email"` - Name string `json:"name"` -} - -func (r *InviteAcceptedRequest) toJSON() (io.Reader, error) { - var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(r); err != nil { - return nil, err - } - return &b, nil -} - // InviteAccepted informs the sender that the invitation was accepted to start sharing // https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1invite-accepted/post func (c *OCMClient) InviteAccepted(ctx context.Context, endpoint string, r *InviteAcceptedRequest) (*User, error) { @@ -154,35 +128,6 @@ func (c *OCMClient) parseInviteAcceptedResponse(r *http.Response) (*User, error) return nil, errtypes.InternalError(string(body)) } -// NewShareRequest contains the parameters for creating a new OCM share. -type NewShareRequest struct { - ShareWith string `json:"shareWith"` - Name string `json:"name"` - Description string `json:"description"` - ProviderID string `json:"providerId"` - Owner string `json:"owner"` - Sender string `json:"sender"` - OwnerDisplayName string `json:"ownerDisplayName"` - SenderDisplayName string `json:"senderDisplayName"` - ShareType string `json:"shareType"` - Expiration uint64 `json:"expiration"` - ResourceType string `json:"resourceType"` - Protocols ocmd.Protocols `json:"protocol"` -} - -func (r *NewShareRequest) toJSON() (io.Reader, error) { - var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(r); err != nil { - return nil, err - } - return &b, nil -} - -// NewShareResponse is the response returned when creating a new share. -type NewShareResponse struct { - RecipientDisplayName string `json:"recipientDisplayName"` -} - // NewShare creates a new share. // https://github.com/cs3org/OCM-API/blob/develop/spec.yaml func (c *OCMClient) NewShare(ctx context.Context, endpoint string, r *NewShareRequest) (*NewShareResponse, error) { @@ -232,25 +177,6 @@ func (c *OCMClient) parseNewShareResponse(r *http.Response) (*NewShareResponse, return nil, errtypes.InternalError(string(body)) } -// Capabilities contains a set of properties exposed by -// a remote cloud storage. -type Capabilities struct { - Enabled bool `json:"enabled"` - APIVersion string `json:"apiVersion"` - EndPoint string `json:"endPoint"` - Provider string `json:"provider"` - ResourceTypes []struct { - Name string `json:"name"` - ShareTypes []string `json:"shareTypes"` - Protocols struct { - Webdav *string `json:"webdav"` - Webapp *string `json:"webapp"` - Datatx *string `json:"datatx"` - } `json:"protocols"` - } `json:"resourceTypes"` - Capabilities []string `json:"capabilities"` -} - // Discovery returns a number of properties used to discover the capabilities offered by a remote cloud storage. // https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1ocm-provider/get func (c *OCMClient) Discovery(ctx context.Context, endpoint string) (*Capabilities, error) { @@ -278,3 +204,68 @@ func (c *OCMClient) Discovery(ctx context.Context, endpoint string) (*Capabiliti return &cap, nil } + +// NotifyRemote sends a notification to a remote OCM instance. +// Send a notification to a remote party about a previously known entity +// Notifications are optional messages. They are expected to be used to inform the other party about a change about a previously known entity, +// such as a share or a trusted user. For example, a notification MAY be sent by a recipient to let the provider know that +// the recipient declined a share. In this case, the provider site MAY mark the share as declined for its user(s). Similarly, +// it MAY be sent by a provider to let the recipient know that the provider removed a given share, such that the recipient MAY clean it up from its database. +// A notification MAY also be sent to let a recipient know that the provider removed that recipient from the list of trusted users, along with any related share. +// The recipient MAY reciprocally remove that provider from the list of trusted users, along with any related share. +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +func (c *OCMClient) NotifyRemote(ctx context.Context, endpoint string, r *NotificationRequest) error { + url, err := url.JoinPath(endpoint, "notifications") + if err != nil { + return err + } + body, err := r.ToJSON() + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) + if err != nil { + return errors.Wrap(err, "error creating request") + } + req.Header.Set("Content-Type", "application/json") + + resp, err := c.client.Do(req) + if err != nil { + return errors.Wrap(err, "error doing request") + } + defer resp.Body.Close() + + err = c.parseNotifyRemoteResponse(resp, nil) + if err != nil { + appctx.GetLogger(ctx).Err(err).Msg("error notifying remote OCM instance") + return err + } + return nil +} + +func (c *OCMClient) parseNotifyRemoteResponse(r *http.Response, resp any) error { + var err error + switch r.StatusCode { + case http.StatusOK, http.StatusCreated: + if resp == nil { + return nil + } + err := json.NewDecoder(r.Body).Decode(resp) + if err != nil { + return errors.Wrap(err, fmt.Sprintf("http status code: %v, error decoding response body", r.StatusCode)) + } + return nil + case http.StatusBadRequest: + err = ErrInvalidParameters + case http.StatusUnauthorized, http.StatusForbidden: + err = ErrServiceNotTrusted + default: + err = errtypes.InternalError("request finished whit code " + strconv.Itoa(r.StatusCode)) + } + + body, err2 := io.ReadAll(r.Body) + if err2 != nil { + return errors.Wrap(err, "error reading response body "+err2.Error()) + } + return errors.Wrap(err, string(body)) +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/payload.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/payload.go new file mode 100644 index 0000000000..5df1e01ff5 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/client/payload.go @@ -0,0 +1,131 @@ +package client + +import ( + "bytes" + "encoding/json" + "io" + + "github.com/opencloud-eu/reva/v3/internal/http/services/ocmd" +) + +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +// NotificationType one of "SHARE_ACCEPTED", "SHARE_DECLINED", "SHARE_CHANGE_PERMISSION", "SHARE_UNSHARED", "USER_REMOVED" +const ( + SHARE_UNSHARED = "SHARE_UNSHARED" + SHARE_CHANGE_PERMISSION = "SHARE_CHANGE_PERMISSION" +) + +// InviteAcceptedRequest contains the parameters for accepting +// an invitation. +type InviteAcceptedRequest struct { + UserID string `json:"userID"` + Email string `json:"email"` + Name string `json:"name"` + RecipientProvider string `json:"recipientProvider"` + Token string `json:"token"` +} + +// User contains the remote user's information when accepting +// an invitation. +type User struct { + UserID string `json:"userID"` + Email string `json:"email"` + Name string `json:"name"` +} + +func (r *InviteAcceptedRequest) toJSON() (io.Reader, error) { + var b bytes.Buffer + if err := json.NewEncoder(&b).Encode(r); err != nil { + return nil, err + } + return &b, nil +} + +// NewShareRequest contains the parameters for creating a new OCM share. +type NewShareRequest struct { + ShareWith string `json:"shareWith"` + Name string `json:"name"` + Description string `json:"description"` + ProviderID string `json:"providerId"` + Owner string `json:"owner"` + Sender string `json:"sender"` + OwnerDisplayName string `json:"ownerDisplayName"` + SenderDisplayName string `json:"senderDisplayName"` + ShareType string `json:"shareType"` + Expiration uint64 `json:"expiration"` + ResourceType string `json:"resourceType"` + Protocols ocmd.Protocols `json:"protocol"` +} + +func (r *NewShareRequest) toJSON() (io.Reader, error) { + var b bytes.Buffer + if err := json.NewEncoder(&b).Encode(r); err != nil { + return nil, err + } + return &b, nil +} + +// Capabilities contains a set of properties exposed by +// a remote cloud storage. +type Capabilities struct { + Enabled bool `json:"enabled"` + APIVersion string `json:"apiVersion"` + EndPoint string `json:"endPoint"` + Provider string `json:"provider"` + ResourceTypes []struct { + Name string `json:"name"` + ShareTypes []string `json:"shareTypes"` + Protocols struct { + Webdav *string `json:"webdav"` + Webapp *string `json:"webapp"` + Datatx *string `json:"datatx"` + } `json:"protocols"` + } `json:"resourceTypes"` + Capabilities []string `json:"capabilities"` +} + +// NotificationRequest is the request payload for the OCM API notifications endpoint. +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +type NotificationRequest struct { + NotificationType string `json:"notificationType" validate:"required"` + ResourceType string `json:"resourceType" validate:"required"` + // Identifier to identify the shared resource at the provider side. This is unique per provider such that if the same resource is shared twice, this providerId will not be repeated. + ProviderId string `json:"providerId" validate:"required"` + // Optional additional parameters, depending on the notification and the resource type. + Notification *Notification `json:"notification,omitempty"` +} + +// Notification is the payload for the notification field in the NotificationRequest. +type Notification struct { + // Owner string `json:"owner,omitempty"` + Grantee string `json:"grantee,omitempty"` + SharedSecret string `json:"sharedSecret,omitempty"` + Protocols ocmd.Protocols `json:"protocol,omitempty"` +} + +// ToJSON returns the JSON io.Reader of the NotificationRequest. +func (r *NotificationRequest) ToJSON() (io.Reader, error) { + var b bytes.Buffer + if err := json.NewEncoder(&b).Encode(r); err != nil { + return nil, err + } + return &b, nil +} + +// NewShareResponse is the response returned when creating a new share. +type NewShareResponse struct { + RecipientDisplayName string `json:"recipientDisplayName"` +} + +// ErrorMessageResponse is the response returned by the OCM API in case of an error. +// https://cs3org.github.io/OCM-API/docs.html?branch=develop&repo=OCM-API&user=cs3org#/paths/~1notifications/post +type ErrorMessageResponse struct { + Message string `json:"message"` + ValidationErrors []*ValidationError `json:"validationErrors,omitempty"` +} + +// ValidationError is the payload for the validationErrors field in the ErrorMessageResponse. +type ValidationError struct { + Name string `json:"name"` + Message string `json:"message"` +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/provider/authorizer/json/json.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/provider/authorizer/json/json.go index a6b15ec528..ae7e4e0410 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/provider/authorizer/json/json.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/provider/authorizer/json/json.go @@ -122,13 +122,32 @@ func (a *authorizer) GetInfoByDomain(_ context.Context, domain string) (*ocmprov // check if the domain matches a regex if ok, err := regexp.MatchString(p.Domain, normalizedDomain); ok && err == nil { // overwrite wildcards with the actual domain - for i, s := range p.Services { - s.Endpoint.Path = strings.ReplaceAll(s.Endpoint.Path, p.Domain, normalizedDomain) - s.Host = strings.ReplaceAll(s.Host, p.Domain, normalizedDomain) - p.Services[i] = s + var services []*ocmprovider.Service + for _, s := range p.Services { + services = append(services, &ocmprovider.Service{ + Host: strings.ReplaceAll(s.Host, p.Domain, normalizedDomain), + Endpoint: &ocmprovider.ServiceEndpoint{ + Type: s.Endpoint.Type, + Name: s.Endpoint.Name, + Path: strings.ReplaceAll(s.Endpoint.Path, p.Domain, normalizedDomain), + IsMonitored: s.Endpoint.IsMonitored, + Properties: s.Endpoint.Properties, + }, + ApiVersion: s.ApiVersion, + AdditionalEndpoints: s.AdditionalEndpoints, + }) } - p.Domain = normalizedDomain - return p, nil + return &ocmprovider.ProviderInfo{ + Name: p.Name, + FullName: p.FullName, + Description: p.Description, + Organization: p.Organization, + Domain: normalizedDomain, + Homepage: p.Homepage, + Email: p.Email, + Services: services, + Properties: p.Properties, + }, nil } } return nil, errtypes.NotFound(domain) diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/json/json.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/json/json.go index 1a6f3a52db..ef9b5a9385 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/json/json.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/json/json.go @@ -379,6 +379,12 @@ func receivedShareEqual(ref *ocm.ShareReference, s *ocm.ReceivedShare) bool { return true } } + // Match the reserved share by the remote share id + if ref.GetId() != nil && s.RemoteShareId != "" { + if ref.GetId().GetOpaqueId() == s.RemoteShareId { + return true + } + } return false } @@ -572,6 +578,23 @@ func (m *mgr) GetReceivedShare(ctx context.Context, user *userpb.User, ref *ocm. return nil, errtypes.NotFound(ref.String()) } +func (m *mgr) DeleteReceivedShare(ctx context.Context, user *userpb.User, ref *ocm.ShareReference) error { + m.Lock() + defer m.Unlock() + + if err := m.load(); err != nil { + return err + } + + for id, share := range m.model.ReceivedShares { + if receivedShareEqual(ref, share) && utils.UserEqual(user.Id, share.GetGrantee().GetUserId()) { + delete(m.model.ReceivedShares, id) + return m.save() + } + } + return errtypes.NotFound(ref.String()) +} + func (m *mgr) UpdateReceivedShare(ctx context.Context, user *userpb.User, share *ocm.ReceivedShare, fieldMask *field_mask.FieldMask) (*ocm.ReceivedShare, error) { rs, err := m.GetReceivedShare(ctx, user, &ocm.ShareReference{Spec: &ocm.ShareReference_Id{Id: share.Id}}) if err != nil { @@ -589,12 +612,15 @@ func (m *mgr) UpdateReceivedShare(ctx context.Context, user *userpb.User, share switch mask { case "state": rs.State = share.State - m.model.ReceivedShares[share.Id.OpaqueId].State = share.State + m.model.ReceivedShares[rs.Id.OpaqueId].State = share.State + case "protocols": + m.model.ReceivedShares[rs.Id.OpaqueId].Protocols = share.Protocols // TODO case "mount_point": default: return nil, errtypes.NotSupported("updating " + mask + " is not supported") } } + m.model.ReceivedShares[rs.Id.OpaqueId].Mtime = &typespb.Timestamp{Seconds: uint64(time.Now().Second())} if err := m.save(); err != nil { return nil, errors.Wrap(err, "error saving model") diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/nextcloud/nextcloud.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/nextcloud/nextcloud.go index 0b3cd33dec..88f4233eac 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/nextcloud/nextcloud.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/repository/nextcloud/nextcloud.go @@ -28,6 +28,7 @@ import ( "strings" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + "github.com/opencloud-eu/reva/v3/pkg/errtypes" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -345,6 +346,11 @@ func (sm *Manager) GetReceivedShare(ctx context.Context, user *userpb.User, ref }, nil } +// DeleteReceivedShare deletes the share pointed by ref. +func (sm *Manager) DeleteReceivedShare(ctx context.Context, user *userpb.User, ref *ocm.ShareReference) error { + return errtypes.NotSupported("not implemented") +} + // UpdateReceivedShare updates the received share with share state. func (sm *Manager) UpdateReceivedShare(ctx context.Context, user *userpb.User, share *ocm.ReceivedShare, fieldMask *field_mask.FieldMask) (*ocm.ReceivedShare, error) { type paramsObj struct { diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/share.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/share.go index 466c3e7b26..3650880167 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/share.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/ocm/share/share.go @@ -55,6 +55,9 @@ type Repository interface { // GetReceivedShare returns the information for a received share the user has access. GetReceivedShare(ctx context.Context, user *userpb.User, ref *ocm.ShareReference) (*ocm.ReceivedShare, error) + // DeleteReceivedShare deletes the share pointed by ref. + DeleteReceivedShare(ctx context.Context, user *userpb.User, ref *ocm.ShareReference) error + // UpdateReceivedShare updates the received share with share state. UpdateReceivedShare(ctx context.Context, user *userpb.User, share *ocm.ReceivedShare, fieldMask *field_mask.FieldMask) (*ocm.ReceivedShare, error) } diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposed/decomposed.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposed/decomposed.go index 48471f2540..72ec9044d3 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposed/decomposed.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposed/decomposed.go @@ -16,6 +16,10 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +// Package decomposed implements the "decomposed" storage driver: decomposedfs with +// a blobstore on the local disk. It only creates the blobstore and hands over to +// decomposedfs.NewDefault, see pkg/storage/pkg/decomposedfs/README.md for how the +// decomposedfs based drivers are structured. package decomposed import ( diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposeds3/decomposeds3.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposeds3/decomposeds3.go index 769bf314c6..f99f4b8637 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposeds3/decomposeds3.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/decomposeds3/decomposeds3.go @@ -16,6 +16,10 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +// Package decomposeds3 implements the "decomposeds3" storage driver: decomposedfs with +// a blobstore in an S3 bucket. It only creates the blobstore and hands over to +// decomposedfs.NewDefault, see pkg/storage/pkg/decomposedfs/README.md for how the +// decomposedfs based drivers are structured. package decomposeds3 import ( diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/lookup/lookup.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/lookup/lookup.go index 9530497780..96d9240197 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/lookup/lookup.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/lookup/lookup.go @@ -134,6 +134,51 @@ func (lu *Lookup) IDsForPath(ctx context.Context, path string) (string, string, return spaceID, nodeID, nil } +// SpacePathFromFSPath resolves a path on disk, as an admin sees it, to the space it is in and its +// path relative to the space root ("" for the space root itself). Relative paths are taken +// relative to the working directory; symlinks are not resolved. The file or folder must be +// known to the id cache, i.e. assimilated. +// +// It checks no permissions, like the other lookups: it only resolves the path. +func (lu *Lookup) SpacePathFromFSPath(ctx context.Context, p string) (string, string, error) { + abs, err := filepath.Abs(p) + if err != nil { + return "", "", err + } + if _, ok := relWithin(lu.InternalRoot(), abs); !ok { + return "", "", errtypes.BadRequest(fmt.Sprintf("%q is not within the storage root %q", abs, lu.InternalRoot())) + } + spaceID, _, err := lu.IDsForPath(ctx, abs) + if err != nil { + return "", "", errtypes.NotFound(fmt.Sprintf("%q is not known to the storage: %v", abs, err)) + } + spaceRoot, err := lu.GetCachedID(ctx, spaceID, spaceID) + if err != nil { + return "", "", errors.Wrapf(err, "could not find the root of space %q", spaceID) + } + rel, ok := relWithin(spaceRoot, abs) + if !ok { + return "", "", errtypes.InternalError(fmt.Sprintf("%q is not within the root %q of its space %q", abs, spaceRoot, spaceID)) + } + if rel == "." { + rel = "" + } + return spaceID, rel, nil +} + +// relWithin returns the path of p relative to root, "." for root itself, and whether p is root +// or within it. Both paths must be absolute. +// +// It relies on filepath.IsLocal rather than on a check for a ".." prefix, which would also +// reject names that only start with "..", e.g. "..foo". +func relWithin(root, p string) (string, bool) { + rel, err := filepath.Rel(root, p) + if err != nil || !filepath.IsLocal(rel) { + return "", false + } + return rel, true +} + // NodeFromPath returns the node for the given path func (lu *Lookup) NodeIDFromParentAndName(ctx context.Context, parent *node.Node, name string) (string, error) { parentPath, err := lu.GetCachedID(ctx, parent.SpaceID, parent.ID) diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/posix.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/posix.go index b95ecbe83a..4c6a7fbc11 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/posix.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/posix.go @@ -16,6 +16,11 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +// Package posix implements the "posix" storage driver, which keeps a regular, +// browsable directory tree on disk and picks up changes made to it directly. +// It reuses the decomposedfs core with its own lookup, tree, trashbin and blobstore +// and wraps the result, see pkg/storage/pkg/decomposedfs/README.md for how it +// builds itself and how it delegates to and overrides the shared code. package posix import ( @@ -29,6 +34,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/rs/zerolog" + "github.com/opencloud-eu/reva/v3/pkg/errtypes" "github.com/opencloud-eu/reva/v3/pkg/events" "github.com/opencloud-eu/reva/v3/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v3/pkg/storage" @@ -47,6 +53,7 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/permissions" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/usermapper" "github.com/opencloud-eu/reva/v3/pkg/storage/utils/middleware" "github.com/pkg/errors" @@ -61,8 +68,21 @@ type posixFS struct { tree *tree.Tree um usermapper.Mapper + // the inner Decomposedfs, for the on-demand revision cleanup: storage.FS is the + // middleware wrapping it, which doesn't pass optional interfaces through + revisions revisioncleanup.OnDemand + // resolves Request.FSPath for the on-demand revision cleanup + fsPaths fsPathResolver } +type fsPathResolver interface { + SpacePathFromFSPath(ctx context.Context, p string) (string, string, error) +} + +var _ fsPathResolver = (*lookup.Lookup)(nil) + +var _ revisioncleanup.OnDemand = (*posixFS)(nil) + // New returns an implementation to of the storage.FS interface that talk to // a local filesystem. func NewDefault(m map[string]interface{}, stream events.Stream, log *zerolog.Logger) (storage.FS, error) { @@ -194,10 +214,14 @@ func New(o *options.Options, stream events.Stream, cache, historyCache *idcache. EventStream: stream, UserMapper: um, Trashbin: trashbin, + // the tree already created the revision cleanup for its own use in assimilation + RevisionsCleanup: tp.RevisionsCleanup(), } dfs, err := decomposedfs.New(&o.Options, aspects, log) if err != nil { + // the tree already started the revision cleanup, stop its workers again + _ = tp.RevisionsCleanup().Shutdown(context.Background()) return nil, err } @@ -236,6 +260,10 @@ func New(o *options.Options, stream events.Stream, cache, historyCache *idcache. mw := middleware.NewFS(dfs, hooks...) fs.FS = mw + if onDemand, ok := dfs.(revisioncleanup.OnDemand); ok { + fs.revisions = onDemand + } + fs.fsPaths = lu fs.tree = tp fs.um = um @@ -248,6 +276,34 @@ func (fs *posixFS) WithDisabledSpaces() storage.FS { return &f } +// CleanupRevisionsUnchecked cleans up revisions on demand, see revisioncleanup.OnDemand. It goes to +// the inner Decomposedfs directly, bypassing the middleware, whose space group hooks only switch to +// the group of the space of a user request: the cleanup switches to the group of each space it +// cleans up itself, see revisioncleanup.SpaceScoper. +// +// A path on disk (Request.FSPath) is resolved here to its space and its path within the space, +// which the Decomposedfs doesn't know about. +func (fs *posixFS) CleanupRevisionsUnchecked(ctx context.Context, req revisioncleanup.Request, report func(revisioncleanup.Result)) error { + if fs.revisions == nil { + return errtypes.NotSupported("on-demand revision cleanup") + } + if req.DryRun { + // a dry run changes nothing on disk, not even the lock files of what it reads + ctx = metadata.WithReadOnly(ctx) + } + if req.FSPath != "" { + if err := req.Validate(); err != nil { + return err + } + spaceID, path, err := fs.fsPaths.SpacePathFromFSPath(ctx, req.FSPath) + if err != nil { + return err + } + req.SpaceIDs, req.Path, req.FSPath = []string{spaceID}, path, "" + } + return fs.revisions.CleanupRevisionsUnchecked(ctx, req, report) +} + // WarmupIDCache allows triggering a posix fs scan and id cache warmup manually. func (fs *posixFS) WarmupIDCache(root string, assimilate, onlyDirty bool) error { return fs.tree.WarmupIDCache(root, assimilate, onlyDirty) @@ -260,6 +316,14 @@ func (fs *posixFS) PrepareCreatesNode() bool { return ok && nc.PrepareCreatesNode() } +// HandleUploadFinished passes the end of an upload on to the wrapped driver, see +// storage.UploadFinishedHandler. +func (fs *posixFS) HandleUploadFinished(ctx context.Context, ref *provider.Reference, sessionID string, versionCreated bool) { + if h, ok := fs.FS.(storage.UploadFinishedHandler); ok { + h.HandleUploadFinished(ctx, ref, sessionID, versionCreated) + } +} + // IsOrphaned reports whether the referenced resource exists but its metadata is unreadable. func (fs *posixFS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool { return fs.FS.(storage.OrphanChecker).IsOrphaned(ctx, ref) diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/assimilation.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/assimilation.go index e024340d90..0fb11c359f 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/assimilation.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/assimilation.go @@ -40,6 +40,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/opencloud-eu/reva/v3/pkg/appctx" "github.com/opencloud-eu/reva/v3/pkg/errtypes" "github.com/opencloud-eu/reva/v3/pkg/events" "github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/watcher" @@ -831,13 +832,46 @@ assimilate: currentPath := currentNode.InternalPath() stat, err := os.Stat(currentPath) if err == nil { - revisionPath := t.lookup.VersionPath(n.SpaceID, n.ID, stat.ModTime().UTC().Format(time.RFC3339Nano)) + // Named after the mtime of '.CURRENT', i.e. the time the content it preserves was + // copied there, when the previous change was picked up (normally right after that + // content was written), not after the time of this change. + version := stat.ModTime().UTC().Format(time.RFC3339Nano) + revisionPath := t.lookup.VersionPath(n.SpaceID, n.ID, version) err = os.Rename(currentPath, revisionPath) if err != nil { t.log.Error().Err(err).Str("path", path).Str("revisionPath", revisionPath).Msg("could not create revision") return } + // The revision cleanup goes by the time a revision was created, i.e. the time + // of this change, not by its name, see node.RevisionCreatedAttr. Without it, the + // cleanup estimates that time, so a failure here is only logged. + revisionNode := node.NewBaseNode(n.SpaceID, n.ID+node.RevisionIDDelimiter+version, t.lookup) + if err := node.SetRevisionCreated(context.Background(), t.lookup.MetadataBackend(), revisionNode, time.Now()); err != nil { + t.log.Warn().Err(err).Str("path", path).Str("revisionPath", revisionPath).Msg("could not record when the revision was created") + } + + // A change on disk has just created a revision, apply the revision cleanup + // strategy (see package revisioncleanup). This is the only trigger for those + // revisions: they are created by the rename above and never go through + // CreateRevision or the upload code, where the other triggers are. + // It runs when this goroutine is done, after the new content was copied to + // '.CURRENT' below (or that failed): '.CURRENT' is missing from the rename above + // until then, and a change on disk in between would find no '.CURRENT' to create + // a revision from, so the cleanup must not make that window any longer. + // The cleanup takes the node lock itself. If the assimilation that started this + // goroutine still holds it, the cleanup just waits, as nothing waits for this + // goroutine there is no deadlock. + // context.Background() carries no logger, pass t.log on or the cleanup's + // logging would be lost. + // The cleanup is handed the ids, not n: n is still used by the assimilation + // that started this goroutine, and a node caches state without locking. + // HandleRevisionCreatedByID reads a node of its own only to clean it up: not + // at all if the cleanup is disabled, and in the background only in the worker. + defer func() { + ctx := appctx.WithLogger(context.Background(), t.log) + t.revisionsCleanup.HandleRevisionCreatedByID(ctx, n.SpaceID, n.ID) + }() } // Copy the new version to the current version diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/revisions.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/revisions.go index 0b56551544..5011f56a09 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/revisions.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/revisions.go @@ -36,7 +36,6 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" - "github.com/opencloud-eu/reva/v3/pkg/storagespace" "github.com/opencloud-eu/reva/v3/pkg/utils" ) @@ -127,34 +126,17 @@ func (tp *Tree) CreateRevision(ctx context.Context, n *node.Node, version string }); err != nil { return "", err } + // the time the revision was created, which the revision cleanup goes by, see + // node.RevisionCreatedAttr + if err := node.SetRevisionCreated(ctx, tp.lookup.MetadataBackend(), revNode, time.Now()); err != nil { + return "", err + } return versionPath, nil } -func (tp *Tree) ListRevisions(ctx context.Context, ref *provider.Reference) (revisions []*provider.FileVersion, err error) { - _, span := tracer.Start(ctx, "ListRevisions") - defer span.End() - var n *node.Node - if n, err = tp.lookup.NodeFromResource(ctx, ref); err != nil { - return - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return - } - - rp, err := tp.permissions.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, err - case !rp.ListFileVersions: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - +// ListRevisions lists all revisions of n. It checks no permissions, see node.Tree. +func (tp *Tree) ListRevisions(ctx context.Context, n *node.Node) (revisions []*provider.FileVersion, err error) { revisions = []*provider.FileVersion{} versionGlob := tp.lookup.VersionPath(n.SpaceID, n.ID, "*") if items, err := filepath.Glob(versionGlob); err == nil { @@ -198,45 +180,28 @@ func (tp *Tree) ListRevisions(ctx context.Context, ref *provider.Reference) (rev return } -// DownloadRevision returns a reader for the specified revision -// FIXME the CS3 api should explicitly allow initiating revision and trash download, a related issue is https://github.com/cs3org/reva/issues/1813 -func (tp *Tree) DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { +// DownloadRevision returns the resource info of the revision revisionKey of n and, if +// openReaderFunc wants it, a reader for its content. It checks no permissions, see node.Tree: +// rp are the permissions of the user on n, for the resource info. +func (tp *Tree) DownloadRevision(ctx context.Context, n *node.Node, revisionKey string, rp *provider.ResourcePermissions, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { _, span := tracer.Start(ctx, "DownloadRevision") defer span.End() - log := appctx.GetLogger(ctx) - // verify revision key format kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) - if len(kp) != 2 || !node.IsValidID(revisionKey) { - log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") + if len(kp) != 2 || kp[0] != n.ID { return nil, nil, errtypes.NotFound(revisionKey) } - log.Debug().Str("revisionKey", revisionKey).Msg("DownloadRevision") - - spaceID := ref.ResourceId.SpaceId - // check if the node is available and has not been deleted - n, err := node.ReadNode(ctx, tp.lookup, spaceID, kp[0], "", false, nil, false) - if err != nil { - return nil, nil, err - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return nil, nil, err - } - - rp, err := tp.permissions.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, nil, err - case !rp.ListFileVersions || !rp.InitiateFileDownload: // TODO add explicit permission in the CS3 api? - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, nil, errtypes.PermissionDenied(f) - } - return nil, nil, errtypes.NotFound(f) - } + spaceID := n.SpaceID revNode := node.NewBaseNode(spaceID, revisionKey, tp.lookup) + // the revision's metadata may come from a stale cache entry, after another process + // deleted the revision (see Decomposedfs.RestoreRevision) + if _, err := os.Stat(revNode.InternalPath()); err != nil { + if os.IsNotExist(err) { + return nil, nil, errtypes.NotFound(revisionKey) + } + return nil, nil, err + } _, blobsize, err := tp.lookup.ReadBlobIDAndSizeAttr(ctx, revNode, nil) if err != nil { return nil, nil, errors.Wrapf(err, "Decomposedfs: could not read blob id and size for revision '%s' of node '%s'", kp[1], n.ID) diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/tree.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/tree.go index 7c5bfd09de..3474b39163 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/tree.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/tree/tree.go @@ -27,6 +27,7 @@ import ( "os" "path/filepath" "strings" + "syscall" "time" "github.com/google/uuid" @@ -57,6 +58,7 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/permissions" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/propagator" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/usermapper" "github.com/opencloud-eu/reva/v3/pkg/storage/utils/templates" @@ -118,6 +120,9 @@ type Tree struct { // files that failed to assimilate, keyed by path, see updateFile() assimilationFailures *assimilation.Failures + // deletes old revisions after a change on disk created a new one, disabled without a strategy + revisionsCleanup *revisioncleanup.Service + es events.Stream log *zerolog.Logger } @@ -150,6 +155,24 @@ func New(lu node.PathLookup, bs node.Blobstore, um usermapper.Mapper, trashbin * } t.idResolver = t.lookup t.assimilateFunc = t.assimilate + // The tree creates the revision cleanup itself, as assimilation needs it for + // revisions created from changes on disk, and the watcher started below may + // assimilate right away. posix.New passes the same instance (with the same background + // workers) on to Decomposedfs through the aspects (see RevisionsCleanup), which also + // stops the workers on Shutdown. An invalid strategy or invalid async settings fail + // startup rather than silently keeping or deleting revisions the admin did not expect. + revisionsCleanup, err := revisioncleanup.NewServiceFromOptions(&o.Options, t.lookup, t, log) + if err != nil { + return nil, errors.Wrap(err, "tree: invalid revisions cleanup configuration") + } + t.revisionsCleanup = revisionsCleanup + // stop its workers again if the tree can't be set up after all + started := false + defer func() { + if !started { + _ = revisionsCleanup.Shutdown(context.Background()) + } + }() if err := t.checkStorage(); err != nil { return nil, errors.Wrap(err, "tree: unfit storage '"+o.Root+"'") } @@ -221,6 +244,7 @@ func New(lu node.PathLookup, bs node.Blobstore, um usermapper.Mapper, trashbin * }() } + started = true return t, nil } @@ -553,6 +577,26 @@ func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) // ListFolder lists the content of a folder node func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, error) { + return t.listFolder(ctx, n, true) +} + +var _ revisioncleanup.Walker = (*Tree)(nil) + +// ListFolderKnownUnchecked lists the children of n that are known to the storage, for +// maintenance, see revisioncleanup.Walker. Known children are the files and folders the storage +// has registered (assimilated), i.e. whose path resolves to a node id in the id cache. Unknown +// ones exist on disk but are not registered yet, e.g. files just created on disk directly. +// Unlike ListFolder, it checks no permissions, and it skips the unknown children instead of +// assimilating them, so that it changes nothing: they are missing from its result until they +// are assimilated, e.g. by the watcher or the next ListFolder. +func (t *Tree) ListFolderKnownUnchecked(ctx context.Context, n *node.Node) ([]*node.Node, error) { + return t.listFolder(ctx, n, false) +} + +// listFolder lists the children of n. For users, it leaves out the ones denied to the user +// in ctx and assimilates the ones not known yet; otherwise, for maintenance, it lists all +// known children, see ListFolderKnownUnchecked. +func (t *Tree) listFolder(ctx context.Context, n *node.Node, forUser bool) ([]*node.Node, error) { ctx, span := tracer.Start(ctx, "ListFolder") defer span.End() dir := n.InternalPath() @@ -628,8 +672,21 @@ func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, erro // silently turned into an assimilation attempt. return errors.Wrap(err, "tree: error resolving ids for "+path) } + if !forUser { + // A listing for maintenance (ListFolderKnownUnchecked, e.g. the walk of the + // on-demand revision cleanup) must not change anything, so it skips the + // item instead of assimilating it. Assimilation registers the item, with a + // new id and metadata, and with enable_fs_revisions it can even create a + // revision (e.g. for a file whose id is missing from the id cache) and run + // the revision cleanup with the driver's own strategy, which a dry run must + // not do either. The item has no revisions the storage knows of yet, so + // there is nothing to clean up; it is listed once it has been assimilated, + // e.g. by the watcher, a scan or a listing for a user. + t.log.Debug().Str("path", path).Msg("skipping an item that is unknown to the storage (not assimilated yet)") + continue + } // we don't know about this node yet, assimilate it on the fly - t.log.Info().Err(err).Str("path", path).Msg("encountered unknown entity while listing the directory. Assimilate.") + t.log.Info().Err(err).Str("path", path).Msg("encountered an item unknown to the storage while listing the directory, assimilating it") err = t.assimilateFunc(scanItem{Path: path}) if err != nil { t.log.Error().Err(err).Str("path", path).Msg("failed to assimilate node") @@ -648,8 +705,10 @@ func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, erro continue } - // prevent listing denied resources - if !child.IsDenied(ctx) { + // prevent listing denied resources, for users only: a listing for maintenance + // (ListFolderKnownUnchecked) has no user in the context, IsDenied would panic + // without one, and it must see all children, also the ones denied to users + if !forUser || !child.IsDenied(ctx) { if child.SpaceRoot == nil { child.SpaceRoot = n.SpaceRoot } @@ -775,6 +834,36 @@ func (t *Tree) DeleteBlob(node *node.Node) error { return t.blobstore.Delete(node) } +// RevisionsCleanup returns the revision cleanup, a disabled one without a strategy. +// It is used to hand the same instance to Decomposedfs via aspects.Aspects, so that +// uploads, restores and changes on disk are all cleaned up by the same strategy and +// share the same background workers. +func (t *Tree) RevisionsCleanup() *revisioncleanup.Service { + return t.revisionsCleanup +} + +var _ revisioncleanup.SpaceScoper = (*Tree)(nil) + +// ScopeToSpace switches the current goroutine to the group of the space with use_space_groups, +// as the space group hooks of the storage driver's middleware do for user requests, see +// revisioncleanup.SpaceScoper. The returned context carries the group, for the goroutines that +// listFolder starts. Without use_space_groups, it does nothing. +func (t *Tree) ScopeToSpace(ctx context.Context, spaceID string) (context.Context, func() error, error) { + if !t.options.UseSpaceGroups { + return ctx, func() error { return nil }, nil + } + fi, err := os.Stat(t.lookup.InternalPath(spaceID, spaceID)) + if err != nil { + return ctx, nil, errors.Wrapf(err, "could not stat the root of space %q", spaceID) + } + gid := fi.Sys().(*syscall.Stat_t).Gid + unscope, err := t.userMapper.ScopeUserByIds(-1, int(gid)) + if err != nil { + return ctx, nil, errors.Wrap(err, "failed to scope user") + } + return context.WithValue(ctx, decomposedfs.CtxKeySpaceGID, gid), unscope, nil +} + // BuildSpaceIDIndexEntry returns the entry for the space id index func (t *Tree) BuildSpaceIDIndexEntry(spaceID string) string { return spaceID diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/README.md b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/README.md new file mode 100644 index 0000000000..707ba358df --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/README.md @@ -0,0 +1,368 @@ +# decomposedfs and the drivers built on it + +This package is the shared core of three storage drivers: + +| driver | package | where file content lives | where metadata lives | +|----------------|---------------------------------|-----------------------------------------------|----------------------------------------------| +| `decomposed` | `pkg/storage/fs/decomposed` | blobs on local disk | node files in a private directory tree | +| `decomposeds3` | `pkg/storage/fs/decomposeds3` | blobs in an S3 bucket | node files in a private directory tree | +| `posix` | `pkg/storage/fs/posix` | the user's files themselves, as they appear on disk | extended attributes on those files | + +`decomposed` and `decomposeds3` "decompose" a file tree into nodes, metadata and blobs, so the files are not recognizable on disk. +`posix` keeps a normal, browsable directory tree, which may also be changed directly on disk, and keeps its own data in extended attributes and hidden directories. +Despite these differences, all three share most of their logic (the CS3 API, uploads, spaces, shares/grants, locks, revisions, quotas) through this package. + +Uploads are driven by the upload coordinator in `pkg/upload`, which is the same for every driver: it keeps the upload sessions, stages the bytes and hands them to postprocessing, and calls the driver at a few defined steps (see [Uploads](#uploads)). + +## Architecture overview + +### How requests reach the storage + +```mermaid +flowchart TB + subgraph services["reva services"] + SP["storageprovider
CS3 gRPC: metadata, spaces,
shares, revisions, trash
"] + DP["dataprovider
HTTP: TUS uploads, downloads"] + end + REG[("fs registry
registry.NewFuncs")] + SP -->|"getFS(driver)"| REG + DP -->|"getFS(driver)"| REG + + subgraph entry["driver entry points · pkg/storage/fs"] + DEC["decomposed.New
creates local blobstore"] + DS3["decomposeds3.New
creates S3 blobstore"] + PNEW["posix.NewDefault → posix.New
creates id caches, posix lookup,
tree, trashbin, blobstore
"] + end + REG -.->|"decomposed"| DEC + REG -.->|"decomposeds3"| DS3 + REG -.->|"posix"| PNEW + + ND["decomposedfs.NewDefault
creates decomposedfs lookup,
tree, trashbin
"] + DEC --> ND + DS3 --> ND + + subgraph wrap["posix only: wrapping"] + PFS["posixFS
forwards optional interfaces,
adds WarmupIDCache
"] + MW["middleware.FS
space group hooks"] + PFS --> MW + end + + NEW["decomposedfs.New(options, aspects)
common constructor"] + ND -->|"aspects"| NEW + PNEW -->|"aspects"| NEW + + DFS["Decomposedfs
implements storage.FS"] + NEW --> DFS + PNEW ==>|"returned to the services"| PFS + MW ==> DFS + ND ==>|"returned to the services"| DFS + + classDef shared fill:#dbeafe,stroke:#1d4ed8,color:#0b1b3f + classDef decomposed fill:#dcfce7,stroke:#15803d,color:#0b2e17 + classDef posix fill:#ffedd5,stroke:#c2410c,color:#3b1606 + classDef caller fill:#f5f3ff,stroke:#6d28d9,color:#1e1035 + class ND,NEW,DFS shared + class DEC,DS3 decomposed + class PNEW,PFS,MW posix + class SP,DP,REG caller +``` + +### Components and extension points + +```mermaid +flowchart TB + subgraph core["shared core · pkg/storage/pkg/decomposedfs"] + DFS["Decomposedfs
CS3 logic, spaces, grants,
locks, quotas, revisions
"] + end + UPC["upload coordinator · pkg/upload
sessions, staged bytes,
postprocessing
"] + UPC -->|"PrepareUpload, CommitUpload,
RollbackUpload, MarkProcessing"| DFS + + subgraph aspects["aspects.Aspects · extension points"] + direction LR + ILU[/"node.PathLookup"/] + ITR[/"node.Tree"/] + ITB[/"trashbin.Trashbin"/] + IBS[/"node.Blobstore"/] + end + DFS --> ILU + DFS --> ITR + DFS --> ITB + ITR --> IBS + + subgraph dfam["decomposed / decomposeds3"] + DLU["decomposedfs/lookup
id → path by computation"] + DTR["decomposedfs/tree"] + DTB["DecomposedfsTrashbin"] + BLOC["decomposed/blobstore"] + BS3["decomposeds3/blobstore"] + DISK[("local disk
root/spaces/…/nodes, blobs")] + S3[("S3 bucket")] + DLU --> DISK + DTR --> DISK + DTB --> DISK + BLOC --> DISK + BS3 --> S3 + end + + subgraph pfam["posix · pkg/storage/fs/posix"] + PLU["posix lookup
id ↔ path via id cache"] + PTR["posix tree"] + PTB["posix trashbin"] + BPX["posix/blobstore
content = the file itself"] + NATS[("NATS KV
id cache")] + PDISK[("local disk / shared fs
real files, .oc-nodes, .Trash")] + WATCH(["fs watcher
inotify, GPFS, CephFS, NATS"]) + PLU --> NATS + PTR --> PDISK + PTB --> PDISK + BPX --> PDISK + WATCH -->|"changes on disk:
assimilation, bypasses Decomposedfs"| PTR + end + + ILU -.-> DLU + ITR -.-> DTR + ITB -.-> DTB + IBS -.->|"decomposed"| BLOC + IBS -.->|"decomposeds3"| BS3 + ILU -.-> PLU + ITR -.-> PTR + ITB -.-> PTB + IBS -.-> BPX + + classDef shared fill:#dbeafe,stroke:#1d4ed8,color:#0b1b3f + classDef iface fill:#ffffff,stroke:#1d4ed8,stroke-dasharray:4 3,color:#0b1b3f + classDef decomposed fill:#dcfce7,stroke:#15803d,color:#0b2e17 + classDef posix fill:#ffedd5,stroke:#c2410c,color:#3b1606 + classDef external fill:#f3f4f6,stroke:#4b5563,color:#111827 + classDef caller fill:#f5f3ff,stroke:#6d28d9,color:#1e1035 + class DFS shared + class UPC caller + class ILU,ITR,ITB,IBS iface + class DLU,DTR,DTB,BLOC,BS3 decomposed + class PLU,PTR,PTB,BPX posix + class DISK,S3,NATS,PDISK,WATCH external +``` + +How to read them: + +- **Colours:** blue is the shared core in this package, green the code used only by `decomposed`/`decomposeds3`, orange the code used only by `posix`, grey the external systems, and purple the callers (in the second diagram the upload coordinator, which calls into `Decomposedfs`). +- **First diagram:** + - dotted arrows are lookups by driver name in the registry; + - thin arrows show what a constructor calls or builds; + - thick arrows show the object that is handed back to the services and the chain a request then travels through. +- **Second diagram:** + - solid arrows are calls at runtime; + - dotted arrows lead from an interface to the implementation each driver plugs in through `aspects.Aspects`. +- **Two paths into the storage:** requests from the services, uploads included, enter through `Decomposedfs` for all drivers (posix wraps it in `posixFS` and `middleware.FS` first). Changes made directly on disk enter only through the posix watcher and the tree's assimilation, which bypasses `Decomposedfs` and the upload code entirely. +- **Not shown:** the shared helpers `permissions`, `spaceidindex`, `node`, `metadata`, `tree/propagator` and `revisioncleanup`, and the NATS event stream used for async postprocessing. They are described in the sections below. + +## From configuration to a running driver + +### Registration + +Every driver registers a constructor in the storage driver registry (`pkg/storage/fs/registry`) from an `init()` function: + +```go +// pkg/storage/fs/decomposed/decomposed.go +func init() { registry.Register("decomposed", New) } + +// pkg/storage/fs/decomposeds3/decomposeds3.go +func init() { registry.Register("decomposeds3", New) } + +// pkg/storage/fs/posix/posix.go +func init() { registry.Register("posix", NewDefault) } +``` + +`pkg/storage/fs/loader` imports all driver packages for their side effect, so importing the loader makes every driver available. + +### Who creates the driver + +Two services look up the configured driver by name in `registry.NewFuncs` and call its constructor with the driver's config map and the event stream: + +- the CS3 **storage provider** gRPC service (`internal/grpc/services/storageprovider`, `getFS`): metadata operations, listing, spaces, shares, locks, revisions, trash; it initiates uploads +- the **data provider** HTTP service (`internal/http/services/dataprovider`, `getFS`): up- and downloads, e.g. TUS uploads via the data transfer handlers in `pkg/rhttp/datatx`; with async uploads, it also consumes the postprocessing results + +Both wrap the driver in an upload coordinator (`upload.NewCoordinatorFromConfig`). +Each service creates its own instance of the driver, and its own coordinator, from the same configuration, even when both run in the same process. +So anything a driver keeps in memory is not shared between the two, and shared state has to live on disk, in the metadata cache or in NATS. + +## How a driver builds itself + +The central type is `Decomposedfs` (`decomposedfs.go`). It implements `storage.FS`, including the steps of an upload the upload coordinator calls, and optional interfaces (e.g. listing disabled spaces). +It does not touch the storage layout itself, though. Everything layout specific is delegated to a set of components that each driver supplies in an `aspects.Aspects` struct: + +```go +// aspects/aspects.go +type Aspects struct { + Lookup node.PathLookup // resolves ids and references to nodes and paths + Tree node.Tree // creates, moves, deletes nodes; blobs; revisions; propagation + Trashbin trashbin.Trashbin // lists, restores and purges trashed items + Permissions permissions.Permissions // assembles CS3 permissions from grants + EventStream events.Stream // NATS events, e.g. to delete revisions + UserMapper usermapper.Mapper // maps users to unix ids (posix with space groups) + SeparateBlobs bool // blobs are kept apart from the nodes (not posix) + RevisionsCleanup *revisioncleanup.Service // deletes old revisions (in background workers by default), disabled without a strategy +} +``` + +`decomposedfs.New(options, aspects, log)` is the common constructor all drivers end up calling. It: + +1. calls `aspects.Tree.Setup()` to create the storage layout, +2. sets up the space indexes (`spaceidindex`: by user, group, mail, type) under `/indexes`, +3. creates the `Decomposedfs` from the aspects, +4. calls `Trashbin.Setup(fs)` so the trashbin can call back into the storage, +5. with async uploads enabled, subscribes to the revision events (`ConsumeRevisionEvents`); the postprocessing results are consumed by the upload coordinator. + +### decomposed and decomposeds3: `NewDefault` + +Both drivers only create their blobstore and then hand over to `decomposedfs.NewDefault`: + +``` +decomposed.New(config) decomposeds3.New(config) + options.New(config) parseConfig(config), check S3 settings + blobstore.New(root) (local disk) blobstore.New(endpoint, bucket, ...) (S3) + \ / + `---> decomposedfs.NewDefault(config, blobstore, stream, log) + options.New(config) + lookup.New(metadata backend: messagepack (default) or xattrs) + permissions.NewPermissions(...) + tree.New(lookup, blobstore, options, permissions, id cache) + revisioncleanup.NewServiceFromOptions(options, lookup, tree) (starts the cleanup workers) + Aspects{Lookup, Tree, Permissions, Trashbin: &DecomposedfsTrashbin{}, ...} + decomposedfs.New(options, aspects) +``` + +The blobstore is the only thing that differs between the two, everything else comes from this package: +`lookup` (`decomposedfs/lookup`), `tree` (`decomposedfs/tree`) and the trashbin `DecomposedfsTrashbin` (`recycle.go`). + +### posix: its own components around the same core + +`posix.NewDefault` sets up the NATS key-value id caches posix depends on, then calls `posix.New`. That function replaces almost every aspect with a posix specific implementation: + +``` +posix.NewDefault(config) + options.New(config) posix options embed the decomposedfs options; + defaults: metadata backend "hybrid", scan debounce, inotify stats + idcache (NATS KV) id -> path cache, plus a history cache for moved/deleted ids + posix.New(options, stream, idcache, historyCache) + usermapper unix mapper with use_space_groups, null mapper otherwise + posix lookup.New(...) metadata backend "hybrid" (default) or "xattrs" + permissions.NewPermissions (shared with decomposedfs) + posix trashbin.New + Setup freedesktop.org style '.Trash' per space + posix blobstore.New(root) writes the content into the actual file + posix tree.New(...) creates the revision cleanup (and its workers), starts the fs + watcher and the initial scan, if configured + Aspects{...posix components...} + decomposedfs.New(options, aspects) the shared core, as above + middleware.NewFS(dfs, hooks...) optional space group scoping hooks + posixFS{FS: middleware, tree, um} the storage.FS that is returned +``` + +The result is layered like this: + +```mermaid +flowchart TD + SP[storageprovider / dataprovider] --> PFS[posixFS] + PFS -->|embeds storage.FS| MW[middleware.FS
space group hooks] + MW --> DFS[Decomposedfs
shared CS3 logic, uploads, spaces, grants] + DFS --> LU[posix lookup] + DFS --> TR[posix tree] + DFS --> TB[posix trashbin] + DFS --> PM[permissions] + TR --> BS[posix blobstore] + TR --> W[watcher + assimilation] +``` + +For `decomposed` and `decomposeds3`, `NewDefault` returns the `Decomposedfs` directly, with no wrapper or middleware. + +## Delegation and overriding + +### Decomposedfs delegates layout specifics to the aspects + +Most `Decomposedfs` methods follow the same pattern: resolve a reference with the lookup, check permissions, then ask the tree to do the work. For example: + +- `CreateDir`, `Move`, `Delete`, `ListFolder` → `fs.lu.NodeFromResource` → `fs.p.AssemblePermissions` → `fs.tp.CreateDir/Move/Delete/ListFolder` +- `ListRevisions`, `DownloadRevision` → `fs.lu.NodeFromResource` or `node.ReadNode` → `fs.p.AssemblePermissions` → `fs.tp.ListRevisions/DownloadRevision` +- `ListRecycle`, `RestoreRecycleItem`, `PurgeRecycleItem`, `EmptyRecycle` → `fs.trashbin` +- size and etag propagation after changes → `fs.tp.Propagate` +- uploads → the steps the upload coordinator calls (see [Uploads](#uploads)) → `tp.InitNewNode`, `tp.CreateRevision`, `tp.WriteBlob` + +The interfaces that define those contracts live in `node/node.go` (`Tree`, `PathLookup`, `Blobstore`), `trashbin/trashbin.go` and `permissions/`. +They are the place to look when a feature needs driver specific behaviour. +Typically a method is added to the interface and implemented in both `decomposedfs/tree` and `fs/posix/tree`. +Such methods check no permissions: `Decomposedfs` checks them before it calls the tree, so that other callers can use the tree as well. +`Tree.ListRevisions` is an example: the revision cleanup (see `revisioncleanup`) calls it on behalf of the system, without a user. + +Before adding such a method, check whether the shared code already handles both layouts. +`Node` methods work through the lookup, so they resolve paths correctly for every driver. +For example, deleting a single revision needs no driver-specific code: `Node.DeleteRevisionUnchecked` removes the revision and returns its blob id, and `Tree.DeleteBlob` deletes the blob in whichever blobstore the driver uses. +`revisioncleanup.PurgeRevisionUnchecked` combines the two for all drivers. + +Shared building blocks that both trees use instead of re-implementing them: + +- `node` – the `Node` type, its attributes, locks, grants and processing status +- `metadata` – the metadata backends (`messagepack`, `xattrs`, `hybrid`) and the file metadata cache +- `tree/propagator` – tree size and mtime propagation (used by both trees) +- `permissions` – CS3 permission assembly from grants and the permissions service +- `revisioncleanup` – applying the revision cleanup strategy, right away or in background workers; documented in [`revisioncleanup/README.md`](revisioncleanup/README.md) + +### What differs per component + +| aspect | decomposed / decomposeds3 | posix | +|------------|---------------------------|-------| +| **lookup** (`InternalPath`) | computed from the ids: `/spaces//nodes/`; children are found through symlinks named after the child in the parent's node directory | the real path of the file, looked up in the NATS KV id cache (id → path); `IDsForPath` goes the other way | +| **metadata** | `messagepack` (`.mpk` file next to the node, default) or `xattrs` | `hybrid` (xattrs, large values spill over into `.mpk` files in `.oc-nodes`, default) or `xattrs`; the node id is stored in an xattr on the file | +| **blobstore** | local blob directory or S3 bucket, addressed by blob id | no separate blobs: `Upload` moves or copies the uploaded file into the real file path; `Delete` is a no-op | +| **tree** | creates/moves nodes by manipulating node files and symlinks | creates/moves real files and directories; additionally watches the file system and *assimilates* external changes (new ids, metadata, revisions with `enable_fs_revisions`) | +| **revisions** | `.REV.` node file next to the node, content in a blob | full copy in `/.oc-nodes/.REV.`; with `enable_fs_revisions` a `.CURRENT` copy is kept to create revisions from changes on disk | +| **trash** | deleted nodes are renamed in place to `.T.`, and a symlink in `/spaces//trash` points to them | freedesktop.org style `/.Trash/{files,info}` with `.trashinfo` files | +| **spaces** | space roots at `/spaces/`, derived from the id | space roots are directories at the paths given by `personalspacepath_template` and `generalspacepath_template` (evaluated by the shared `CreateStorageSpace`, but only the posix lookup places space roots there) | +| **wrapping** | `Decomposedfs` returned as is | `posixFS` → `middleware.FS` → `Decomposedfs` | + +### How posix overrides and extends `Decomposedfs` + +`posixFS` embeds a `storage.FS` (the middleware wrapping `Decomposedfs`), so every `storage.FS` method is forwarded automatically. +Go only promotes the methods of the embedded *interface type*, though, not those of the concrete type behind it. +That means optional interfaces that `Decomposedfs` implements in addition to `storage.FS` would be invisible on `posixFS`. +`posixFS` therefore forwards them explicitly with type assertions, e.g. `WithDisabledSpaces`, `PrepareCreatesNode` (`storage.NodeCreator`) and `IsOrphaned` (`storage.OrphanChecker`). +It also adds posix-only methods such as `WarmupIDCache`. +When `Decomposedfs` gains a new optional interface, posix only supports it once a forwarding method is added to `posixFS`. + +Other places where posix hooks into the shared code: + +- **Middleware hooks** (`pkg/storage/utils/middleware`): with `use_space_groups`, every call first resolves the space's unix group and scopes the process to it, so files are created with the right group ownership. +- **Trashbin setup:** `Trashbin.Setup(fs)` is called twice for posix: in `posix.New` with the `posixFS` wrapper (not filled in yet at that point), and in `decomposedfs.New` with the inner `Decomposedfs`. The posix trashbin keeps the first reference and ignores the second, but currently does not use it otherwise. `DecomposedfsTrashbin` on the other hand requires a `*Decomposedfs` and uses it to implement trash operations. +- **Driver specific behaviour inside the shared code** is selected through the aspects, not through type switches. For example, `CommitUpload` calls `tp.WriteBlob`, which in posix moves the upload into the real file and updates `.CURRENT`, while in decomposedfs it uploads a blob. + +### Uploads + +The upload coordinator (`pkg/upload`) owns the upload sessions and the staged bytes, and drives every upload through the same steps of the driver: + +1. `PrepareUpload`, once all bytes are received: it re-checks the preconditions, creates the node of a new file, or keeps the previous content of an existing one as a revision (`tp.CreateRevision`, unless versioning is disabled), and writes the new metadata. Usually it marks the node as processing for the upload's session. + A driver whose blobs are kept apart from the nodes (`SeparateBlobs`, i.e. not posix) can finish an upload right here when there is no postprocessing, e.g. a synchronous upload: it stores the blob before the node points to it and never marks the node (the result says `Committed`). +2. postprocessing, with async uploads: the coordinator publishes the staged upload and waits for the result. +3. `CommitUpload`, once the bytes may be stored: it writes them (`tp.WriteBlob`). If a newer upload took over the node in the meantime, they go into the revision that upload kept for this one. +4. `MarkProcessing(false)` clears the processing mark of the session, if the node still carries it. + +When an upload fails after `PrepareUpload`, e.g. in postprocessing, the coordinator calls `RollbackUpload`, which restores the previous state from the revision, and then `MarkProcessing(false)`. + +### Changes on disk (posix only) + +`decomposed` and `decomposeds3` assume they are the only writers. +posix allows changes to the files on disk, and picks them up through the watcher configured with `watch_fs`/`watch_type`: inotify, GPFS, CephFS or NATS. +It can also scan the whole tree at startup (`scan_fs`). +Detected changes are queued (`ScanDebouncer`) and *assimilated* (`tree/assimilation.go`): new files get an id and metadata, moved files keep their id via the id cache, and sizes are propagated. +With `enable_fs_revisions` a revision is created from the previous `.CURRENT` copy. +This path bypasses `Decomposedfs` and the upload code completely, so any feature that hooks into uploads (e.g. revision cleanup, postprocessing) needs a separate trigger in assimilation if it should also apply to changes on disk. + +The inotify watcher starts `inotifywait` with `KillOthers`, which runs `pkill inotifywait`. +Only one watching posix instance per host is therefore possible, which matters for tests (see `fs/posix/tree/export_test.go`). + +## Where to start reading + +- `decomposedfs.go` – `NewDefault`, `New`, the `Decomposedfs` struct +- `aspects/aspects.go` – the extension points +- `node/node.go` – `Node`, and the `Tree`, `PathLookup` and `Blobstore` interfaces +- `prepare_upload.go`, `commit_upload.go` – the steps of an upload; `pkg/upload/coordinator.go` – the upload coordinator that calls them +- `pkg/storage/fs/posix/posix.go` – how posix assembles its aspects and wraps the result +- `pkg/storage/fs/posix/tree/assimilation.go` – how changes on disk are picked up diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/aspects/aspects.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/aspects/aspects.go index 1fafc023b1..28d0d7b468 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/aspects/aspects.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/aspects/aspects.go @@ -22,6 +22,7 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/events" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/permissions" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/trashbin" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/usermapper" ) @@ -37,4 +38,9 @@ type Aspects struct { // SeparateBlobs is set when the blobstore keeps blobs apart from the nodes, // so a blob can be stored before any node references it. SeparateBlobs bool + // RevisionsCleanup deletes old revisions after new ones have been created, right away or in + // background workers; disabled without a strategy, and nil disables it as well. It is + // passed in here rather than created by Decomposedfs because posix needs the same instance + // (and the same workers) in its own tree, for revisions created from changes on disk. + RevisionsCleanup *revisioncleanup.Service } diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/commit_upload.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/commit_upload.go index 73d35341b3..ac7f6ef5d3 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/commit_upload.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/commit_upload.go @@ -101,6 +101,21 @@ func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Referenc return err } + // set once this upload wrote its content into the revision a newer upload created for it + cleanupRevisions := false + // That revision only becomes a version here, when its processing mark is removed, after the + // cleanup triggered by the newer upload left it alone: apply the revision cleanup strategy + // (see package revisioncleanup) once more. HandleUploadFinished, which triggers it for all + // other uploads, can't tell this case: the versionCreated of this upload is about the content + // it replaced itself, not about this revision. It never fails the upload. Registered before + // the lock is taken, so that it runs once the locks are released, for the reasons given in + // RestoreRevision. + defer func() { + if cleanupRevisions { + fs.revisionsCleanup.HandleRevisionCreated(ctx, n) + } + }() + unlock, err := fs.lu.MetadataBackend().Lock(n) if err != nil { return errors.Wrap(err, "Decomposedfs: could not lock node") @@ -159,6 +174,7 @@ func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Referenc if err := target.RemoveXattr(ctx, prefixes.StatusPrefix); err != nil && !metadata.IsAttrUnset(err) { appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", target.ID).Msg("could not remove the processing mark from the revision") } + cleanupRevisions = true } else { // revisions kept only for a rollback of this upload served their purpose; versions // stay, also the ones created before versioning was disabled @@ -193,7 +209,7 @@ func (fs *Decomposedfs) removeRevisions(ctx context.Context, n *node.Node) { continue } revisionNode := node.NewBaseNode(n.SpaceID, n.ID+node.RevisionIDDelimiter+strings.TrimPrefix(rev, revPrefix), fs.lu) - if !fs.keptForRollback(ctx, revisionNode) { + if !node.KeptForRollback(ctx, fs.lu.MetadataBackend(), revisionNode) { continue } blobID, err := fs.lu.MetadataBackend().Get(ctx, revisionNode, prefixes.BlobIDAttr) @@ -207,17 +223,6 @@ func (fs *Decomposedfs) removeRevisions(ctx context.Context, n *node.Node) { } } -// keptForRollback reports whether a revision exists only for a rollback, rather than as a -// version. -func (fs *Decomposedfs) keptForRollback(ctx context.Context, revision metadata.MetadataNode) bool { - for _, attr := range []string{purgeOnRestoreAttr, uploadSnapshotAttr} { - if _, err := fs.lu.MetadataBackend().Get(ctx, revision, attr); err == nil { - return true - } - } - return false -} - // uploadRevision returns the locked revision of n that holds the upload sessionID, // or nil if there is none. func (fs *Decomposedfs) uploadRevision(ctx context.Context, n *node.Node, sessionID string) (*node.Node, metadata.UnlockFunc, error) { diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/decomposedfs.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/decomposedfs.go index 68eeee865d..db4e293cbb 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/decomposedfs.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/decomposedfs.go @@ -16,6 +16,10 @@ // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. +// Package decomposedfs is the shared core of the decomposed, decomposeds3 and posix +// storage drivers. Each driver supplies its storage layout through aspects.Aspects, +// see README.md in this directory for how the drivers are built and how they +// delegate to and override the shared code. package decomposedfs import ( @@ -55,6 +59,7 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/permissions" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/spaceidindex" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/timemanager" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/trashbin" @@ -101,6 +106,10 @@ type Decomposedfs struct { // separateBlobs is set when the blobstore keeps blobs apart from the nodes separateBlobs bool + // deletes old revisions after uploads and restores created new ones, disabled + // without a strategy, see aspects.Aspects. + revisionsCleanup *revisioncleanup.Service + UserCache *ttlcache.Cache userSpaceIndex *spaceidindex.Index groupSpaceIndex *spaceidindex.Index @@ -155,16 +164,30 @@ func NewDefault(m map[string]interface{}, bs node.Blobstore, es events.Stream, l store.TLSRootCA(o.IDCache.TLSRootCACertificate), ), log) - aspects := aspects.Aspects{ - Lookup: lu, - Tree: tp, - Permissions: p, - EventStream: es, - Trashbin: &DecomposedfsTrashbin{}, - SeparateBlobs: true, + // fail at startup on an invalid strategy or async settings rather than silently keeping + // or deleting revisions the admin did not expect. The posix driver does the same in tree.New. + revisionsCleanup, err := revisioncleanup.NewServiceFromOptions(o, lu, tp, log) + if err != nil { + return nil, errors.Wrap(err, "invalid revisions cleanup configuration") } - return New(o, aspects, log) + aspects := aspects.Aspects{ + Lookup: lu, + Tree: tp, + Permissions: p, + EventStream: es, + Trashbin: &DecomposedfsTrashbin{}, + SeparateBlobs: true, + RevisionsCleanup: revisionsCleanup, + } + + fs, err := New(o, aspects, log) + if err != nil { + // stop the workers of the revision cleanup again + _ = revisionsCleanup.Shutdown(context.Background()) + return nil, err + } + return fs, nil } // New returns an implementation of the storage.FS interface that talks to @@ -217,20 +240,21 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor } fs := &Decomposedfs{ - tp: aspects.Tree, - lu: aspects.Lookup, - trashbin: aspects.Trashbin, - o: o, - p: aspects.Permissions, - um: aspects.UserMapper, - stream: aspects.EventStream, - separateBlobs: aspects.SeparateBlobs, - UserCache: ttlcache.NewCache(), - userSpaceIndex: userSpaceIndex, - groupSpaceIndex: groupSpaceIndex, - mailSpaceIndex: mailSpaceIndex, - spaceTypeIndex: spaceTypeIndex, - log: log, + tp: aspects.Tree, + lu: aspects.Lookup, + trashbin: aspects.Trashbin, + o: o, + p: aspects.Permissions, + um: aspects.UserMapper, + stream: aspects.EventStream, + separateBlobs: aspects.SeparateBlobs, + UserCache: ttlcache.NewCache(), + revisionsCleanup: aspects.RevisionsCleanup, + userSpaceIndex: userSpaceIndex, + groupSpaceIndex: groupSpaceIndex, + mailSpaceIndex: mailSpaceIndex, + spaceTypeIndex: spaceTypeIndex, + log: log, } if err = fs.trashbin.Setup(fs); err != nil { return nil, err @@ -297,7 +321,7 @@ func (fs *Decomposedfs) handleRevisionEvent(ctx context.Context, event events.Ev sublog.Debug().Msg("node is not stuck, ignoring") return } - _, deleteErr = n.DeleteRevision(ctx, "") + _, deleteErr = n.DeleteRevisionUnchecked(ctx, "") } else { versionID := time.Unix(int64(ev.Timestamp.Seconds), int64(ev.Timestamp.Nanos)).UTC().Format(time.RFC3339Nano) deleteErr = fs.deleteRevisionFile(ctx, n, n.ID+node.RevisionIDDelimiter+versionID) @@ -319,7 +343,8 @@ func (fs *Decomposedfs) WithDisabledSpaces() storage.FS { // Shutdown shuts down the storage func (fs *Decomposedfs) Shutdown(ctx context.Context) error { - return nil + // stop the background revision cleanup workers, see revisioncleanup.Service.Shutdown + return fs.revisionsCleanup.Shutdown(ctx) } // Capabilities declares decomposedfs fully writeable, stated explicitly so it is diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go index 4adb4c60a1..adba3b4794 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go @@ -133,17 +133,56 @@ func (b HybridBackend) All(ctx context.Context, n MetadataNode) (map[string][]by } if !n.LockHeld() { - unlock, err := b.Lock(n) + unlock, locked, err := b.lockToRead(ctx, n) if err != nil { return nil, err } defer func() { _ = unlock() }() + if !locked { + // read without a lock, see WithReadOnly: it may see a write halfway through, so + // don't cache it, where it could replace what the writer just cached + return b.readAll(ctx, n, false) + } } return b.getAll(ctx, n, false) } +// Reload reads all extended attributes for a node from storage, never from the cache, +// and updates the cache with them, except after a read without a lock (see WithReadOnly). +// It acquires a shared file lock unless the caller already holds the node's metadata lock +// (n.LockHeld()). +func (b HybridBackend) Reload(ctx context.Context, n MetadataNode) (map[string][]byte, error) { + if !n.LockHeld() { + unlock, locked, err := b.lockToRead(ctx, n) + if err != nil { + return nil, err + } + defer func() { _ = unlock() }() + if !locked { + // read without a lock, see WithReadOnly: it may see a write halfway through, so + // don't cache it, where it could replace what the writer just cached + return b.readAll(ctx, n, false) + } + } + + return b.getAll(ctx, n, false) +} + +// getAll reads all attributes of n from storage, like readAll, and caches them. func (b HybridBackend) getAll(ctx context.Context, n MetadataNode, skipOffloaded bool) (map[string][]byte, error) { + attribs, err := b.readAll(ctx, n, skipOffloaded) + if err != nil { + return nil, err + } + if err := b.metaCache.PushToCache(b.cacheKey(n), attribs); err != nil { + return nil, err + } + return attribs, nil +} + +// readAll reads all attributes of n from storage, without caching them. +func (b HybridBackend) readAll(ctx context.Context, n MetadataNode, skipOffloaded bool) (map[string][]byte, error) { b.metrics.reads.Inc() attribs := map[string][]byte{} attrNames, err := b.list(ctx, n) @@ -152,10 +191,6 @@ func (b HybridBackend) getAll(ctx context.Context, n MetadataNode, skipOffloaded } if len(attrNames) == 0 { - err = b.metaCache.PushToCache(b.cacheKey(n), attribs) - if err != nil { - return nil, err - } return attribs, nil } @@ -200,11 +235,6 @@ func (b HybridBackend) getAll(ctx context.Context, n MetadataNode, skipOffloaded } } - err = b.metaCache.PushToCache(b.cacheKey(n), attribs) - if err != nil { - return nil, err - } - return attribs, nil } @@ -549,6 +579,28 @@ func (b HybridBackend) Lock(n MetadataNode) (UnlockFunc, error) { }, nil } +// lockToRead locks n to read its metadata, like Lock. Under WithReadOnly, it doesn't create the +// lock file: it locks the lock file only if it exists, and doesn't lock otherwise, which locked +// tells. +func (b HybridBackend) lockToRead(ctx context.Context, n MetadataNode) (unlock UnlockFunc, locked bool, err error) { + if !IsReadOnly(ctx) { + unlock, err = b.Lock(n) + return unlock, err == nil, err + } + mlock, locked, err := lockExisting(n, b.LockfilePath(n), os.O_RDWR, b.metrics) + if err != nil { + return nil, false, err + } + if !locked { + return func() error { return nil }, false, nil + } + n.SetLockHeld(true) + return func() error { + n.SetLockHeld(false) + return mlock.Close() + }, true, nil +} + func (b HybridBackend) cacheKey(n MetadataNode) string { // rootPath is guaranteed to have no trailing slash // the cache key shouldn't begin with a slash as some stores drop it which can cause diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go index 6080a0a918..6834721e69 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go @@ -91,6 +91,12 @@ func (b MessagePackBackend) All(ctx context.Context, n MetadataNode) (map[string return b.loadAttributes(ctx, n) } +// Reload reads all extended attributes for a node from storage, never from the cache, +// and updates the cache with them +func (b MessagePackBackend) Reload(ctx context.Context, n MetadataNode) (map[string][]byte, error) { + return b.readAttributes(ctx, n) +} + // Get an extended attribute value for the given key func (b MessagePackBackend) Get(ctx context.Context, n MetadataNode, key string) ([]byte, error) { attribs, err := b.loadAttributes(ctx, n) @@ -219,9 +225,15 @@ func (b MessagePackBackend) loadAttributes(ctx context.Context, n MetadataNode) return attribs, err } + // No cached entry found. Read from storage and store in cache + return b.readAttributes(ctx, n) +} + +// readAttributes reads the attributes of a node from storage and stores them in the cache +func (b MessagePackBackend) readAttributes(ctx context.Context, n MetadataNode) (map[string][]byte, error) { + attribs := map[string][]byte{} metaPath := b.MetadataPath(n) - // No cached entry found. Read from storage and store in cache b.metrics.reads.Inc() _, subspan := tracer.Start(ctx, "os.Open") source, err := os.Open(metaPath) diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/metadata.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/metadata.go index b1a6b484aa..b1da886d32 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/metadata.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/metadata.go @@ -56,6 +56,12 @@ type Backend interface { // All reads all extended attributes for a node. It acquires the node's metadata // lock unless n.LockHeld() reports that the caller already holds it. All(ctx context.Context, n MetadataNode) (map[string][]byte, error) + // Reload reads all extended attributes for a node from storage, never from the + // cache, and updates the cache with them. The cache may be local to the process, + // so another process, e.g. a command run next to the server, can have changed the + // attributes since they were cached: use Reload where a decision must not rest on + // such a stale state. It locks like All. + Reload(ctx context.Context, n MetadataNode) (map[string][]byte, error) Get(ctx context.Context, n MetadataNode, key string) ([]byte, error) GetInt64(ctx context.Context, n MetadataNode, key string) (int64, error) @@ -92,6 +98,11 @@ func (NullBackend) All(ctx context.Context, n MetadataNode) (map[string][]byte, return nil, errUnconfiguredError } +// Reload reads all extended attributes for a node from storage +func (NullBackend) Reload(ctx context.Context, n MetadataNode) (map[string][]byte, error) { + return nil, errUnconfiguredError +} + // Get an extended attribute value for the given key func (NullBackend) Get(ctx context.Context, n MetadataNode, key string) ([]byte, error) { return []byte{}, errUnconfiguredError diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/readonly.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/readonly.go new file mode 100644 index 0000000000..e846c105e0 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/readonly.go @@ -0,0 +1,47 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package metadata + +import ( + "context" + "errors" + "os" +) + +type readOnlyKey struct{} + +// WithReadOnly returns a context for reads that must not change anything on disk, e.g. the +// dry run of a revision cleanup. +// +// Today it covers the lock files: to read the metadata of a node, the backends that lock to +// read (the hybrid backend, and the xattrs backend in its locked retry) lock the lock file of +// the node only if it exists, and read without a lock otherwise, instead of creating the lock +// file and its folder. A read without a lock can see a write to the node halfway through, so +// use it only where that is acceptable, never for the reads of the server; and what it read +// isn't cached, where it could replace what a writer cached meanwhile. Writes are not +// affected: they lock, and create the lock files, as before. +func WithReadOnly(ctx context.Context) context.Context { + return context.WithValue(ctx, readOnlyKey{}, true) +} + +// IsReadOnly tells whether ctx is meant for reads that must not change anything on disk, see +// WithReadOnly. +func IsReadOnly(ctx context.Context) bool { + readOnly, _ := ctx.Value(readOnlyKey{}).(bool) + return readOnly +} + +// lockExisting locks the lock file at path like lockFile, but never creates it: locked is +// false, and there is no error, when there is no lock file to lock. It is how the backends +// lock to read under WithReadOnly. +func lockExisting(n MetadataNode, path string, flag int, m *backendMetrics) (l *heldLock, locked bool, err error) { + l, err = lockFile(n, path, flag&^os.O_CREATE, m) + switch { + case errors.Is(err, os.ErrNotExist): + return nil, false, nil + case err != nil: + return nil, false, err + } + return l, true, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go index 634dbcb67b..b21d85509c 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go @@ -107,17 +107,26 @@ func (b XattrsBackend) list(ctx context.Context, n MetadataNode, acquireLock boo // listing xattrs failed, try again, either with lock or without if acquireLock { - f, err := lockFile(n, filePath+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, b.metrics) + lockPath := filePath + filelocks.LockFileSuffix + var f *heldLock + locked := true + if IsReadOnly(ctx) { + // lock only an existing lock file, and don't lock without one + f, locked, err = lockExisting(n, lockPath, os.O_WRONLY, b.metrics) + } else { + f, err = lockFile(n, lockPath, os.O_CREATE|os.O_WRONLY, b.metrics) + } if err != nil { return nil, err } - n.SetLockHeld(true) - // Warning: do not remove the lockfile or we may lock the same file more than once, https://github.com/opencloud-eu/opencloud/issues/1793 - defer func() { - n.SetLockHeld(false) - _ = f.Close() - }() - + if locked { + n.SetLockHeld(true) + // Warning: do not remove the lockfile or we may lock the same file more than once, https://github.com/opencloud-eu/opencloud/issues/1793 + defer func() { + n.SetLockHeld(false) + _ = f.Close() + }() + } } return listXattr(ctx, filePath) } @@ -128,6 +137,23 @@ func (b XattrsBackend) All(ctx context.Context, n MetadataNode) (map[string][]by return b.getAll(ctx, n, false, !n.LockHeld()) } +// Reload reads all extended attributes for a node from storage, never from the cache, +// and updates the cache with them. It acquires a shared file lock unless the caller +// already holds the node's metadata lock (n.LockHeld()). +func (b XattrsBackend) Reload(ctx context.Context, n MetadataNode) (map[string][]byte, error) { + attribs, err := b.getAll(ctx, n, true, !n.LockHeld()) + if err != nil { + return nil, err + } + if len(attribs) == 0 { + // getAll doesn't cache a node without attributes, so the stale entry would stay + if err := b.metaCache.PushToCache(b.cacheKey(n), attribs); err != nil { + return nil, err + } + } + return attribs, nil +} + func (b XattrsBackend) getAll(ctx context.Context, n MetadataNode, skipCache, acquireLock bool) (map[string][]byte, error) { attribs := map[string][]byte{} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node/node.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node/node.go index 8c86dd06ee..57b4ab9b65 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node/node.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node/node.go @@ -147,12 +147,36 @@ type Tree interface { ResolveSpaceIDIndexEntry(spaceID string) (string, error) CreateRevision(ctx context.Context, n *Node, version string) (string, error) - ListRevisions(ctx context.Context, ref *provider.Reference) ([]*provider.FileVersion, error) - DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) + // ListRevisions and DownloadRevision check no permissions: Decomposedfs checks them for the + // requests of users, and the revision cleanup (see package revisioncleanup) lists + // revisions on behalf of the system, e.g. in async postprocessing, where the context has + // no user with suitable permissions. + ListRevisions(ctx context.Context, n *Node) ([]*provider.FileVersion, error) + // DownloadRevision gets the permissions of the user on n in rp, for the resource info. + DownloadRevision(ctx context.Context, n *Node, revisionKey string, rp *provider.ResourcePermissions, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) Propagate(ctx context.Context, node *Node, sizeDiff int64) (err error) } +// ValidateRevisionKey makes sure that revisionKey denotes a revision of n. +// +// Callers that turn a full revision key into a version for Node.DeleteRevisionUnchecked, like +// revisioncleanup.PurgeRevisionUnchecked, use it to guard against keys that would hit something +// else, as Node.DeleteRevisionUnchecked does not check permissions: +// - a key of another node, which would delete that node's revision +// - the bare '.REV.' prefix, or the node id itself: they would turn into an +// empty version, for which Node.DeleteRevisionUnchecked deletes the node's *current* revision, +// i.e. reverts the node to its latest revision or purges the node if there is none +// - path separators, as the key is turned into a file path +func ValidateRevisionKey(n *Node, revisionKey string) error { + if !strings.HasPrefix(revisionKey, n.ID+RevisionIDDelimiter) || + len(revisionKey) == len(n.ID+RevisionIDDelimiter) || + strings.ContainsAny(revisionKey, `/\`) { + return errtypes.BadRequest(fmt.Sprintf("invalid revision key %q for node %q", revisionKey, n.ID)) + } + return nil +} + // PathLookup defines the interface for the lookup component type PathLookup interface { WithDisabledSpaces() PathLookup @@ -1687,13 +1711,15 @@ func (n *Node) RevertUpload(ctx context.Context, versionID string) error { return nil } -// DeleteRevision deletes a revision of the node and returns the blob id of the +// DeleteRevisionUnchecked deletes a revision of the node and returns the blob id of the // deleted revision, so that the caller can delete the blob. If versionID is // empty the node's current revision is deleted: the latest stored revision is // restored onto the node (or the node is purged when there is none) and the // processing flag is removed, unstalling the node. No blob is returned in that // case. -func (n *Node) DeleteRevision(ctx context.Context, versionID string) (string, error) { +// +// It checks no permissions, Decomposedfs.DeleteRevision is the variant that does. +func (n *Node) DeleteRevisionUnchecked(ctx context.Context, versionID string) (string, error) { if versionID != "" { return n.deleteRevision(ctx, n.ID+RevisionIDDelimiter+versionID) } @@ -1769,6 +1795,56 @@ func (n *Node) deleteRevision(ctx context.Context, revisionID string) (string, e return blobID, nil } +// PurgeOnRestoreAttr marks a revision kept for an upload that created the file and was +// rolled back while a newer upload was processing: restoring it removes the file. +var PurgeOnRestoreAttr = prefixes.OcPrefix + "purgeonrestore" + +// UploadSnapshotAttr marks a revision PrepareUpload kept with versioning disabled, only so +// that a rollback can hand the node back to the upload it superseded. It is not a version. +var UploadSnapshotAttr = prefixes.OcPrefix + "uploadsnapshot" + +// KeepAfterRestoreAttr marks the revision a restore created of the content it replaced. Its +// value is the blob id of the restored content: while the file still has it, the revision +// cleanup keeps the revision, so that the content the user just replaced can't be lost. +var KeepAfterRestoreAttr = prefixes.OcPrefix + "keepafterrestore" + +// RevisionCreatedAttr records when a revision was created, i.e. when the content it holds was +// replaced, as the time of the server in RFC 3339 format with nanoseconds (UTC). The name of a +// revision is the modification time of its content instead, which whoever writes the file can +// choose (X-OC-Mtime, or the mtime of a change on disk with posix). The revision cleanup orders +// revisions and measures their age by this attribute, so that nobody can date a revision such +// that the cleanup deletes other ones. Revisions created before it was introduced don't have it, +// see revisioncleanup. +// Write and read it with SetRevisionCreated and RevisionCreated, which decide how the time is +// stored. +var RevisionCreatedAttr = prefixes.OcPrefix + "revision.created" + +// SetRevisionCreated records t as the time revision was created, see RevisionCreatedAttr. +func SetRevisionCreated(ctx context.Context, backend metadata.Backend, revision metadata.MetadataNode, t time.Time) error { + return backend.Set(ctx, revision, RevisionCreatedAttr, []byte(t.UTC().Format(time.RFC3339Nano))) +} + +// RevisionCreated returns the time revision was created, see RevisionCreatedAttr. It fails for +// a revision created before that time was recorded. +func RevisionCreated(ctx context.Context, backend metadata.Backend, revision metadata.MetadataNode) (time.Time, error) { + created, err := backend.Get(ctx, revision, RevisionCreatedAttr) + if err != nil { + return time.Time{}, err + } + return time.Parse(time.RFC3339Nano, string(created)) +} + +// KeptForRollback reports whether a revision exists only for a rollback, rather than as a +// version (see PurgeOnRestoreAttr and UploadSnapshotAttr). +func KeptForRollback(ctx context.Context, backend metadata.Backend, revision metadata.MetadataNode) bool { + for _, attr := range []string{PurgeOnRestoreAttr, UploadSnapshotAttr} { + if _, err := backend.Get(ctx, revision, attr); err == nil { + return true + } + } + return false +} + // RevertLatestRevision reverts the upload that created the node's latest // revision: the revision is restored onto the node and removed. Unlike // DeleteRevision it neither purges the node when there is no revision nor diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options/options.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options/options.go index 4c8cc26ce9..56e78330c6 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options/options.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options/options.go @@ -96,6 +96,67 @@ type Options struct { DisableVersioning bool `mapstructure:"disable_versioning"` + // RevisionsCleanupStrategy defines which old revisions of a file are deleted after a new + // revision has been created, e.g. "auto", "14d, auto", "auto, 90d" or "7d, auto, 90d". + // Leaving it empty or setting it to "disabled" keeps all revisions. + // + // The supported forms, where X is a duration with a unit suffix (w, d, h, m, s) or + // a plain number of revisions, which always refers to the newest revisions: + // - "auto": thin out revisions the older they get, keeping e.g. one per 10 + // seconds in the last minute, one per minute in the last hour, one per hour in + // the last day, one per day in the last 30 days and one per week beyond + // - "X": delete everything beyond X, e.g. "10" or "30d"; "0" deletes all revisions, + // which, unlike disable_versioning, also removes the ones accumulated so far + // - "X, auto": keep everything within X, apply "auto" to the older revisions + // - "auto, X": delete everything beyond X, apply "auto" to the rest + // - "X1, X2": keep everything within X1, delete everything beyond X2; one must be + // a number and the other a duration, e.g. "5, 30d" or "7d, 10" + // - "X1, auto, X2": keep everything within X1, delete everything beyond X2 and + // apply "auto" in between, e.g. "7d, auto, 90d" + // - "disabled": never delete any revisions + // + // A number of revisions to keep counts the ones within X1 too: "7d, 10" keeps at + // most 10 revisions, unless more than 10 are younger than 7 days. + // + // The age of a revision is the time its content was written, i.e. the modification time + // the file had before it was changed, not the time of that change, which turned the + // content into a revision. A revision created today from content that was unchanged for + // two months is two months old, so e.g. "30d" deletes it right away; combine + // durations with a number of revisions, e.g. "5, 30d", to always keep the newest ones. + // + // A duration in days or weeks with an uppercase unit (D, W) is aligned to midnight in the + // server's local time zone: "1d" means the last 24 hours, "1D" since yesterday 00:00, + // "0D" since today 00:00, e.g. "1D, auto, 30d". + // + // See revisions.NewRevisionCleanupStrategy in pkg/storage/revisions for the exact + // grammar and pkg/storage/pkg/decomposedfs/revisioncleanup for when it is applied. + // It is shared by all decomposedfs based drivers, including posix, and also applies + // to revisions posix creates from changes on disk (enable_fs_revisions). + // An invalid value makes the driver fail at startup. + RevisionsCleanupStrategy string `mapstructure:"revisions_cleanup_strategy"` + + // RevisionsCleanupAsync runs the revision cleanup in the background instead of as part of + // the upload, restore or change on disk that created the new revision, so that those are not + // slowed down by it. Defaults to true. + RevisionsCleanupAsync bool `mapstructure:"revisions_cleanup_async"` + // RevisionsCleanupAsyncWorkers is the number of background workers for the revision cleanup. + // 0, the default, determines it automatically: half the available CPUs (which respects + // container CPU limits), but at least 2. + RevisionsCleanupAsyncWorkers int `mapstructure:"revisions_cleanup_async_workers"` + // RevisionsCleanupAsyncQueueSize is the number of nodes that can wait for a background + // revision cleanup. 0, the default, determines it automatically from the number of workers. + RevisionsCleanupAsyncQueueSize int `mapstructure:"revisions_cleanup_async_queue_size"` + // RevisionsCleanupAsyncQueueFull defines what happens when a new revision is created while + // the queue is full: "drop" (the default) skips the cleanup of that node and logs it, the + // node is cleaned up again when it gets its next revision; "block" waits until there is + // room, for at most RevisionsCleanupAsyncQueueFullTimeout, so that no cleanup is skipped + // unless the queue stays full that long, at the cost of slowing down writes under heavy + // load. + RevisionsCleanupAsyncQueueFull string `mapstructure:"revisions_cleanup_async_queue_full"` + // RevisionsCleanupAsyncQueueFullTimeout is how long "block" waits for room in a full queue, + // before the cleanup of the node is skipped as with "drop". 0 waits as long as it takes. + RevisionsCleanupAsyncQueueFullTimeout time.Duration `mapstructure:"revisions_cleanup_async_queue_full_timeout"` + MountID string `mapstructure:"mount_id"` MultiTenantEnabled bool `mapstructure:"multi_tenant_enabled"` @@ -121,7 +182,12 @@ type TokenOptions struct { // New returns a new Options instance for the given configuration func New(m map[string]interface{}) (*Options, error) { - o := &Options{} + o := &Options{ + // defaults for options that are not false/0/"" by default; mapstructure only + // overwrites the fields that are present in m + RevisionsCleanupAsync: true, + RevisionsCleanupAsyncQueueFullTimeout: 5 * time.Second, + } if err := mapstructure.Decode(m, o); err != nil { err = errors.Wrap(err, "error decoding conf") return nil, err diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/prepare_upload.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/prepare_upload.go index d264aca3db..924686a6ef 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/prepare_upload.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/prepare_upload.go @@ -264,6 +264,9 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen supersededMark := oldAttrs[prefixes.StatusPrefix] superseding := strings.HasPrefix(string(supersededMark), node.ProcessingStatus) if !fs.o.DisableVersioning || superseding { + // the revision is named after the mtime of the content it preserves, not after the + // time it is created; the revision cleanup goes by the time it is created, which + // CreateRevision records (see node.RevisionCreatedAttr) timestamp := oldMtime.UTC().Format(time.RFC3339Nano) versionPath, err := fs.tp.CreateRevision(ctx, n, timestamp) if err != nil { @@ -278,7 +281,7 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen revisionAttrs := map[string][]byte{prefixes.StatusPrefix: supersededMark} if fs.o.DisableVersioning { // not a version, only kept for a rollback: a live commit removes it - revisionAttrs[uploadSnapshotAttr] = []byte("1") + revisionAttrs[node.UploadSnapshotAttr] = []byte("1") } if err := fs.lu.MetadataBackend().SetMultiple(ctx, versionNode, revisionAttrs); err != nil { return nil, err @@ -517,20 +520,12 @@ func (fs *Decomposedfs) restoreLatestRevision(ctx context.Context, n *node.Node) if v, ok := revisionAttrs[prefixes.BlobsizeAttr]; ok { n.Blobsize, _ = strconv.ParseInt(string(v), 10, 64) } - _, purge = revisionAttrs[purgeOnRestoreAttr] + _, purge = revisionAttrs[node.PurgeOnRestoreAttr] removeRevision(ctx, fs.lu, revisionNode) return true, purge, nil } -// purgeOnRestoreAttr marks a revision kept for an upload that created the file and was -// rolled back while a newer upload was processing: restoring it removes the file. -var purgeOnRestoreAttr = prefixes.OcPrefix + "purgeonrestore" - -// uploadSnapshotAttr marks a revision PrepareUpload kept with versioning disabled, only so -// that a rollback can hand the node back to the upload it superseded. It is not a version. -var uploadSnapshotAttr = prefixes.OcPrefix + "uploadsnapshot" - // retireUploadRevision handles the revision a newer upload kept of the upload sessionID, // which is being rolled back. If that upload overwrote the file, the revision is dropped: // the one it kept itself describes the file before it. If it created the file, there is @@ -563,7 +558,7 @@ func (fs *Decomposedfs) retireUploadRevision(ctx context.Context, n *node.Node, removeRevision(ctx, fs.lu, &revision.BaseNode) return } - if err := revision.SetXattrsWithContext(ctx, node.Attributes{purgeOnRestoreAttr: []byte("1")}); err != nil { + if err := revision.SetXattrsWithContext(ctx, node.Attributes{node.PurgeOnRestoreAttr: []byte("1")}); err != nil { log.Error().Err(err).Msg("could not mark the upload's revision") } if err := revision.RemoveXattr(ctx, prefixes.StatusPrefix); err != nil && !metadata.IsAttrUnset(err) { diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup.go new file mode 100644 index 0000000000..e6dc0a30ee --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup.go @@ -0,0 +1,243 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package decomposedfs + +import ( + "context" + "fmt" + "maps" + "math/rand/v2" + "os" + "slices" + "strings" + + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/pkg/errors" + + "github.com/opencloud-eu/reva/v3/pkg/appctx" + "github.com/opencloud-eu/reva/v3/pkg/errtypes" + "github.com/opencloud-eu/reva/v3/pkg/storage" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup" +) + +var _ revisioncleanup.OnDemand = (*Decomposedfs)(nil) + +var _ storage.UploadFinishedHandler = (*Decomposedfs)(nil) + +// HandleUploadFinished applies the revision cleanup strategy (see package revisioncleanup) to +// the file of an upload that has finished, if the upload created a revision, see +// storage.UploadFinishedHandler. Uploads that created the file, and rolled back ones, which +// never get here, leave nothing to clean up. It never fails the upload. +// +// The revision a newer upload kept for an older one only becomes a version when the older +// upload writes its content into it, see CommitUpload, which triggers the cleanup for that case +// itself: versionCreated of the older upload doesn't say anything about that revision. +func (fs *Decomposedfs) HandleUploadFinished(ctx context.Context, ref *provider.Reference, _ string, versionCreated bool) { + if !versionCreated { + return + } + // The cleanup takes the file by its ids, without resolving a path. The coordinator always + // passes them: it sets the space id and the node id of a session when the upload is + // initiated, also for a new file, whose node id it chooses itself. A reference without + // them, e.g. one with only a path, would come from another caller and be a bug there: + // it is logged, and the file is left as it is, as a missed cleanup only keeps revisions + // a little longer, until the next one. + id := ref.GetResourceId() + if id.GetSpaceId() == "" || id.GetOpaqueId() == "" { + appctx.GetLogger(ctx).Error().Interface("ref", ref).Msg("revision cleanup: a finished upload without the ids of its file, not cleaning up") + return + } + fs.revisionsCleanup.HandleRevisionCreatedByID(ctx, id.GetSpaceId(), id.GetOpaqueId()) +} + +// CleanupRevisionsUnchecked cleans up the revisions of the files of whole spaces, or of a file or +// folder within a space, on demand, see revisioncleanup.OnDemand. It is meant for command line +// tools: it checks no permissions and needs no user in the context. +// +// With Request.All, a space that can't be cleaned up doesn't stop the others: a disabled space +// (in the trash) is reported as skipped, any other one as failed. A space requested by its id +// fails the request instead. +// +// Paths on disk (Request.FSPath) are not supported: the decomposed layout stores files under +// their ids. The posix driver resolves them before it calls this. +// +// The strategy and the AsyncOptions default to the configured ones (the +// revisions_cleanup_* options) and can be overridden in the request; without AsyncOptions in +// the request, the run waits for room in a full queue as long as it takes, see +// revisioncleanup.Request. +func (fs *Decomposedfs) CleanupRevisionsUnchecked(ctx context.Context, req revisioncleanup.Request, report func(revisioncleanup.Result)) error { + if err := req.Validate(); err != nil { + return err + } + if req.FSPath != "" { + return errtypes.NotSupported("cleaning up revisions by a path on disk, only the posix driver supports it") + } + if req.DryRun { + // a dry run changes nothing on disk, not even the lock files of what it reads + ctx = metadata.WithReadOnly(ctx) + } + w, ok := fs.tp.(revisioncleanup.Walker) + if !ok { + return errtypes.NotSupported("cleaning up revisions on demand, the tree can't list folders for maintenance") + } + if report == nil { + report = func(revisioncleanup.Result) {} + } + + strategy := req.Strategy + if strategy == "" { + strategy = fs.o.RevisionsCleanupStrategy + } + cleaner, err := revisioncleanup.New(strategy) + if err != nil { + return errors.Wrap(err, "invalid revisions cleanup strategy") + } + if !cleaner.Enabled() { + return errors.New("no revisions cleanup strategy configured or given") + } + o := revisioncleanup.RunOptions{Async: revisioncleanup.AsyncOptionsFromOptions(fs.o), DryRun: req.DryRun, Shuffle: req.Shuffle} + // a run queues the files as fast as it finds them: dropping them, or giving up after + // the timeout meant for uploads, would skip most of them + o.Async.QueueFull, o.Async.QueueFullTimeout = revisioncleanup.QueueFullBlock, 0 + if req.Async != nil { + o.Async = *req.Async + } + + roots, err := fs.revisionCleanupRoots(ctx, req, report) + if err != nil { + return err + } + return revisioncleanup.Run(ctx, fs.lu, w, roots, cleaner, o, report, fs.log) +} + +// errSpaceDisabled is the error for a space that is disabled, i.e. in the trash +var errSpaceDisabled = errors.New("the space is disabled") + +// revisionCleanupRoots resolves the scope of the request to the nodes to clean up below. With +// Request.All, it reports the spaces that can't be cleaned up and leaves them out. +func (fs *Decomposedfs) revisionCleanupRoots(ctx context.Context, req revisioncleanup.Request, report func(revisioncleanup.Result)) ([]*node.Node, error) { + // a space given more than once is cleaned up once + spaceIDs := uniqueInOrder(req.SpaceIDs) + if req.All { + ids, err := fs.allSpaceIDs() + if err != nil { + return nil, err + } + spaceIDs = ids + } + // Request.Shuffle randomizes the order in two places: here, the order of the spaces, and in + // revisioncleanup.Run, the order of the files and folders within each folder it walks + // through (RunOptions.Shuffle). + if req.Shuffle { + spaceIDs = slices.Clone(spaceIDs) + rand.Shuffle(len(spaceIDs), func(i, j int) { spaceIDs[i], spaceIDs[j] = spaceIDs[j], spaceIDs[i] }) + } + + roots := make([]*node.Node, 0, len(spaceIDs)) + for _, spaceID := range spaceIDs { + n, err := fs.revisionCleanupRootScoped(ctx, spaceID, req.Path) + // Stopped, before or during the lookup: the run ends here. A lookup that honours the + // context, e.g. of the posix id cache, fails then, but the space hasn't failed. + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, ctxErr + } + switch { + case err == nil: + roots = append(roots, n) + case !req.All: + return nil, err + case errors.Is(err, errSpaceDisabled): + report(revisioncleanup.Result{SpaceID: spaceID, NodeID: spaceID, DryRun: req.DryRun, Skipped: errSpaceDisabled.Error()}) + default: + // one space that can't be cleaned up doesn't stop the others + report(revisioncleanup.Result{SpaceID: spaceID, NodeID: spaceID, DryRun: req.DryRun, Err: err}) + } + } + return roots, nil +} + +// revisionCleanupRootScoped resolves the root, see revisionCleanupRoot, switched to the group of +// its space if the tree is a revisioncleanup.SpaceScoper: with posix use_space_groups, the +// folders on the way to the file or folder at path may only be accessible to that group, like +// the folders the cleanup walks through below it. +func (fs *Decomposedfs) revisionCleanupRootScoped(ctx context.Context, spaceID, path string) (*node.Node, error) { + scoper, ok := fs.tp.(revisioncleanup.SpaceScoper) + if !ok { + return fs.revisionCleanupRoot(ctx, spaceID, path) + } + scoped, unscope, err := scoper.ScopeToSpace(ctx, spaceID) + if err != nil { + return nil, errors.Wrapf(err, "could not switch to the group of space %q", spaceID) + } + defer func() { _ = unscope() }() + return fs.revisionCleanupRoot(scoped, spaceID, path) +} + +// revisionCleanupRoot resolves the space, or the file or folder at path within it. +func (fs *Decomposedfs) revisionCleanupRoot(ctx context.Context, spaceID, path string) (*node.Node, error) { + var n *node.Node + var err error + if path == "" { + n, err = fs.lu.NodeFromSpaceID(ctx, spaceID) + } else { + n, err = fs.lu.NodeFromResource(ctx, &provider.Reference{ + ResourceId: &provider.ResourceId{SpaceId: spaceID, OpaqueId: spaceID}, + Path: "./" + strings.TrimLeft(path, "/"), + }) + } + if err == nil && n != nil && n.Exists { + return n, nil + } + // the lookups don't find disabled spaces, tell them apart from missing ones + if root, rerr := node.ReadNode(ctx, fs.lu, spaceID, spaceID, "", true, nil, false); rerr == nil && root.Exists && root.IsDisabled(ctx) { + return nil, fmt.Errorf("space %q: %w", spaceID, errSpaceDisabled) + } + switch { + case err != nil: + return nil, errors.Wrapf(err, "could not find space %q", spaceID) + case path != "": + return nil, fmt.Errorf("no file or folder %q in space %q", path, spaceID) + default: + return nil, fmt.Errorf("no space %q", spaceID) + } +} + +// allSpaceIDs lists the ids of all spaces from the space type index, of all space types, +// without permission checks. +func (fs *Decomposedfs) allSpaceIDs() ([]string, error) { + spaceTypes, err := fs.spaceTypeIndex.Indexes() + if err != nil { + return nil, errors.Wrap(err, "could not list the space types") + } + // a space can be in the index of more than one type, collect each once + unique := map[string]struct{}{} + for _, spaceType := range spaceTypes { + spaces, err := fs.spaceTypeIndex.Load(spaceType) + if err != nil { + if os.IsNotExist(err) { + continue // no spaces of this type + } + return nil, errors.Wrapf(err, "could not read the index of %q spaces", spaceType) + } + for spaceID := range spaces { + unique[spaceID] = struct{}{} + } + } + return slices.Sorted(maps.Keys(unique)), nil +} + +// uniqueInOrder returns ids without duplicates, in the order of their first occurrence. +func uniqueInOrder(ids []string) []string { + seen := make(map[string]struct{}, len(ids)) + unique := make([]string, 0, len(ids)) + for _, id := range ids { + if _, ok := seen[id]; !ok { + seen[id] = struct{}{} + unique = append(unique, id) + } + } + return unique +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/README.md b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/README.md new file mode 100644 index 0000000000..052d11a116 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/README.md @@ -0,0 +1,156 @@ +# Revision cleanup + +Every change to a file keeps the previous content as a revision (version). +Without a cleanup, revisions accumulate forever and use up storage. +The revision cleanup deletes old revisions according to a configurable strategy, whenever a file gets a new revision. + +It works for the `decomposed`, `decomposeds3` and `posix` storage drivers. +With posix it also covers the revisions created from changes made directly on disk (`enable_fs_revisions`). +For how those drivers are structured, see [`../README.md`](../README.md); for implementation details, see the package documentation in `cleanup.go`. + +## Configuration + +The options are part of the decomposedfs options and therefore apply to all three drivers. + +| Option | Default | Meaning | +|---|---|---| +| `revisions_cleanup_strategy` | `""` (disabled) | Which revisions to delete, see below. Empty or `disabled` keeps all revisions. | +| `revisions_cleanup_async` | `true` | Run the cleanup in background workers, so that it doesn't slow down the upload, restore or change that created the new revision. `false` runs it right away. | +| `revisions_cleanup_async_workers` | `0` (automatic) | Number of background workers. Automatic: half the available CPUs (respecting container CPU limits), at least 2. | +| `revisions_cleanup_async_queue_size` | `0` (automatic) | Number of files that can wait for a background cleanup. Automatic: 64 per worker. | +| `revisions_cleanup_async_queue_full` | `drop` | What happens when the queue is full: `drop` skips the cleanup of that file (logged), it is cleaned up with its next revision; `block` waits for room, up to `revisions_cleanup_async_queue_full_timeout`. | +| `revisions_cleanup_async_queue_full_timeout` | `5s` | How long `block` waits for room at most, after which the cleanup of that file is skipped as with `drop`. `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. | + +An invalid value in any of these options makes the storage driver fail at startup. + +## Strategies + +A strategy is a comma separated list of up to three parts. +Each `X` is either + +- a plain number, which is a **number of revisions**, always counting from the newest one, or +- a number with a unit suffix, which is a **duration**: `w` weeks, `d` days, `h` hours, `m` minutes, `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` means since yesterday 00:00, `0D` since today 00:00. + +| Strategy | Meaning | Example | +|---|---|---| +| `auto` | Thin out revisions the older they get (see below) | `auto` | +| `X` | Delete everything beyond `X`, no thinning | `10` keeps the 10 newest revisions, `30d` deletes revisions older than 30 days, `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 and the other a duration | `5, 30d` deletes revisions older than 30 days but always keeps the 5 newest; `7d, 10` keeps at most 10 revisions but never deletes revisions younger than 7 days | +| `X1, auto, X2` | Keep everything within `X1`, delete everything beyond `X2`, thin out in between | `7d, auto, 90d`, `2, auto, 50`, `1D, auto, 30d` | +| `disabled` | Never delete revisions (same as empty) | `disabled` | + +Rules worth knowing: + +- **`auto` thins out revisions** by keeping one revision per time slot, the oldest one: it holds the content the file had when the slot began. The slots get longer the older the revisions are: + + | Age of the revision | Kept | + |---|---| + | last minute | one per 10 seconds | + | last hour | one per minute | + | last 24 hours | one per hour | + | last 30 days | one per day | + | older | one per week | + +- **A number of revisions is a total**, the protected revisions included: `7d, 10` keeps 10 revisions in total, not 10 on top of the ones from the last 7 days. Revisions within the protected range are never deleted, though, even if there are more of them. +- **In `auto, N`, the number `N` applies first, then `auto` thins out what is left.** So `auto, 10` keeps *at most* 10 revisions, usually fewer, and sometimes fewer than `auto` alone: if the 10 newest revisions were all saved within the same minute yesterday, `auto, 10` keeps a single revision, while `auto` keeps one of those plus one per day before. It does *not* mean "thin out first, then keep the 10 newest of what is left". The same goes for a number in `X1, auto, N`. +- **Two values of the same kind are rejected** in `X1, X2`, because one of them would have no effect: `5, 10` is the same as `10`, and `7d, 30d` is the same as `30d`. The error message names the equivalent single value. +- **In `X1, auto, X2` with two values of the same kind, `X1` must be smaller than `X2`**, otherwise `auto` would never apply. +- **`0` deletes all revisions.** Unlike `disable_versioning`, which only stops creating new revisions, this also removes the ones that have accumulated, over time (see [When the cleanup runs](#when-the-cleanup-runs) below). + +## How the age of a revision is measured + +A revision's age 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 recorded in an attribute of the revision (`user.oc.revision.created`) when the revision is created: by an upload, by a restore, or with `posix` by a change on disk. + +It is **not** the time the content of the revision was written, i.e. the modification time the file had before it was changed. +That time is what the revision is named after on disk, and the date the version list shows for it, but whoever writes the file can choose it, e.g. with the `X-OC-Mtime` header of an upload. +If the cleanup went by it, a client could date revisions such that the cleanup deletes other ones: a revision dated just after an existing one would push that one out of its slot of `auto`, and revisions dated years ahead would take the places of a number of revisions to keep, so that every new version would be deleted, also after the client lost access to the file. + +For files that sit unchanged for a long time, the two times are far apart: + +1. On August 14, a document is saved. +2. Nobody touches it for two months. +3. On October 14, it is changed. A revision is created to keep the previous content. The version list shows it as August 14. +4. The cleanup runs right after the change. The revision counts as created on October 14, a few seconds ago. + +So `30d` keeps that revision until November 13, 30 days after it was replaced. + +Revisions created before the attribute was introduced don't have it. Their time is estimated as the time they were replaced: the content time of the next newer revision, or the modification time of the file for the newest one, but never later than the current time. + +## When the cleanup runs + +The cleanup of a file runs after the file got a new revision: + +- after an upload replaced an existing file, once the upload is complete (with async postprocessing: once postprocessing finished), +- after a revision was restored; the revision holding the content from before the restore is kept by every cleanup, as long as the file still has the restored content: the next upload or restore, or a change on disk with posix, makes it a revision like any other. Until then, the strategy doesn't apply to it, also not an age limit like `30d`: a file that isn't changed again after a restore keeps this one revision, however old it gets, +- with posix and `enable_fs_revisions`, after a change on disk created a revision. + +The cleanup skips a file while an upload to it is still being processed, as that upload may still need its revisions. +Only the latest upload of a file is tracked, though: if an older upload is still being processed after a newer one finished, the cleanup runs anyway. +It then leaves the revision alone that the older upload will write its content into, and doesn't count it. + +Files that are never changed again keep their revisions. To clean those up as well, or to apply a different strategy once, the cleanup can also run on demand for whole spaces, folders or files: in OpenCloud with the command `opencloud storage-users revisions cleanup`. + +## Metrics + +The cleanup exports Prometheus metrics, all named `reva_revision_cleanup_*`. + +| Metric | Type | Meaning | +|---|---|---| +| `reva_revision_cleanup_enabled` | gauge | 1 if a strategy is configured, 0 otherwise | +| `reva_revision_cleanup_revisions_deleted_total` | counter | Deleted revisions | +| `reva_revision_cleanup_bytes_deleted_total` | counter | Total size of the deleted revisions | +| `reva_revision_cleanup_purge_failures_total` | counter | Revisions that could not be deleted, which are retried with the file's next revision, and revisions whose blob could not be deleted afterwards, which is left behind (logged with its blob id) | +| `reva_revision_cleanup_queue_full_total{outcome}` | counter | Requests that found the queue full, by `outcome`: `blocked` (the writer waited) or `dropped` (cleanup skipped); a writer that waited until the timeout of `block` counts as both | +| `reva_revision_cleanup_queue_length` | gauge | Files waiting for a background cleanup, including writers waiting for room in a full queue | +| `reva_revision_cleanup_queue_capacity` | gauge | Size of the queue | +| `reva_revision_cleanup_workers` | gauge | Background workers | +| `reva_revision_cleanup_running` | gauge | Files being cleaned up by workers right now | + +Things to keep in mind: + +- **The queue holds files, not revisions.** A file waits at most once, however many revisions it got in the meantime, and how many of its revisions get deleted is only decided when a worker processes it. +- **One process can have several queues.** The storageprovider and the dataprovider each create their own storage driver, and with it their own cleanup. The queue and worker gauges are the sum over all of them. + Because a sum can hide one queue being full while another one is empty, `queue_full_total` counts every request that found its queue full. + It is the most direct sign that there are too few workers or the queue is too small. +- **On-demand cleanups only count their deletions.** A cleanup of whole spaces, folders or files on demand uses a queue and workers of its own, which the queue, worker and `enabled` metrics leave out, as they describe the cleanup that runs whenever a file gets a new revision. The revisions it deletes are counted in `revisions_deleted_total`, `bytes_deleted_total` and `purge_failures_total`. + +Example queries: + +```promql +# revisions deleted per second, and storage freed per second +rate(reva_revision_cleanup_revisions_deleted_total[5m]) +rate(reva_revision_cleanup_bytes_deleted_total[5m]) + +# how full the queues are (0..1, can exceed 1 while writers wait for room) +reva_revision_cleanup_queue_length / reva_revision_cleanup_queue_capacity + +# requests hitting a full queue, worth an alert if it doesn't stay at 0 +sum by (outcome) (rate(reva_revision_cleanup_queue_full_total[5m])) + +# how busy the workers are (0..1) +reva_revision_cleanup_running / reva_revision_cleanup_workers + +# failed deletions, worth an alert +increase(reva_revision_cleanup_purge_failures_total[1h]) > 0 +``` + +## Logging + +- At startup with background workers: one info line `revision cleanup: running in the background` with the strategy, workers, queue size, queue full policy and timeout. +- Per cleaned file: one info line `revision cleanup: purged old revisions` with the strategy (`config`), the number and size of the deleted revisions, and how many revisions the file had. Nothing is logged for files where nothing was deleted. +- Every deleted revision is logged at debug level (`revision cleanup: purged revision`), with its `size` and the `reason`: which rule of the strategy deleted it, and the boundary it was evaluated with. This is particularly useful to understand the time slots of `auto`. Examples: + - `deleted by "30d": older than 2026-09-14T10:00:00Z` + - `deleted by "10": beyond the 10 newest, counting the 3 protected ones` + - `deleted by "auto" (last hour): its slot of 1 minute starting 2026-10-14T09:05:00Z already keeps an older revision` +- A revision dated in the future is logged as a warning (`revision cleanup: revision dated in the future, it counts as the newest one`), every time its file is cleaned up, and its reason ends in `dated in the future (...), so it counts as the newest`. Its time is when it was created, by the clock of the server, so this only happens when that clock was set back. Such a revision takes the first places of a number of revisions to keep, and no duration deletes it before its date has passed, which can make the cleanup delete the actual newest revisions instead: check the clock of the server. +- With `drop`, or when `block` gives up after its timeout, a skipped cleanup is logged as a warning; on shutdown, the number of abandoned queued cleanups is logged. + +## Limitations + +- **Shutdown:** cleanups still waiting in the queue are abandoned when the service stops. They are picked up again with the files' next revisions. diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/cleanup.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/cleanup.go new file mode 100644 index 0000000000..b59ee563d1 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/cleanup.go @@ -0,0 +1,723 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +// Package revisioncleanup applies a revisions.RevisionCleanupStrategy to the +// revisions of a node, independently of the storage driver that holds them. +// +// # How the storage drivers plug in +// +// All decomposedfs based drivers (decomposed, decomposeds3, posix) share the +// Decomposedfs struct, which implements the CS3 API, the upload sessions and +// RestoreRevision. What differs per driver is the on-disk layout, which each +// driver supplies as a node.Tree through aspects.Aspects: +// +// - decomposed and decomposeds3 use decomposedfs/tree.Tree. A revision is an +// empty node file next to the node, '.REV.', whose +// metadata references the content as a blob in the blobstore (BlobIDAttr). +// The two drivers differ only in the blobstore (local disk or S3). +// - posix uses fs/posix/tree.Tree. A revision is a full copy of the content in +// the '.oc-nodes' directory of the space (lookup.VersionPath), the posix +// blobstore does not hold any separate blobs. +// +// In both cases the revision key is '.REV.', with an +// optional '.' suffix when CreateRevision had to rename a colliding revision. +// +// See pkg/storage/pkg/decomposedfs/README.md for a more detailed overview of the +// driver structure. +// +// The shared code only knows node.Tree. Listing revisions is driver specific +// (node.Tree.ListRevisions), but deleting one is not: Node.DeleteRevisionUnchecked handles +// both layouts, and node.Tree.DeleteBlob deletes the blob in whichever blobstore the +// driver uses. PurgeRevisionUnchecked combines the two. So both the decision about *what* to +// delete and the deletion itself are made here, once for all drivers. +// Neither ListRevisions nor PurgeRevisionUnchecked check permissions: this is system +// housekeeping, which runs e.g. at the end of an upload, where there is no suitable +// user in the context. +// +// # When the cleanup runs +// +// Service.HandleRevisionCreated is called after a new revision has been created and has +// settled: +// +// - after an upload that replaced a file, once the upload has finished: the upload +// coordinator (pkg/upload) calls Decomposedfs.HandleUploadFinished for every successful +// upload, whether it was committed right away or after its postprocessing. Uploads that +// created the file, and uploads that were rolled back, don't trigger it, +// - in Decomposedfs.CommitUpload, when an upload that a newer one superseded wrote its +// content into the revision the newer upload created for it, which makes that revision +// a version (see "Overlapping uploads" below), +// - after Decomposedfs.RestoreRevision, +// - in posix, when a change on disk turned the '.CURRENT' copy into a revision +// (assimilation). Those revisions are created by a plain rename and never go +// through CreateRevision or the upload code, hence the separate trigger. +// +// Besides, the revisions of whole spaces, folders or single files can be cleaned up on demand, +// e.g. by a command line tool, through the OnDemand interface implemented by the storage drivers +// (see Request and Run). That cleanup also reaches files that never get a new revision anymore. +// +// It deliberately does not run inside Tree.CreateRevision, because revisions are +// not settled at that point while uploads are in flight: +// +// - An upload whose postprocessing is still pending writes its blob into a +// revision node that a newer upload created for it in the meantime +// (see Decomposedfs.CommitUpload). +// - A failed upload rolls back by restoring the revision it created +// (see Decomposedfs.RollbackUpload). +// +// The 'auto' strategy keeps only one revision per 10 seconds in the last minute, +// so with rapid uploads a cleanup inside CreateRevision could delete a revision +// that one of those uploads still needs. Instead, Cleanup does nothing at all +// while the node is marked as processing. +// +// # Running in the background +// +// By default (option revisions_cleanup_async) HandleRevisionCreated only queues the node, and +// background workers run Cleaner.Cleanup, so that the cleanup does not slow down the +// upload, restore or change on disk that triggered it (see Service). This also +// shortens the time the node lock is held by those operations. The number of workers, +// the queue size and what happens when the queue is full (block or drop) are +// configurable (AsyncOptions). With revisions_cleanup_async disabled, HandleRevisionCreated runs the +// cleanup right away, in the caller's goroutine. +// +// # Metrics +// +// The cleanup exports Prometheus metrics (see metrics.go), all named +// reva_revision_cleanup_*: counters of deleted revisions, deleted bytes, failed deletions +// and requests that found the queue full, and gauges of the queue length and capacity, the +// workers, the running cleanups and whether the cleanup is enabled. The queue and worker +// gauges are summed over all Services of the process. +// +// Overlapping uploads: the processing mark of a node only tracks its latest upload, so a +// cleanup triggered by a newer upload runs while an older one may still be in +// postprocessing. The revision the newer upload created for the older one keeps the older +// upload's processing mark, and the older upload writes its content into it when it +// finishes. The cleanup never deletes such a revision, see Cleaner: the older upload would +// then discard its content. Once the older upload has written its content into it and +// removed the mark, the revision is a version, and CommitUpload runs the cleanup for it. +package revisioncleanup + +import ( + "cmp" + "context" + "fmt" + "math" + "slices" + "strconv" + "strings" + "time" + + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + + "github.com/opencloud-eu/reva/v3/pkg/appctx" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" + "github.com/opencloud-eu/reva/v3/pkg/storage/revisions" +) + +// BlobDeleter is the part of node.Tree needed to purge a revision. +type BlobDeleter interface { + DeleteBlob(n *node.Node) error +} + +// RevisionStore is the part of node.Tree needed to clean up revisions. +// It is a separate interface so that the posix tree can pass itself from within +// its own package without the cleanup depending on the full node.Tree. +type RevisionStore interface { + ListRevisions(ctx context.Context, n *node.Node) ([]*provider.FileVersion, error) + BlobDeleter +} + +// SpaceScoper is implemented by trees whose files may only be accessible to the group of their +// space, i.e. posix with use_space_groups. The cleanup runs on behalf of the system, e.g. in +// background workers, so nothing has switched to that group for it, unlike for user requests, +// where the storage driver's middleware does. +type SpaceScoper interface { + // ScopeToSpace switches the current goroutine to the group of the space, and returns a + // context carrying the group, for the goroutines the tree starts itself, e.g. to list a + // folder, and a function that switches back. The goroutine stays on its OS thread until then. + ScopeToSpace(ctx context.Context, spaceID string) (context.Context, func() error, error) +} + +// scopeToSpace switches to the group of the space of n if rs is a SpaceScoper, see there. It +// returns ctx and a no-op otherwise. +// +// A goroutine that switched to the group of the space already doesn't switch again: a worker +// switches before it reads the node, and the Cleaner then runs in the same goroutine. Switching +// costs a stat of the root of the space and two system calls. The context records the space the +// goroutine switched to; it must not be handed to another goroutine that should run in the +// group, which has to switch on its own. +func scopeToSpace(ctx context.Context, rs any, spaceID string) (context.Context, func() error, error) { + noop := func() error { return nil } + scoper, ok := rs.(SpaceScoper) + if !ok { + return ctx, noop, nil + } + if scoped, _ := ctx.Value(scopedToSpaceKey{}).(string); scoped == spaceID { + return ctx, noop, nil + } + ctx, unscope, err := scoper.ScopeToSpace(ctx, spaceID) + if err != nil { + return ctx, nil, err + } + return context.WithValue(ctx, scopedToSpaceKey{}, spaceID), unscope, nil +} + +// scopedToSpaceKey is the context key of the id of the space whose group the current goroutine +// switched to, see scopeToSpace. +type scopedToSpaceKey struct{} + +// PurgeRevisionUnchecked physically removes the revision of n with the given key, including its +// blob, metadata and lockfile, without checking permissions. Callers that act on behalf +// of a user must check permissions themselves. +// +// It works for all decomposedfs based drivers: +// - decomposed, decomposeds3: a revision is the empty node file '.REV.' +// with its metadata and lockfile, plus the blob holding the content, referenced by +// BlobIDAttr in the revision's metadata. +// - posix: a revision is a full copy of the content in the '.oc-nodes' directory of the +// space, with its metadata and lockfile. Revisions created from changes on disk by +// assimilation have the same layout. The posix blobstore does not hold separate blobs, +// its Delete is a no-op. +// +// Node.DeleteRevisionUnchecked removes everything but the blob, under the node's metadata lock +// (which is reentrant, callers may hold it), and returns the blob id, so that the blob can be +// deleted here. It is a no-op for a revision that does not exist (anymore), e.g. when it was purged +// concurrently. +// +// The key is validated first (node.ValidateRevisionKey), as it is turned into the version that +// Node.DeleteRevisionUnchecked expects, and an empty version would make +// Node.DeleteRevisionUnchecked revert or even purge the node itself instead of deleting a revision. +// +// The blob of a revision is never shared with the current version or other revisions: +// every upload gets a new blob id, CreateRevision moves the reference of the previous +// blob to the revision, and RestoreRevision moves it back while removing the revision +// without deleting its blob. So deleting it here cannot affect anything else. +// +// Decomposedfs.deleteRevisionFile, used by the DeleteFileVersions API and the DeleteRevision +// event, does the same without the key validation. It is left as it is for now, using one +// for the other is https://github.com/opencloud-eu/opencloud/issues/3734. +func PurgeRevisionUnchecked(ctx context.Context, bd BlobDeleter, n *node.Node, revisionKey string) error { + blobID, err := removeRevisionUnchecked(ctx, n, revisionKey) + if err != nil { + return err + } + return deleteBlob(bd, n.SpaceID, blobID) +} + +// removeRevisionUnchecked removes the revision of n with the given key, but not its blob, and +// returns the blob id, see PurgeRevisionUnchecked. It checks no permissions. +func removeRevisionUnchecked(ctx context.Context, n *node.Node, revisionKey string) (string, error) { + if err := node.ValidateRevisionKey(n, revisionKey); err != nil { + return "", err + } + return n.DeleteRevisionUnchecked(ctx, strings.TrimPrefix(revisionKey, n.ID+node.RevisionIDDelimiter)) +} + +// deleteBlob deletes the blob of a removed revision. An empty blob id means there is no blob: +// a zero byte revision, or no such revision. +func deleteBlob(bd BlobDeleter, spaceID, blobID string) error { + if blobID == "" { + return nil + } + // DeleteBlob only needs the blob coordinates, not a full node + return bd.DeleteBlob(&node.Node{BaseNode: node.BaseNode{SpaceID: spaceID}, BlobID: blobID}) +} + +// Cleaner deletes old revisions according to a cleanup strategy. +// A disabled Cleaner, created by New without a strategy, never deletes anything; see +// Enabled. A nil *Cleaner behaves the same, as a safeguard, but New never returns one. +// +// It is stateless apart from the parsed strategy and safe for concurrent use. +// The storage drivers use it through a Service, created from their options by +// NewServiceFromOptions and passed on through aspects.Aspects.RevisionsCleanup. +type Cleaner struct { + // nil if the cleanup is disabled + strategy revisions.RevisionCleanupStrategy + // the specification the strategy was parsed from, logged so that support can tell + // which configuration was in effect from the log output alone + config string +} + +// New creates a Cleaner from a strategy specification as understood by +// revisions.NewRevisionCleanupStrategy. An empty or "disabled" specification +// returns a disabled Cleaner. +// +// A disabled Cleaner, rather than nil, lets the call sites call Cleanup unconditionally, +// without the risk of a nil pointer, while it still skips all the work, including taking +// the node lock, when the feature is off, which is the default. +func New(config string) (*Cleaner, error) { + config = strings.TrimSpace(config) + if config == "" || config == "disabled" { + return &Cleaner{config: "disabled"}, nil + } + strategy, err := revisions.NewRevisionCleanupStrategy(config) + if err != nil { + return nil, err + } + return &Cleaner{strategy: strategy, config: config}, nil +} + +// Enabled tells whether c cleans up anything, i.e. whether it was created with a strategy. +// It is false for a disabled Cleaner, and for a nil one. +func (c *Cleaner) Enabled() bool { + return c != nil && c.strategy != nil +} + +// keptAfterRestore is the reason for the revisions a restore keeps, see keptAfterRestoreKeys. +const keptAfterRestore = "protected: holds the content a restore replaced, as long as the file has the restored content" + +// Cleanup deletes the revisions of n that the strategy does not want to keep. +// The revision a restore created of the content it replaced is never deleted as long as the +// file has the restored content, see node.KeepAfterRestoreAttr. +// +// It locks the metadata of n (the lock is reentrant, callers may already hold it) +// and does nothing while an upload to n is still being processed, as that upload +// may still need existing revisions to write its blob into or to roll back to. +// See the package documentation for the details. The blobs of the deleted revisions are +// deleted after the lock is released. If rs is a SpaceScoper, it switches to the group of the +// space of n first. +// +// Errors are logged, and reported in the Result, but not returned: a failed cleanup must +// not fail the operation that triggered it. Callers that don't report on the cleanup can +// ignore the Result. +// +// It checks no permissions: it is housekeeping on behalf of the system, e.g. after async +// postprocessing, where there is no suitable user in the context. Callers decide which nodes +// to clean up. +func (c *Cleaner) Cleanup(ctx context.Context, lu node.PathLookup, rs RevisionStore, n *node.Node) Result { + return c.run(ctx, lu, rs, n, false, true) +} + +// DryRun decides like Cleanup, but deletes nothing: the Result tells which revisions would +// be deleted, kept or protected, and why. It neither counts metrics nor logs purges. +// +// It changes nothing on disk: it doesn't lock n, and reads its metadata under +// metadata.WithReadOnly, so that no lock file is created. Its decisions are a snapshot, which +// an upload to n may change meanwhile. +// +// Like Cleanup, it checks no permissions. +func (c *Cleaner) DryRun(ctx context.Context, lu node.PathLookup, rs RevisionStore, n *node.Node) Result { + return c.run(ctx, lu, rs, n, true, true) +} + +// The result is named, so that the deletion of the blobs, which runs deferred, can report its +// errors in it. Without details, it has no Revisions: the background cleanup has no one to report +// to, and building them, with the reason for every revision, would be wasted on every upload. +func (c *Cleaner) run(ctx context.Context, lu node.PathLookup, rs RevisionStore, n *node.Node, dryRun, details bool) (result Result) { + if !c.Enabled() || n == nil { + return Result{DryRun: dryRun, Skipped: "the revision cleanup is disabled"} + } + result = Result{SpaceID: n.SpaceID, NodeID: n.ID, DryRun: dryRun} + if dryRun { + // also the backends that lock to read must not create lock files + ctx = metadata.WithReadOnly(ctx) + } + log := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() + + ctx, unscope, err := scopeToSpace(ctx, rs, n.SpaceID) + if err != nil { + log.Error().Err(err).Msg("revision cleanup: could not switch to the group of the space") + result.Err = fmt.Errorf("could not switch to the group of the space: %w", err) + return result + } + defer func() { _ = unscope() }() + + // The blobs of the purged revisions are deleted once the node lock is released (this defer + // runs after the one releasing it): their revisions are gone by then, so nothing refers to + // them anymore, and deleting a blob can be slow, e.g. one request per blob with + // decomposeds3, which would block uploads to the node all along. + type pendingBlob struct { + key string // of the revision the blob belonged to + blobID string + size uint64 // of the revision + } + var blobs []pendingBlob + // the blob of the node itself, read under the node lock below + var currentBlobID string + defer func() { + for _, b := range blobs { + if currentBlobID != "" && b.blobID == currentBlobID { + // A revision normally has a blob of its own. Should one ever share the blob of + // the node, deleting it would delete the current content of the file, so it is + // left alone (as CommitUpload does for the revisions it removes). + log.Warn().Str("revision", b.key).Str("blobid", b.blobID).Msg("revision cleanup: not deleting the blob of a purged revision, the file still uses it") + // the revision is deleted all the same, but it freed no space + RevisionsDeleted.Inc() + continue + } + if err := deleteBlob(rs, n.SpaceID, b.blobID); err != nil { + // the revision is gone, but not its blob: that's a failure, not a deletion + PurgeFailures.Inc() + log.Error().Err(err).Str("revision", b.key).Str("blobid", b.blobID).Msg("revision cleanup: could not delete the blob of a purged revision") + for i := range result.Revisions { + if result.Revisions[i].Key == b.key { + result.Revisions[i].Err = fmt.Errorf("the revision was deleted, but not its blob %q: %w", b.blobID, err) + } + } + continue + } + RevisionsDeleted.Inc() + BytesDeleted.Add(float64(b.size)) + } + }() + + // Holding the node lock serializes the cleanup with uploads to the same node: + // those create revisions and mark the node as processing while holding it, so + // the processing check below cannot race with a new upload starting. + // Revisions have their own lockfiles, purging them while holding the node lock + // does not deadlock. + // A dry run doesn't take the lock: it must not change anything on disk, and locking + // creates the lock file of the node when there is none yet. Its decisions are a + // snapshot, which an upload to the node may change meanwhile; a real cleanup decides + // again, under the lock. + if !dryRun { + unlock, err := lu.MetadataBackend().Lock(n) + if err != nil { + log.Error().Err(err).Msg("revision cleanup: could not lock node") + result.Err = fmt.Errorf("could not lock node: %w", err) + return result + } + defer func() { _ = unlock() }() + } + + // Read the status and the blob id from storage, under the lock (but in a dry run), + // and neither via n.IsProcessing() nor from the cache of the backend: + // - n caches its attributes, and after an upload the processing flag is removed + // through a different *node.Node instance (Decomposedfs.MarkProcessing), so the + // cache of n would still say "processing" and the cleanup would never run; + // - the cache of the backend may be local to the process, and an on-demand cleanup + // runs in a process of its own next to the server: when it cached the node + // earlier, e.g. while listing the folder, it would miss an upload the server + // started since then, and delete the revision the upload has to roll back to. + attribs, err := lu.MetadataBackend().Reload(ctx, n) + if err != nil { + log.Error().Err(err).Msg("revision cleanup: could not read node status") + result.Err = fmt.Errorf("could not read node status: %w", err) + return result + } + if strings.HasPrefix(string(attribs[prefixes.StatusPrefix]), node.ProcessingStatus) { + log.Debug().Msg("revision cleanup: node is processing, skipping") + result.Skipped = "an upload to the file is still being processed" + return result + } + if blobID, ok := attribs[prefixes.BlobIDAttr]; ok { + currentBlobID = string(blobID) + } + now := time.Now() + // when the node got its current content, for the estimate in revisionTimes + fileMTime, err := node.Attributes(attribs).Time(prefixes.MTimeAttr) + if err != nil { + fileMTime = now + } + + versions, err := rs.ListRevisions(ctx, n) + if err != nil { + log.Error().Err(err).Msg("revision cleanup: could not list revisions") + result.Err = fmt.Errorf("could not list revisions: %w", err) + return result + } + times := revisionTimes(ctx, lu, n, versions, fileMTime, now) + // The strategy only sees versions: the revisions that are not are neither deleted nor + // counted, see notAVersion. + versions, skipped := splitOffNotVersions(ctx, lu, n, versions) + for _, sk := range skipped { + log.Debug().Str("revision", sk.version.Key).Str("reason", sk.reason).Msg("revision cleanup: leaving a revision alone that is not a version") + } + if len(versions) == 0 { + if details { + result.Revisions = revisionResults(nil, nil, nil, nil, skipped, times) + } + return result + } + keep := keptAfterRestoreKeys(ctx, lu, n, versions, currentBlobID, dryRun) + + revs := make([]revisions.Revision, len(versions)) + for i, v := range versions { + revs[i] = fileVersionRevision{version: v, created: times[v.Key]} + } + + // All revisions, including the ones in keep, are handed to the strategy, as + // count based strategies ("keep the n newest") need to see the complete set to + // decide correctly. keep is only applied to the strategy's deletion plan. + purgeErrs := map[string]error{} + purged := 0 + var purgedBytes uint64 + plan, err := revisions.ExecuteCleanupStrategy(now, c.strategy, revs, ctx, &log, func(rev revisions.Revision, reason string) error { + if dryRun || slices.Contains(keep, rev.Key()) { + return nil + } + blobID, err := removeRevisionUnchecked(ctx, n, rev.Key()) + if err != nil { + PurgeFailures.Inc() + purgeErrs[rev.Key()] = err + return fmt.Errorf("could not purge revision %q: %w", rev.Key(), err) + } + blobs = append(blobs, pendingBlob{key: rev.Key(), blobID: blobID, size: rev.Size()}) + purged++ + purgedBytes += rev.Size() + // the reason explains which rule deleted the revision, e.g. which slot of the 'auto' + // strategy, see revisions.Plan + log.Debug().Str("revision", rev.Key()).Uint64("size", rev.Size()).Str("reason", reason).Msg("revision cleanup: purged revision") + return nil + }) + if plan == nil { + // the strategy itself failed + log.Error().Err(err).Msg("revision cleanup: failed") + result.Err = err + return result + } + if details { + result.Revisions = revisionResults(revs, plan, keep, purgeErrs, skipped, times) + } + + // One summary per node at info level, so that admins can see the cleanup at work + // without the per revision debug logging. Nothing is logged when nothing was purged, + // which is the common case for nodes with few revisions. + if purged > 0 { + log.Info().Str("config", c.config).Int("purged", purged).Uint64("purgedbytes", purgedBytes). + Int("revisions", len(versions)).Msg("revision cleanup: purged old revisions") + } + if err != nil { + // a revision that could not be purged is still listed and will be retried + // by the next cleanup of this node + log.Error().Err(err).Msg("revision cleanup: failed") + } + return result +} + +// revisionResults turns the plan of the strategy into one RevisionResult per revision, in the +// order of revs (newest first), together with the revisions that were skipped as they are not +// versions (reported as protected). plan is nil if the strategy didn't run. times are the times of +// the revisions, see revisionTimes. +func revisionResults(revs []revisions.Revision, plan revisions.Plan, keep []string, purgeErrs map[string]error, skipped []skippedRevision, times map[string]time.Time) []RevisionResult { + decisions := map[string]Decision{} + reasons := map[string]string{} + if plan != nil { + for _, rev := range plan.Deleted() { + decisions[rev.Key()] = Deleted + } + for _, rev := range plan.Retained() { + decisions[rev.Key()] = Kept + } + for _, rev := range plan.Safeguarded() { + decisions[rev.Key()] = Protected + } + for _, rev := range revs { + reasons[rev.Key()] = plan.Reason(rev.Key()) + } + } + + sorted := slices.Clone(revs) + for _, sk := range skipped { + sorted = append(sorted, fileVersionRevision{version: sk.version, created: times[sk.version.Key]}) + decisions[sk.version.Key] = Protected + reasons[sk.version.Key] = "protected: " + sk.reason + } + revisions.SortRevisionsCanonically(sorted) + results := make([]RevisionResult, 0, len(sorted)) + for _, rev := range sorted { + r := RevisionResult{ + Key: rev.Key(), + Time: rev.CreationTime(), + Size: rev.Size(), + Decision: decisions[rev.Key()], + Reason: reasons[rev.Key()], + Err: purgeErrs[rev.Key()], + } + if r.Decision == Deleted && slices.Contains(keep, rev.Key()) { + r.Decision = Protected + r.Reason = keptAfterRestore + } + results = append(results, r) + } + return results +} + +// keptAfterRestoreKeys returns the keys of the versions of n that a restore keeps: the ones +// marked with node.KeepAfterRestoreAttr, as long as n still has the content the restore put in +// place, i.e. while its blob id is the value of the mark. The next upload or restore of n, or a +// change on disk with posix, gives n a new blob id: from then on such a revision is a version +// like any other, and the mark is removed, but in a dry run, which changes nothing. +// +// The mark is on disk rather than in the request for the cleanup, so that it holds also when +// the request is dropped or merged with another, for a cleanup by another instance of the +// driver in the same process, and for a cleanup on demand in a process of its own. +func keptAfterRestoreKeys(ctx context.Context, lu node.PathLookup, n *node.Node, versions []*provider.FileVersion, currentBlobID string, dryRun bool) []string { + backend := lu.MetadataBackend() + var keep []string + for _, v := range versions { + revision := node.NewBaseNode(n.SpaceID, v.Key, lu) + restoredBlobID, err := backend.Get(ctx, revision, node.KeepAfterRestoreAttr) + if err != nil { + continue + } + if currentBlobID != "" && string(restoredBlobID) == currentBlobID { + keep = append(keep, v.Key) + continue + } + if dryRun { + continue + } + if err := backend.Remove(ctx, revision, node.KeepAfterRestoreAttr); err != nil && !metadata.IsAttrUnset(err) { + appctx.GetLogger(ctx).Warn().Err(err).Str("revision", v.Key).Msg("revision cleanup: could not remove the mark of a restore that the file no longer has") + } + } + return keep +} + +// skippedRevision is a revision the cleanup leaves alone, see notAVersion. +type skippedRevision struct { + version *provider.FileVersion + reason string +} + +// splitOffNotVersions splits the revisions of n that are not versions (see notAVersion) off +// the given ones. +func splitOffNotVersions(ctx context.Context, lu node.PathLookup, n *node.Node, all []*provider.FileVersion) ([]*provider.FileVersion, []skippedRevision) { + versions := make([]*provider.FileVersion, 0, len(all)) + var skipped []skippedRevision + for _, v := range all { + if reason := notAVersion(ctx, lu.MetadataBackend(), node.NewBaseNode(n.SpaceID, v.Key, lu)); reason != "" { + skipped = append(skipped, skippedRevision{version: v, reason: reason}) + continue + } + versions = append(versions, v) + } + return versions, skipped +} + +// notAVersion explains why a revision is not a version, or returns "" if it is one. +// +// The upload coordinator (pkg/upload) keeps revisions for uploads in flight that are not +// versions: +// +// - a revision that keeps the processing mark of an older upload, which a newer upload +// superseded while the older one was still in postprocessing: the older upload writes +// its content into it when it finishes (Decomposedfs.CommitUpload), and discards its +// content if the revision is gone, +// - a revision kept only to roll back an upload (node.KeptForRollback), which the upload +// coordinator removes itself. +// +// The cleanup leaves them alone and doesn't count them. Usually the node itself is marked as +// processing while such revisions exist, and the cleanup skips it altogether, but not always: +// an upload that the coordinator finishes right away, e.g. of an empty file, clears the mark +// of the node while an older upload may still be in postprocessing. +func notAVersion(ctx context.Context, backend metadata.Backend, revision metadata.MetadataNode) string { + if status, err := backend.Get(ctx, revision, prefixes.StatusPrefix); err == nil && strings.HasPrefix(string(status), node.ProcessingStatus) { + return uploadInProgress + } + if node.KeptForRollback(ctx, backend, revision) { + return keptForRollback + } + return "" +} + +const ( + // the reasons for leaving a revision alone, see notAVersion + uploadInProgress = "an upload into this revision is still being processed" + keptForRollback = "kept only to roll back an upload, it is not a version" +) + +// revisionTimes returns the time each of the given revisions of n was created, by key: the time +// the cleanup orders them by and measures their age from. +// +// It is the time recorded in node.RevisionCreatedAttr, i.e. when the content the revision holds +// was replaced, by the clock of the server. The name of a revision is no good for this: it is +// the modification time of its content (see contentTime), which whoever writes the file can +// choose, e.g. with X-OC-Mtime. A revision dated just after an existing one would push that one +// out of its slot of "auto", and revisions dated years ahead would take the places of a number +// of revisions to keep, e.g. of "5, 30d", so that every new version would be deleted, for as +// long as they exist. +// +// Revisions created before the attribute was introduced don't have it. Their time is estimated +// as the time they were replaced: the content time of the next newer revision, or fileMTime, +// the modification time of the file, for the newest one, but never later than now. These come +// from the client as well, but they only apply to the revisions that exist already, and +// capping them at now keeps revisions dated in the future from taking the places of the ones +// created from now on. +// +// That the age of a revision is the time it was replaced, rather than the time its content was +// written, is what https://github.com/opencloud-eu/opencloud/issues/3735 is about. +func revisionTimes(ctx context.Context, lu node.PathLookup, n *node.Node, all []*provider.FileVersion, fileMTime, now time.Time) map[string]time.Time { + backend := lu.MetadataBackend() + byContent := slices.Clone(all) + slices.SortStableFunc(byContent, compareContentTime) + times := make(map[string]time.Time, len(all)) + for i, v := range byContent { + if t, err := node.RevisionCreated(ctx, backend, node.NewBaseNode(n.SpaceID, v.Key, lu)); err == nil { + times[v.Key] = t + continue + } + estimate := fileMTime + if i+1 < len(byContent) { + estimate, _ = contentTime(byContent[i+1]) + } + if estimate.After(now) { + estimate = now + } + times[v.Key] = estimate + } + return times +} + +// contentTime determines when the content of a revision was last modified from the timestamp +// in its key, '.REV.' with an optional '.' suffix for colliding +// revisions, which is returned as well (0 without one). The mtime of the revision file is used +// as a fallback. +// +// Revisions are named after the mtime of the content they preserve (see +// Decomposedfs.PrepareUpload, the posix assimilation and RestoreRevision). For changes on disk +// with posix, the name is the time the content was copied to '.CURRENT', when that change was +// picked up, normally right after the content was written (see the posix assimilation). +// +// The key is preferred over the file mtime because the file mtime is not reliable: +// the upload code only sets it to the mtime of the old content (os.Chtimes in +// Decomposedfs.PrepareUpload) after CreateRevision has returned, and the +// FileVersion.Mtime from ListRevisions has only a precision of seconds. +func contentTime(v *provider.FileVersion) (time.Time, int) { + if _, ts, ok := strings.Cut(v.Key, node.RevisionIDDelimiter); ok { + if t, err := time.Parse(time.RFC3339Nano, ts); err == nil { + return t, 0 + } + if i := strings.LastIndex(ts, "."); i > 0 { + if t, err := time.Parse(time.RFC3339Nano, ts[:i]); err == nil { + suffix, _ := strconv.Atoi(ts[i+1:]) + return t, suffix + } + } + } + return time.Unix(int64(v.Mtime), 0), 0 +} + +// compareContentTime orders revisions by their content time, oldest first. Of colliding +// revisions, the one with the key without a suffix is the newest: CreateRevision renames the +// existing one to the next free suffix, and gives the new one the key without a suffix. +func compareContentTime(a, b *provider.FileVersion) int { + ta, sa := contentTime(a) + tb, sb := contentTime(b) + if c := ta.Compare(tb); c != 0 { + return c + } + if sa == 0 { + sa = math.MaxInt + } + if sb == 0 { + sb = math.MaxInt + } + return cmp.Compare(sa, sb) +} + +// fileVersionRevision adapts a CS3 FileVersion, as returned by +// node.Tree.ListRevisions, to the revisions.Revision interface the +// cleanup strategies work on. +type fileVersionRevision struct { + version *provider.FileVersion + created time.Time // see revisionTimes +} + +var _ revisions.Revision = fileVersionRevision{} + +func (f fileVersionRevision) Key() string { return f.version.Key } +func (f fileVersionRevision) CreationTime() time.Time { return f.created } +func (f fileVersionRevision) Size() uint64 { return f.version.Size } diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/metrics.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/metrics.go new file mode 100644 index 0000000000..b9caf099e7 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/metrics.go @@ -0,0 +1,123 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisioncleanup + +import ( + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" +) + +// Prometheus metrics of the revision cleanup, e.g. for Grafana dashboards. +// +// They are registered once per process, at package level: a process can create several +// storage drivers, and with them several Services (e.g. the storageprovider and the +// dataprovider each create their own driver), and registering a metric twice panics. +// The gauges describing the queue and the workers are therefore the sum over all Services of +// the process: each Service adds its share when it starts and removes it when it shuts down. +// As a sum can hide one queue being full while another one is empty, QueueFull counts every +// request that found its queue full, which is the most direct sign that the number of workers +// or the queue size is too small. +var ( + // RevisionsDeleted counts the revisions deleted by the cleanup. + RevisionsDeleted = promauto.NewCounter(prometheus.CounterOpts{ + Name: "reva_revision_cleanup_revisions_deleted_total", + Help: "Number of old file revisions deleted by the revision cleanup", + }) + + // BytesDeleted counts the size of the revisions deleted by the cleanup. + BytesDeleted = promauto.NewCounter(prometheus.CounterOpts{ + Name: "reva_revision_cleanup_bytes_deleted_total", + Help: "Total size in bytes of the old file revisions deleted by the revision cleanup", + }) + + // PurgeFailures counts the revisions that could not be deleted. They are retried by the + // next cleanup of their node, i.e. when the node gets its next revision. + PurgeFailures = promauto.NewCounter(prometheus.CounterOpts{ + Name: "reva_revision_cleanup_purge_failures_total", + Help: "Number of old file revisions the revision cleanup failed to delete, completely or only their blob", + }) + + // QueueFull counts the cleanup requests that found the queue full, by outcome: "blocked" + // (the caller waited for room, queue full policy "block") or "dropped" (the cleanup was + // skipped until the node's next revision, queue full policy "drop"). A caller that waited + // in vain until the timeout of "block" counts as both: blocked when it starts to wait, and + // dropped when it gives up. + QueueFull = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_revision_cleanup_queue_full_total", + Help: "Number of revision cleanup requests that found the queue full, by outcome (blocked or dropped)", + }, []string{"outcome"}) + + // QueueLength is the number of nodes waiting for a background cleanup, including the + // ones whose callers wait for room in a full queue. A node waits at most once (requests + // are de-duplicated per node), how many of its revisions get deleted is only known once a + // worker processes it. + QueueLength = promauto.NewGauge(prometheus.GaugeOpts{ + Name: "reva_revision_cleanup_queue_length", + Help: "Number of files waiting for a background revision cleanup, summed over all queues of the process", + }) + + // QueueCapacity is the size of the background cleanup queues. + QueueCapacity = promauto.NewGauge(prometheus.GaugeOpts{ + Name: "reva_revision_cleanup_queue_capacity", + Help: "Number of files that can wait for a background revision cleanup, summed over all queues of the process", + }) + + // Workers is the number of background cleanup workers, 0 when the cleanup runs synchronously. + Workers = promauto.NewGauge(prometheus.GaugeOpts{ + Name: "reva_revision_cleanup_workers", + Help: "Number of background revision cleanup workers, summed over all queues of the process", + }) + + // Running is the number of nodes being cleaned up by background workers right now. + Running = promauto.NewGauge(prometheus.GaugeOpts{ + Name: "reva_revision_cleanup_running", + Help: "Number of files whose revisions are being cleaned up by background workers right now", + }) + + // Enabled is 1 if a revision cleanup strategy is configured, 0 otherwise. + Enabled = promauto.NewGauge(prometheus.GaugeOpts{ + Name: "reva_revision_cleanup_enabled", + Help: "Whether the revision cleanup is enabled (1) or not (0)", + }) +) + +// labels of QueueFull +const ( + queueFullBlocked = "blocked" + queueFullDropped = "dropped" +) + +// serviceMetrics are the metrics a Service updates about itself: its configuration, its queue +// and its workers. +type serviceMetrics struct { + enabled, workers, queueCapacity, queueLength, running prometheus.Gauge + queueFull *prometheus.CounterVec +} + +// driverMetrics are the exported metrics, updated by the Services of the storage drivers. +var driverMetrics = serviceMetrics{ + enabled: Enabled, + workers: Workers, + queueCapacity: QueueCapacity, + queueLength: QueueLength, + running: Running, + queueFull: QueueFull, +} + +// unregisteredMetrics returns metrics that are not registered, for the Service of an on-demand +// Run: the exported ones describe the cleanup of the storage driver, which a run of its own, +// with its own queue and workers, must not distort, should it ever run in the same process. +// The deletions of a run are counted all the same (RevisionsDeleted, BytesDeleted and +// PurgeFailures), as the Cleaner counts them. +func unregisteredMetrics() *serviceMetrics { + gauge := func() prometheus.Gauge { return prometheus.NewGauge(prometheus.GaugeOpts{Name: "unregistered"}) } + return &serviceMetrics{ + enabled: gauge(), + workers: gauge(), + queueCapacity: gauge(), + queueLength: gauge(), + running: gauge(), + queueFull: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "unregistered"}, []string{"outcome"}), + } +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/ondemand.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/ondemand.go new file mode 100644 index 0000000000..de1278753e --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/ondemand.go @@ -0,0 +1,266 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisioncleanup + +import ( + "context" + "errors" + "fmt" + "math/rand/v2" + "path" + "sync" + + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + "github.com/rs/zerolog" + + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" +) + +// Request describes an on-demand cleanup of revisions, e.g. by a command line tool, as opposed +// to the cleanup that runs whenever a file gets a new revision. +// +// The strategy and the AsyncOptions default to the configuration of the storage driver, and +// can be overridden for this run. Without AsyncOptions of its own, though, a run waits for +// room in a full queue for as long as it takes (QueueFullBlock without a timeout), whatever +// the queue full policy of the storage driver: a run queues the files as fast as it finds +// them, so dropping them whenever the queue is full would skip most of them. +type Request struct { + // SpaceIDs are the spaces to clean up. Exactly one of SpaceIDs, All and FSPath must be given. + SpaceIDs []string + // All cleans up all spaces. + All bool + // Path narrows the cleanup down to a file or a folder (recursively) within the space, + // relative to the space root. It requires exactly one space in SpaceIDs. + Path string + // FSPath is a file or folder (recursively) given by its path on disk, as an admin sees it. + // Only drivers that keep files under their own names on disk support it, i.e. posix, which + // resolves it to the space and the path within it. + FSPath string + + // Strategy overrides the configured revisions cleanup strategy for this run, see + // revisions.NewRevisionCleanupStrategy. + Strategy string + // Async overrides the configured AsyncOptions for this run. Without it, the configured + // ones are used, but with QueueFullBlock and no timeout. + Async *AsyncOptions + // DryRun only decides which revisions would be deleted, without deleting anything. + DryRun bool + // Shuffle cleans up the spaces, and the files and folders within each folder, in a random + // order instead of the same order every time. A run that is stopped early through its + // context (e.g. by a timeout) starts over from the beginning the next time; shuffled, + // repeated runs start in different places, and eventually reach all files, also within a + // space that is too large for a single run. + Shuffle bool +} + +// Validate checks the scope of the request. +func (r Request) Validate() error { + switch { + case r.FSPath != "" && (r.All || len(r.SpaceIDs) > 0 || r.Path != ""): + return errors.New("a path on disk can't be combined with spaces or a path within a space") + case r.FSPath != "": + return nil + case r.All && len(r.SpaceIDs) > 0: + return errors.New("either all spaces or specific spaces can be cleaned up, not both") + case !r.All && len(r.SpaceIDs) == 0: + return errors.New("no space to clean up given") + case r.Path != "" && len(r.SpaceIDs) != 1: + return errors.New("a path requires exactly one space") + } + return nil +} + +// OnDemand is implemented by the storage drivers that can clean up revisions on demand. +// +// CleanupRevisionsUnchecked cleans up the revisions of all files within the scope of the request +// and hands the Result of every file to report, one at a time, including the files that were +// skipped. It returns once all cleanups are done. It returns an error if the request is invalid or +// the cleanup could not be run; errors with single files are only reported. +// +// The end of ctx, e.g. a timeout, stops the cleanup gracefully: the files being cleaned up +// are finished, and the files already queued are reported as skipped. It then returns ctx's +// error. +type OnDemand interface { + CleanupRevisionsUnchecked(ctx context.Context, req Request, report func(Result)) error +} + +// Walker is the part of a tree needed to clean up the revisions of whole folders or spaces. +type Walker interface { + RevisionStore + // ListFolderKnownUnchecked lists the children of a folder that are known to the storage, for + // maintenance. Unlike ListFolder: + // - it checks no permissions, so it needs no user in the context, and it also lists the + // files and folders that are denied to users; + // - it lists only the known children, the files and folders the storage has registered + // with a node id, and never assimilates (registers) unknown ones, which exist on disk + // but are not registered yet. Only posix has unknown files today, as files can be + // created on disk directly; in the other trees, every child is known. + // So it changes nothing, and a cleanup, a dry run in particular, changes nothing but the + // revisions it deletes. Unknown files have no revisions the storage knows of anyway, and a + // later run covers them once they are registered. + ListFolderKnownUnchecked(ctx context.Context, n *node.Node) ([]*node.Node, error) +} + +// RunOptions are the settings of an on-demand Run. +type RunOptions struct { + // Async are the AsyncOptions of the run's own Service. + Async AsyncOptions + // DryRun only decides which revisions would be deleted, without deleting anything. + DryRun bool + // Shuffle walks the files and folders within each folder in a random order, see + // Request.Shuffle. The order of the roots is the caller's. + Shuffle bool +} + +// Run cleans up the revisions of the given roots, files or folders (recursively, e.g. space roots), +// with the given Cleaner and RunOptions, and hands the Result of every file to report, one at a +// time. It is the common implementation of OnDemand.CleanupRevisionsUnchecked for the storage +// drivers. +// +// It uses a Service of its own, independent of the storage driver's, so that the Cleaner and +// the AsyncOptions of the run apply: files are queued as they are found, while the workers +// already clean up, and Run waits for all cleanups before it returns. Files dropped by a full +// queue (queue full policy "drop") are reported as skipped. That Service leaves the metrics +// of the storage driver's queue and workers alone; the deleted revisions are counted. +// +// It returns an error if a cleanup could not be run at all, or ctx's error if it ends. Errors +// with single files or folders are only reported. When ctx ends, Run stops gracefully: it +// finishes the cleanups that are running, reports the files that are still queued as skipped, +// and doesn't look at the remaining ones. +// +// It checks no permissions: the Walker lists folders without them, and neither do the +// cleanups. +func Run(ctx context.Context, lu node.PathLookup, w Walker, roots []*node.Node, cleaner *Cleaner, o RunOptions, report func(Result), log *zerolog.Logger) error { + if !cleaner.Enabled() { + return errors.New("no revisions cleanup strategy configured or given") + } + if report == nil { + report = func(Result) {} + } + // the workers report concurrently, report gets the results one at a time + var reportMu sync.Mutex + // the paths of the files queued by the walk, until their results are reported: the walk + // knows them for free, while looking them up for every result would read all the parents + paths := map[string]*queuedPath{} + serialized := func(result Result) { + reportMu.Lock() + defer reportMu.Unlock() + key := result.SpaceID + "/" + result.NodeID + if p, ok := paths[key]; ok { + if result.Path == "" { + result.Path = p.path + } + if p.count--; p.count <= 0 { + delete(paths, key) + } + } + report(result) + } + remember := func(n *node.Node, path string) { + reportMu.Lock() + defer reportMu.Unlock() + key := n.SpaceID + "/" + n.ID + if p, ok := paths[key]; ok { + p.count++ // the same file in more than one root + return + } + paths[key] = &queuedPath{path: path, count: 1} + } + + s, err := newService(cleaner, lu, w, o.Async, log, true, o.DryRun, serialized) + if err != nil { + return err + } + // stop the workers also when ctx ended; they are idle by then unless ctx ended + defer func() { _ = s.Shutdown(context.WithoutCancel(ctx)) }() + + for _, root := range roots { + if err := walkScoped(ctx, lu, w, root, s, o, serialized, remember); err != nil { + return err + } + } + return s.Wait(ctx) +} + +// walkScoped walks root, see walk, switched to the group of its space if w is a SpaceScoper, +// so that the folders can be listed, see SpaceScoper. A space whose group can't be switched to +// is reported and left out. +func walkScoped(ctx context.Context, lu node.PathLookup, w Walker, root *node.Node, s *Service, o RunOptions, report func(Result), remember func(n *node.Node, path string)) error { + ctx, unscope, err := scopeToSpace(ctx, w, root.SpaceID) + if err != nil { + report(Result{SpaceID: root.SpaceID, NodeID: root.ID, DryRun: o.DryRun, Err: fmt.Errorf("could not switch to the group of the space: %w", err)}) + return nil + } + defer func() { _ = unscope() }() + return walk(ctx, w, root, rootPath(ctx, lu, root), s, o, report, remember) +} + +// queuedPath is the path of a queued file, see Run +type queuedPath struct { + path string + count int +} + +// rootPath returns the path of root within its space, "/" for the space root, or "" if it +// can't be determined. +func rootPath(ctx context.Context, lu node.PathLookup, root *node.Node) string { + if root.SpaceRoot == nil { + return "" + } + p, err := lu.Path(ctx, root, node.NoCheck) + if err != nil { + return "" + } + return p +} + +// walk queues the cleanup of n, if it is a file, or of all files below it, if it is a folder. +// rootPath is the path of n within its space, the paths of the files below it are derived +// from it and handed to remember before they are queued. +func walk(ctx context.Context, w Walker, n *node.Node, rootPath string, s *Service, o RunOptions, report func(Result), remember func(n *node.Node, path string)) error { + type entry struct { + n *node.Node + path string + } + stack := []entry{{n: n, path: rootPath}} + for len(stack) > 0 { + if err := ctx.Err(); err != nil { + return err + } + current := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + switch current.n.Type(ctx) { + case provider.ResourceType_RESOURCE_TYPE_FILE: + remember(current.n, current.path) + s.HandleRevisionCreated(ctx, current.n) + case provider.ResourceType_RESOURCE_TYPE_CONTAINER: + children, err := w.ListFolderKnownUnchecked(ctx, current.n) + if err != nil && ctx.Err() != nil { + return ctx.Err() // stopped while listing, not an error of the folder + } + if err != nil { + report(Result{SpaceID: current.n.SpaceID, NodeID: current.n.ID, Path: current.path, DryRun: o.DryRun, Err: fmt.Errorf("could not list the folder at %q: %w", current.n.InternalPath(), err)}) + continue + } + // The second part of Request.Shuffle, after the order of the spaces (see + // Decomposedfs.CleanupRevisionsUnchecked): the order of the children of this folder, + // files and folders alike. As the walk takes them from a stack, depth first, this also + // changes the order in which the subfolders are walked through. + if o.Shuffle { + rand.Shuffle(len(children), func(i, j int) { children[i], children[j] = children[j], children[i] }) + } + for _, child := range children { + childPath := "" + if current.path != "" { + childPath = path.Join(current.path, child.Name) + } + stack = append(stack, entry{n: child, path: childPath}) + } + default: + // references, symlinks and the like have no revisions + } + } + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/result.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/result.go new file mode 100644 index 0000000000..7f7c0db28f --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/result.go @@ -0,0 +1,66 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisioncleanup + +import "time" + +// Decision is what the cleanup decided about a revision. +type Decision string + +const ( + // Deleted revisions are deleted by the strategy (or would be, in a dry run). + Deleted Decision = "deleted" + // Kept revisions are not deleted by the strategy, but not protected either: a later + // cleanup may delete them as they get older. + Kept Decision = "kept" + // Protected revisions are safeguarded by the strategy, or were requested to be kept by + // the operation that triggered the cleanup (e.g. the state from before a restore). + Protected Decision = "protected" +) + +// RevisionResult is the outcome of a cleanup for one revision. +type RevisionResult struct { + Key string + // Time is the time the revision was created, which the cleanup orders the revisions by and + // takes their age from, see revisionTimes. + Time time.Time + Size uint64 + // Decision and Reason explain what the strategy decided and why, see revisions.Plan. + Decision Decision + Reason string + // Err is set when deleting a revision failed. + Err error +} + +// Result is the outcome of a cleanup for one node, with an entry for each of its revisions, +// newest first. It is used to report on a cleanup, e.g. in the verbose output of a command. +type Result struct { + SpaceID string + NodeID string + // Path is the path of the file (or folder) within its space, e.g. "/Documents/report.odt". + // Only on-demand runs (Run) set it, from the folders they walk through; it is empty when + // the path is not known, e.g. for a space that could not be cleaned up. + Path string + // DryRun is set when nothing was deleted, only decided. + DryRun bool + // Skipped explains why the node was not cleaned up, e.g. because an upload to it is still + // being processed. Revisions is empty then. + Skipped string + // Err is set when the cleanup failed as a whole, e.g. when the revisions could not be + // listed. Errors of single revisions are in Revisions. + Err error + Revisions []RevisionResult +} + +// DeletedCount returns the number and the total size of the revisions that were deleted +// (or would be, in a dry run), not counting the ones whose deletion failed. +func (r Result) DeletedCount() (count int, bytes uint64) { + for _, rev := range r.Revisions { + if rev.Decision == Deleted && rev.Err == nil { + count++ + bytes += rev.Size + } + } + return count, bytes +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/service.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/service.go new file mode 100644 index 0000000000..b60e0575be --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/service.go @@ -0,0 +1,698 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisioncleanup + +import ( + "context" + "fmt" + "runtime" + "slices" + "strings" + "sync" + "time" + + "github.com/rs/zerolog" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" + + "github.com/opencloud-eu/reva/v3/pkg/appctx" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options" +) + +var tracer = otel.Tracer("github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup") + +// QueueFullPolicy defines what happens when a cleanup is scheduled while the queue is full. +type QueueFullPolicy string + +const ( + // QueueFullBlock makes the caller wait until there is room in the queue, so that no + // cleanup is ever skipped, at the cost of slowing down writes under heavy load. + QueueFullBlock QueueFullPolicy = "block" + // QueueFullDrop skips the cleanup and logs it, so that writes never wait for the + // cleanup. The node is cleaned up again when it gets its next revision. + QueueFullDrop QueueFullPolicy = "drop" +) + +// queueSizePerWorker is the number of queue slots per worker when the queue size is +// determined automatically. +const queueSizePerWorker = 64 + +// AsyncOptions configures how a Service runs the cleanup. They are passed as +// parameters rather than read from the driver options, so that other callers, like a +// command line tool, can use their own settings. +type AsyncOptions struct { + // Enabled runs the cleanup in background workers. Otherwise HandleRevisionCreated runs it + // right away, in the caller's goroutine. + Enabled bool + // Workers is the number of background workers, 0 determines it automatically: + // half the available CPUs, but at least 2. + Workers int + // QueueSize is the number of nodes that can wait for a cleanup, 0 determines it + // automatically from the number of workers. + QueueSize int + // QueueFull is the policy when the queue is full, "" means QueueFullDrop. + QueueFull QueueFullPolicy + // QueueFullTimeout bounds how long QueueFullBlock waits for room in a full queue: after + // that, the cleanup of the node is skipped, as with QueueFullDrop. 0 waits as long as it + // takes. + QueueFullTimeout time.Duration +} + +// resolve validates the options and determines the automatic values. +func (o AsyncOptions) resolve() (workers int, queueSize int, policy QueueFullPolicy, err error) { + switch { + case o.Workers < 0: + return 0, 0, "", fmt.Errorf("invalid number of revision cleanup workers %d", o.Workers) + case o.Workers == 0: + // GOMAXPROCS rather than NumCPU, as it respects container CPU limits (cgroups) + workers = max(2, runtime.GOMAXPROCS(0)/2) + default: + workers = o.Workers + } + + switch { + case o.QueueSize < 0: + return 0, 0, "", fmt.Errorf("invalid revision cleanup queue size %d", o.QueueSize) + case o.QueueSize == 0: + queueSize = workers * queueSizePerWorker + default: + queueSize = o.QueueSize + } + + if o.QueueFullTimeout < 0 { + return 0, 0, "", fmt.Errorf("invalid revision cleanup queue full timeout %s", o.QueueFullTimeout) + } + + switch o.QueueFull { + case "": + policy = QueueFullDrop + case QueueFullBlock, QueueFullDrop: + policy = o.QueueFull + default: + return 0, 0, "", fmt.Errorf("invalid revision cleanup queue full policy %q, must be %q or %q", o.QueueFull, QueueFullBlock, QueueFullDrop) + } + return workers, queueSize, policy, nil +} + +// Service is the revision cleanup of a storage driver. Callers report that a new revision +// was created (HandleRevisionCreated), and the Service decides whether, when and how the +// old revisions are cleaned up; callers don't need to know whether that happens right away +// or in background workers (see AsyncOptions). It binds a Cleaner to the driver's lookup +// and tree, so that callers only need to name the node. +// A disabled Service, created without a strategy, never cleans up anything; see Enabled. +// A nil *Service behaves the same, as a safeguard, but NewService never returns one. +// +// In asynchronous mode, the cleanup runs in background workers fed by a bounded queue, so +// that it doesn't slow down the upload, restore or change on disk that created the new +// revision. Queued requests only carry the space and node id, and the worker reads the +// node again: a *node.Node must not be shared between goroutines, as its lock-held flag is +// per goroutine and its cached attributes go stale. +// +// Requests are de-duplicated per node: a node that is already waiting in the queue is not +// queued again. A node whose cleanup is already running is not queued either, as another +// worker would only wait for the node lock: when that cleanup is done, the node is queued +// once more, at the end of the queue, as new revisions may have been created in the meantime. +// A node therefore never occupies more than +// one worker, and a single busy file can't keep the workers from the others. +type Service struct { + cleaner *Cleaner + lu node.PathLookup + rs RevisionStore + log *zerolog.Logger + + // set for the Service of an on-demand Run: only decide, don't delete, and hand the Result + // of every cleanup to report + dryRun bool + report func(Result) + // the metrics this Service updates, see m + metrics *serviceMetrics + // set for the Service of an on-demand Run: it leaves the metrics of the storage driver's + // Service alone (see unregisteredMetrics), and it can be stopped through the caller's + // context: a caller blocked on a full queue gives up when its context ends, and a cleanup + // in synchronous mode always finishes its file, see HandleRevisionCreated + onDemand bool + // the bookkeeping of a Service shared by the instances of a storage, nil if it isn't + // shared, see shared + share *share + + async bool + policy QueueFullPolicy + process func(ctx context.Context, spaceID, nodeID string) + queue chan *request + done chan struct{} + wg sync.WaitGroup + + // how long a caller waits for room in a full queue with QueueFullBlock, 0 for as long as + // it takes + queueFullTimeout time.Duration + + // the numbers this Service added to the Workers and QueueCapacity gauges + workers int + queueSize int + + mu sync.Mutex + queued map[string]*request // the requests waiting in the queue, by node; QueueLength counts them + // the nodes being cleaned up by a worker, with the request to queue once more when it + // is done, nil if there is none; QueueLength counts those requests as well + running map[string]*request + closed bool + // pending counts the requests from being queued until their cleanup has finished (or they + // were dropped or abandoned); idle is closed whenever pending is 0, see Wait + pending int + idle chan struct{} +} + +type request struct { + ctx context.Context // see detach + // link points to the span of the request that triggered the cleanup, see detach + link trace.Link + spaceID string + nodeID string +} + +func (r *request) key() string { + return r.spaceID + "/" + r.nodeID +} + +// NewServiceFromOptions returns the Service of a storage driver from its options: the cleanup +// strategy (RevisionsCleanupStrategy) and the RevisionsCleanupAsync* settings. +// It returns a disabled Service when no strategy is configured, and an error for invalid +// settings. +// +// The instances of the driver for the same storage (Root) in a process share one Service, see +// shared: only the first one creates it, with its lu and rs. Each instance shuts it down once, +// see Service.Shutdown. +func NewServiceFromOptions(o *options.Options, lu node.PathLookup, rs RevisionStore, log *zerolog.Logger) (*Service, error) { + async := AsyncOptionsFromOptions(o) + return sharedService(o.Root, o.RevisionsCleanupStrategy, async, func() (*Service, error) { + cleaner, err := New(o.RevisionsCleanupStrategy) + if err != nil { + return nil, err + } + return NewService(cleaner, lu, rs, async, log) + }) +} + +// AsyncOptionsFromOptions returns the AsyncOptions configured in the driver options +// (the RevisionsCleanupAsync* settings). +func AsyncOptionsFromOptions(o *options.Options) AsyncOptions { + return AsyncOptions{ + Enabled: o.RevisionsCleanupAsync, + Workers: o.RevisionsCleanupAsyncWorkers, + QueueSize: o.RevisionsCleanupAsyncQueueSize, + QueueFull: QueueFullPolicy(o.RevisionsCleanupAsyncQueueFull), + QueueFullTimeout: o.RevisionsCleanupAsyncQueueFullTimeout, + } +} + +// NewService creates a Service that cleans up with the given Cleaner, and starts its +// workers if opts.Enabled. With a disabled (or nil) Cleaner, it returns a disabled Service, +// which starts no workers and never cleans up anything. +// The options are validated in any case, so that invalid settings are reported even while +// the cleanup is disabled. +func NewService(cleaner *Cleaner, lu node.PathLookup, rs RevisionStore, opts AsyncOptions, log *zerolog.Logger) (*Service, error) { + return newService(cleaner, lu, rs, opts, log, false, false, nil) +} + +// newService creates a Service, see NewService; onDemand creates the Service of an on-demand +// Run, with dryRun it only decides without deleting, and report, if not nil, gets the Result +// of every cleanup. +func newService(cleaner *Cleaner, lu node.PathLookup, rs RevisionStore, opts AsyncOptions, log *zerolog.Logger, onDemand, dryRun bool, report func(Result)) (*Service, error) { + workers, queueSize, policy, err := opts.resolve() + if err != nil { + return nil, err + } + if log == nil { + log = &zerolog.Logger{} + } + if !cleaner.Enabled() { + return &Service{cleaner: cleaner, log: log}, nil + } + s := &Service{cleaner: cleaner, lu: lu, rs: rs, log: log, onDemand: onDemand, dryRun: dryRun, report: report} + if onDemand { + s.metrics = unregisteredMetrics() + } + s.m().enabled.Set(1) + if opts.Enabled { + s.queueFullTimeout = opts.QueueFullTimeout + s.startWorkers(workers, queueSize, policy, s.cleanupNode) + log.Info().Str("config", cleaner.config).Int("workers", workers).Int("queuesize", queueSize). + Str("queuefull", string(policy)).Dur("queuefulltimeout", opts.QueueFullTimeout). + Msg("revision cleanup: running in the background") + } + return s, nil +} + +// Enabled tells whether s cleans up anything, i.e. whether its Cleaner has a strategy. +// It is false for a disabled Service, and for a nil one. +func (s *Service) Enabled() bool { + return s != nil && s.cleaner.Enabled() +} + +// startWorkers switches the Service to asynchronous mode. process does the work for one +// node; it is a parameter so that tests can observe the queueing without a storage. +func (s *Service) startWorkers(workers, queueSize int, policy QueueFullPolicy, process func(ctx context.Context, spaceID, nodeID string)) { + s.async = true + s.policy = policy + s.process = process + s.queue = make(chan *request, queueSize) + s.done = make(chan struct{}) + s.queued = make(map[string]*request) + s.running = make(map[string]*request) + s.idle = make(chan struct{}) + close(s.idle) + s.workers = workers + s.queueSize = queueSize + s.m().workers.Add(float64(workers)) + s.m().queueCapacity.Add(float64(queueSize)) + for range workers { + s.wg.Add(1) + go s.work() + } +} + +// HandleRevisionCreated handles the event that a new revision of n was created and has +// settled: it cleans up the old revisions of n according to the strategy. In asynchronous +// mode it only queues n and returns, +// see Service and AsyncOptions. +// Errors are logged, never returned: a failed cleanup must not fail the operation that +// triggered it. +// +// In an on-demand Run, the end of ctx stops the run between files: a cleanup in synchronous +// mode still finishes its file, and a caller blocked on a full queue gives up, reporting the +// file as skipped. +// +// It checks no permissions, see Cleaner.Cleanup. +func (s *Service) HandleRevisionCreated(ctx context.Context, n *node.Node) { + if !s.Enabled() || n == nil { + return + } + s.handle(ctx, n.SpaceID, n.ID, n) +} + +// HandleRevisionCreatedByID is HandleRevisionCreated for a node given by its ids, for callers +// whose node is still in use elsewhere, as a node must not be shared between goroutines. It +// reads a node of its own only to clean it up: not at all if the cleanup is disabled, and in +// asynchronous mode only in the worker, which reads the node anyway. +// +// It checks no permissions, see Cleaner.Cleanup. +func (s *Service) HandleRevisionCreatedByID(ctx context.Context, spaceID, nodeID string) { + if !s.Enabled() { + return + } + s.handle(ctx, spaceID, nodeID, nil) +} + +// handle cleans up the node right away in synchronous mode, n if given, otherwise read by its +// ids, and queues it in asynchronous mode. +func (s *Service) handle(ctx context.Context, spaceID, nodeID string, n *node.Node) { + if !s.async { + if s.onDemand { + // don't leave a file half cleaned up, the run stops before the next one + ctx = context.WithoutCancel(ctx) + } + if n == nil { + s.cleanupNode(ctx, spaceID, nodeID) + return + } + s.clean(ctx, n) + return + } + // the cleanup outlives the request that triggered it, see detach + detached, link := detach(ctx) + s.enqueue(ctx, &request{ctx: detached, link: link, spaceID: spaceID, nodeID: nodeID}) +} + +// detach returns the context for a cleanup in the background, which outlives the request that +// triggered it, and a link to the request's span. +// +// The context is never cancelled, and it carries none of the values of the request's context, +// which may only be valid during the request, and which a request waiting in the queue would +// otherwise keep alive, except for the logger, so that the log lines of the cleanup keep the +// fields of the request, e.g. its id. The cleanup gets a trace of its own (see startSpan) with +// the link, rather than a span of the request's trace, which would usually have ended long +// before. +func detach(ctx context.Context) (context.Context, trace.Link) { + detached := appctx.WithLogger(context.Background(), appctx.GetLogger(ctx)) + return detached, trace.LinkFromContext(ctx) +} + +// startSpan starts the span of the cleanup of r in a worker, linked to the span of the request +// that triggered it, if there was one, see detach. +func startSpan(r *request) (context.Context, trace.Span) { + opts := []trace.SpanStartOption{trace.WithAttributes( + attribute.String("spaceid", r.spaceID), + attribute.String("nodeid", r.nodeID), + )} + if r.link.SpanContext.IsValid() { + opts = append(opts, trace.WithLinks(r.link)) + } + return tracer.Start(r.ctx, "revision cleanup", opts...) +} + +// enqueue queues r; ctx is the caller's context, which only an on-demand Run waits on. +func (s *Service) enqueue(ctx context.Context, r *request) { + log := appctx.GetLogger(r.ctx).With().Str("spaceid", r.spaceID).Str("nodeid", r.nodeID).Logger() + key := r.key() + + s.mu.Lock() + if s.closed { + s.mu.Unlock() + log.Debug().Msg("revision cleanup: shutting down, not scheduling cleanup") + return + } + if _, ok := s.queued[key]; ok { + // already waiting in the queue, it will see the new revision as well + s.mu.Unlock() + return + } + if again, ok := s.running[key]; ok { + // being cleaned up right now: it is queued once more when that is done + if again == nil { + s.running[key] = r + s.addPending() + s.m().queueLength.Inc() + } + s.mu.Unlock() + return + } + s.queued[key] = r + s.addPending() + s.m().queueLength.Inc() + s.mu.Unlock() + s.send(ctx, r) +} + +// send puts r, which waits in s.queued, into the queue, applying the queue full policy. +// s.mu is not held while sending, so that a blocked sender does not block the workers. +// ctx is the caller's context, see enqueue. +func (s *Service) send(ctx context.Context, r *request) { + log := appctx.GetLogger(r.ctx).With().Str("spaceid", r.spaceID).Str("nodeid", r.nodeID).Logger() + select { + case s.queue <- r: + return + default: + } + if s.policy == QueueFullDrop { + s.m().queueFull.WithLabelValues(queueFullDropped).Inc() + if s.forget(r) { + s.reportResult(Result{SpaceID: r.spaceID, NodeID: r.nodeID, DryRun: s.dryRun, + Skipped: fmt.Sprintf("the queue was full (queue full policy %q)", QueueFullDrop)}) + } + log.Warn().Str("path", s.internalPath(r.spaceID, r.nodeID)). + Msg("revision cleanup: queue is full, skipping the cleanup of this node until its next revision") + return + } + s.m().queueFull.WithLabelValues(queueFullBlocked).Inc() + log.Debug().Msg("revision cleanup: queue is full, waiting for room") + // with a timeout, a caller doesn't wait for longer than that: under sustained load, it + // would otherwise slow down every write, e.g. the consumer of the postprocessing events + var timeout <-chan time.Time + if s.queueFullTimeout > 0 { + timer := time.NewTimer(s.queueFullTimeout) + defer timer.Stop() + timeout = timer.C + } + var stopped <-chan struct{} // nil, i.e. never, unless on demand + if s.onDemand { + stopped = ctx.Done() + } + select { + case s.queue <- r: + case <-s.done: + // Shutdown abandoned (and reported) it + s.forget(r) + case <-timeout: + s.m().queueFull.WithLabelValues(queueFullDropped).Inc() + if s.forget(r) { + s.reportResult(Result{SpaceID: r.spaceID, NodeID: r.nodeID, DryRun: s.dryRun, + Skipped: fmt.Sprintf("the queue was still full after %s (queue full policy %q)", s.queueFullTimeout, QueueFullBlock)}) + } + log.Warn().Str("path", s.internalPath(r.spaceID, r.nodeID)).Dur("timeout", s.queueFullTimeout). + Msg("revision cleanup: queue is still full after the timeout, skipping the cleanup of this node until its next revision") + case <-stopped: + if s.forget(r) { + s.reportResult(Result{SpaceID: r.spaceID, NodeID: r.nodeID, DryRun: s.dryRun, Skipped: skippedStopped}) + } + } +} + +// the reason for skipping files whose cleanup was queued when an on-demand run was stopped +const skippedStopped = "the cleanup was stopped before this file was reached" + +// internalPath returns the path of a node on disk, e.g. for logging what is skipped, so that +// admins can find it. It is empty for a Service without a lookup. +func (s *Service) internalPath(spaceID, nodeID string) string { + if s.lu == nil { + return "" + } + return s.lu.InternalPath(spaceID, nodeID) +} + +// forget removes a request that did not make it into the queue. It returns false if the +// request was not waiting anymore, e.g. as Shutdown abandoned it. +func (s *Service) forget(r *request) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.queued[r.key()] != r { + return false + } + delete(s.queued, r.key()) + s.m().queueLength.Dec() + s.donePending(1) + return true +} + +func (s *Service) work() { + defer s.wg.Done() + for { + // a select with several ready cases picks one at random, so check for the + // shutdown first, otherwise a worker could keep taking requests from a + // non-empty queue after Shutdown + select { + case <-s.done: + return + default: + } + select { + case <-s.done: + return + case r := <-s.queue: + select { + case <-s.done: + // shut down while waiting for this request: abandon it, Shutdown + // counts it as abandoned + return + default: + } + // from here on, new requests for the node are collected to queue it once more + // when this cleanup is done, instead of being merged into this one + s.mu.Lock() + if s.closed { + // shut down in the meantime: Shutdown already counted this request as abandoned + s.mu.Unlock() + return + } + if s.queued[r.key()] == r { + delete(s.queued, r.key()) + s.m().queueLength.Dec() + } + s.running[r.key()] = nil + s.mu.Unlock() + s.m().running.Inc() + ctx, span := startSpan(r) + s.process(ctx, r.spaceID, r.nodeID) + span.End() + s.m().running.Dec() + s.mu.Lock() + again := s.running[r.key()] + delete(s.running, r.key()) + s.donePending(1) + if again == nil || s.closed { + // done, or shut down, which abandoned a request to queue again + s.mu.Unlock() + continue + } + // queue the node once more, at the end of the queue, so that the other nodes get + // their turn; sending in a goroutine of its own, as a worker must never wait for + // room in the queue it empties. QueueLength and pending already count the request. + s.queued[again.key()] = again + s.mu.Unlock() + // No caller waits for it: in an on-demand Run, Shutdown stops it. + go s.send(context.Background(), again) + } + } +} + +// cleanupNode reads the node again and cleans it up, it runs in a worker. +func (s *Service) cleanupNode(ctx context.Context, spaceID, nodeID string) { + if s.dryRun { + // also reading the node must not create lock files, see Cleaner.DryRun; a worker's + // context doesn't carry the marker of the request, see detach + ctx = metadata.WithReadOnly(ctx) + } + // Reading the node needs the group of its space just as cleaning it up does, see + // SpaceScoper. Nothing has switched to it for a worker; the Cleaner switches once more. + ctx, unscope, err := scopeToSpace(ctx, s.rs, spaceID) + if err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", spaceID).Str("nodeid", nodeID).Msg("revision cleanup: could not switch to the group of the space") + s.reportResult(Result{SpaceID: spaceID, NodeID: nodeID, DryRun: s.dryRun, Err: fmt.Errorf("could not switch to the group of the space: %w", err)}) + return + } + defer func() { _ = unscope() }() + + // read also in a disabled space, to tell it apart from an error + n, err := node.ReadNode(ctx, s.lu, spaceID, nodeID, "", true, nil, false) + if err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", spaceID).Str("nodeid", nodeID).Msg("revision cleanup: could not read node") + s.reportResult(Result{SpaceID: spaceID, NodeID: nodeID, DryRun: s.dryRun, Err: fmt.Errorf("could not read node: %w", err)}) + return + } + if !n.Exists { + // deleted in the meantime, its revisions went with it (or into the trash) + s.reportResult(Result{SpaceID: spaceID, NodeID: nodeID, DryRun: s.dryRun, Skipped: "the file no longer exists"}) + return + } + if n.SpaceRoot != nil && n.SpaceRoot.IsDisabled(ctx) { + // disabled in the meantime: the space is in the trash, leave its files alone + appctx.GetLogger(ctx).Debug().Str("spaceid", spaceID).Str("nodeid", nodeID).Msg("revision cleanup: the space is disabled, skipping") + s.reportResult(Result{SpaceID: spaceID, NodeID: nodeID, DryRun: s.dryRun, Skipped: "the space is disabled"}) + return + } + s.clean(ctx, n) +} + +// clean runs the cleanup of n, or only decides about it in a dry run, and reports the Result. +func (s *Service) clean(ctx context.Context, n *node.Node) { + // the details of the revisions only for someone who reads them + result := s.cleaner.run(ctx, s.lu, s.rs, n, s.dryRun, s.report != nil) + s.reportResult(result) +} + +// m returns the metrics this Service updates: the exported ones, unless it is the Service of an +// on-demand Run. +func (s *Service) m() *serviceMetrics { + if s.metrics != nil { + return s.metrics + } + return &driverMetrics +} + +func (s *Service) reportResult(result Result) { + if s.report != nil { + s.report(result) + } +} + +// addPending counts a new request, s.mu must be held. +func (s *Service) addPending() { + if s.pending == 0 { + s.idle = make(chan struct{}) + } + s.pending++ +} + +// donePending counts n requests as finished, s.mu must be held. +func (s *Service) donePending(n int) { + if n <= 0 { + return + } + s.pending -= n + if s.pending <= 0 { + s.pending = 0 + close(s.idle) + } +} + +// Wait waits until no cleanup is queued or running anymore, or until ctx ends, in which case +// it returns ctx's error. Requests that were dropped (queue full policy "drop") or abandoned +// by Shutdown don't keep it waiting. In synchronous mode, and for a nil Service, it returns +// right away, as the cleanups already ran in their callers. +// +// Unlike Shutdown, it doesn't stop anything: it is meant for callers that queue a batch of +// cleanups and need them to be done, e.g. a command cleaning up all files of a space. +// Cleanups queued while it waits are waited for as well, until the Service is idle once. +func (s *Service) Wait(ctx context.Context) error { + if s == nil || !s.async { + return nil + } + s.mu.Lock() + idle := s.idle + s.mu.Unlock() + select { + case <-idle: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// Shutdown stops the background workers. A Service shared by the instances of a storage (see +// NewServiceFromOptions) only stops when the last of them shuts it down: each instance calls +// Shutdown once. A cleanup that is running is finished, the ones +// still waiting in the queue are abandoned (and logged, and reported as skipped in an +// on-demand Run): they are picked up again when their nodes get their next revision. +// Blocked callers are released. It returns when the +// workers have stopped, or with ctx's error if ctx ends first. +func (s *Service) Shutdown(ctx context.Context) error { + if s == nil || !s.release() || !s.async { + return nil + } + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return nil + } + s.closed = true + close(s.done) + // abandon the requests still waiting, in the queue or to be queued once more: they won't + // be processed anymore, and their nodes are cleaned up again when they get their next + // revision + var abandonedRequests []*request + for _, r := range s.queued { + abandonedRequests = append(abandonedRequests, r) + } + clear(s.queued) + for key, r := range s.running { + if r != nil { + abandonedRequests = append(abandonedRequests, r) + s.running[key] = nil + } + } + abandoned := len(abandonedRequests) + var skipped []Result + if s.report != nil { + for _, r := range abandonedRequests { + skipped = append(skipped, Result{SpaceID: r.spaceID, NodeID: r.nodeID, DryRun: s.dryRun, Skipped: skippedStopped}) + } + slices.SortFunc(skipped, func(a, b Result) int { return strings.Compare(a.SpaceID+"/"+a.NodeID, b.SpaceID+"/"+b.NodeID) }) + } + s.donePending(abandoned) + s.m().queueLength.Sub(float64(abandoned)) + s.m().workers.Sub(float64(s.workers)) + s.m().queueCapacity.Sub(float64(s.queueSize)) + s.mu.Unlock() + for _, result := range skipped { + s.reportResult(result) + } + + stopped := make(chan struct{}) + go func() { + s.wg.Wait() + close(stopped) + }() + select { + case <-stopped: + case <-ctx.Done(): + return ctx.Err() + } + + if abandoned > 0 { + s.log.Info().Int("abandoned", abandoned).Msg("revision cleanup: stopped, abandoned the cleanups still waiting in the queue") + } + return nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/shared.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/shared.go new file mode 100644 index 0000000000..7e2e92cc93 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup/shared.go @@ -0,0 +1,79 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisioncleanup + +import ( + "fmt" + "path/filepath" + "sync" +) + +// A process may set up the same storage more than once: e.g. the storage provider and the data +// provider each create an instance of the storage driver. Each instance used to get a Service +// of its own, so that every storage had twice the configured workers, and the de-duplication of +// the requests per node didn't work across the two, so that a node could be cleaned up by both +// at the same time. +// +// NewServiceFromOptions therefore shares one Service between the instances of a storage in a +// process, by the root of the storage. The first instance creates it, with its lookup and its +// revision store, and the others reuse it: all instances of a storage work on the same files +// with the same settings, so either instance's lookup and store do. The Service stops once the +// last instance has shut it down, see Service.Shutdown. +var shared = struct { + sync.Mutex + byRoot map[string]*Service +}{byRoot: map[string]*Service{}} + +// share is the bookkeeping of a Service shared by the instances of a storage, see shared. +type share struct { + root string + refs int // the instances that haven't shut the Service down yet + strategy string + async AsyncOptions +} + +// sharedService returns the Service shared by the instances of the storage at root, creating it +// with create for the first one. The instances must agree on the strategy and the AsyncOptions: +// a storage set up twice with different settings would otherwise be cleaned up with the +// settings of whichever instance happened to come first. +func sharedService(root, strategy string, async AsyncOptions, create func() (*Service, error)) (*Service, error) { + root = filepath.Clean(root) + shared.Lock() + defer shared.Unlock() + if s, ok := shared.byRoot[root]; ok { + if s.share.strategy != strategy || s.share.async != async { + return nil, fmt.Errorf("the storage at %q is set up more than once in this process with different revision cleanup settings: strategy %q and %+v, then strategy %q and %+v", + root, s.share.strategy, s.share.async, strategy, async) + } + s.share.refs++ + return s, nil + } + s, err := create() + if err != nil { + return nil, err + } + s.share = &share{root: root, refs: 1, strategy: strategy, async: async} + shared.byRoot[root] = s + return s, nil +} + +// release gives up the share of one instance of the storage in s, and reports whether it was +// the last one, so that s is to stop. A Service that isn't shared is always the last one. +func (s *Service) release() bool { + if s.share == nil { + return true + } + shared.Lock() + defer shared.Unlock() + if s.share.refs == 0 { + // released by every instance already: stopping it again is harmless + return true + } + s.share.refs-- + if s.share.refs > 0 { + return false + } + delete(shared.byRoot, s.share.root) + return true +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisions.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisions.go index fee10c0146..eedec572dc 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisions.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisions.go @@ -24,6 +24,7 @@ import ( "os" "path/filepath" "strings" + "sync" "time" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -45,13 +46,68 @@ import ( // and replace the revision file with a symbolic link in the future, if necessary. func (fs *Decomposedfs) ListRevisions(ctx context.Context, ref *provider.Reference) (revisions []*provider.FileVersion, err error) { - return fs.tp.ListRevisions(ctx, ref) + _, span := tracer.Start(ctx, "ListRevisions") + defer span.End() + n, err := fs.lu.NodeFromResource(ctx, ref) + if err != nil { + return nil, err + } + if !n.Exists { + return nil, errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) + } + + rp, err := fs.p.AssemblePermissions(ctx, n) + switch { + case err != nil: + return nil, err + case !rp.ListFileVersions: + f, _ := storagespace.FormatReference(ref) + if rp.Stat { + return nil, errtypes.PermissionDenied(f) + } + return nil, errtypes.NotFound(f) + } + + return fs.tp.ListRevisions(ctx, n) } // DownloadRevision returns a reader for the specified revision // FIXME the CS3 api should explicitly allow initiating revision and trash download, a related issue is https://github.com/cs3org/reva/issues/1813 func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { - return fs.tp.DownloadRevision(ctx, ref, revisionKey, openReaderFunc) + _, span := tracer.Start(ctx, "DownloadRevision") + defer span.End() + log := appctx.GetLogger(ctx) + + // verify revision key format + kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) + if len(kp) != 2 || !node.IsValidID(revisionKey) { + log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") + return nil, nil, errtypes.NotFound(revisionKey) + } + log.Debug().Str("revisionKey", revisionKey).Msg("DownloadRevision") + + // check if the node is available and has not been deleted + n, err := node.ReadNode(ctx, fs.lu, ref.ResourceId.SpaceId, kp[0], "", false, nil, false) + if err != nil { + return nil, nil, err + } + if !n.Exists { + return nil, nil, errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) + } + + rp, err := fs.p.AssemblePermissions(ctx, n) + switch { + case err != nil: + return nil, nil, err + case !rp.ListFileVersions || !rp.InitiateFileDownload: // TODO add explicit permission in the CS3 api? + f, _ := storagespace.FormatReference(ref) + if rp.Stat { + return nil, nil, errtypes.PermissionDenied(f) + } + return nil, nil, errtypes.NotFound(f) + } + + return fs.tp.DownloadRevision(ctx, n, revisionKey, rp, openReaderFunc) } // RestoreRevision restores the specified revision of the resource @@ -105,10 +161,25 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer if err != nil { return nil, err } - defer func() { - _ = unlock() - _ = os.Remove(fs.lu.MetadataBackend().LockfilePath(n)) - }() + // released before the revision cleanup at the end, or on any return before that + unlockNode := sync.OnceValue(unlock) + defer func() { _ = unlockNode() }() + + // The revision must still exist on disk. Its metadata may come from a stale cache + // entry: another process, e.g. `opencloud storage-users revisions cleanup` with the + // default in-memory metadata cache, may have deleted it. Restoring it anyway would + // point the node to the revision's deleted blob, and it would leave a revision of the + // current content behind. Checked under the node's lock, which deleting a revision + // takes too (Node.DeleteRevisionUnchecked). + revisionNode := node.NewBaseNode(spaceID, revisionKey, fs.lu) + if _, err := os.Stat(revisionNode.InternalPath()); err != nil { + if !os.IsNotExist(err) { + return nil, err + } + // drop the stale cache entry, if there is one + _ = fs.lu.MetadataBackend().Purge(ctx, revisionNode) + return nil, errtypes.NotFound(revisionKey) + } // move current version to new revision mtime, err := n.GetMTime(ctx) @@ -117,14 +188,23 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer return nil, err } + // the blob id the node gets back, for the mark of the revision created below + restoredBlobID, err := fs.lu.MetadataBackend().Get(ctx, revisionNode, prefixes.BlobIDAttr) + if err != nil { + log.Warn().Err(err).Interface("ref", ref).Str("revisionKey", revisionKey).Msg("could not read the blob id of the revision, the revision of the replaced content won't be protected from the revision cleanup") + } + // create a revision of the current node - if _, err := fs.tp.CreateRevision(ctx, n, mtime.UTC().Format(time.RFC3339Nano)); err != nil { + // It is named after the mtime of the content it preserves, not after the time it is + // created; the revision cleanup goes by the time it is created, which CreateRevision + // records (see node.RevisionCreatedAttr). + newRevision := mtime.UTC().Format(time.RFC3339Nano) + if _, err := fs.tp.CreateRevision(ctx, n, newRevision); err != nil { return nil, err } // revision 5, current 10 (restore a smaller blob) -> 5-10 = -5 // revision 10, current 5 (restore a bigger blob) -> 10-5 = +5 - revisionNode := node.NewBaseNode(spaceID, revisionKey, fs.lu) revisionSize, err := fs.lu.MetadataBackend().GetInt64(ctx, revisionNode, prefixes.BlobsizeAttr) if err != nil { return nil, errtypes.InternalError("failed to read blob size xattr from old revision") @@ -137,6 +217,19 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer return nil, err } + // A restore is a deliberate user action: the revision cleanup must not drop the content the + // user just replaced, e.g. because its revision is older than the strategy allows, or as the + // 'auto' strategy thins out revisions that are close in time. Marked on disk, while the + // node is still locked, so that every cleanup sees it, see node.KeepAfterRestoreAttr. Not + // marking it doesn't fail the restore, which is done by now: the revision is only protected + // less. + if len(restoredBlobID) > 0 { + newRevisionNode := node.NewBaseNode(spaceID, n.ID+node.RevisionIDDelimiter+newRevision, fs.lu) + if err := fs.lu.MetadataBackend().Set(ctx, newRevisionNode, node.KeepAfterRestoreAttr, restoredBlobID); err != nil { + log.Error().Err(err).Interface("ref", ref).Str("revision", newRevisionNode.ID).Msg("could not mark the revision of the replaced content, the revision cleanup may delete it") + } + } + // drop old revision if err := os.Remove(restoredRevisionPath); err != nil { log.Warn().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("could not delete old revision, continuing") @@ -154,6 +247,15 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer if err := fs.tp.Propagate(ctx, n, sizeDiff); err != nil { return nil, err } + + // The restore created a new revision from the previous content, so apply the + // revision cleanup strategy (see package revisioncleanup). It runs last, once the + // restore is complete, and never fails the restore. It keeps the revision marked above. + // The node lock is released first: the cleanup takes it itself, and when it runs in the + // background, waiting for room in its queue while holding the lock could deadlock with + // a worker waiting for the lock. + _ = unlockNode() + fs.revisionsCleanup.HandleRevisionCreated(ctx, n) return &storage.RestoreRevisionResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID}, nil } @@ -180,7 +282,7 @@ func (fs *Decomposedfs) deleteRevisionFile(ctx context.Context, n *node.Node, re return errtypes.NotFound(revisionKey) } - blobID, err := n.DeleteRevision(ctx, kp[1]) + blobID, err := n.DeleteRevisionUnchecked(ctx, kp[1]) if err != nil { return err } diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/spaceidindex/spaceidindex.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/spaceidindex/spaceidindex.go index 325db845a5..09a770e542 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/spaceidindex/spaceidindex.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/spaceidindex/spaceidindex.go @@ -4,6 +4,8 @@ import ( "io" "os" "path/filepath" + "slices" + "strings" "time" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/mtimesyncedcache" @@ -49,6 +51,22 @@ func (i *Index) Load(index string) (map[string]string, error) { return i.readSpaceIndex(indexPath, i.name+":"+index, fi.ModTime()) } +// Indexes returns the names of the indexes, sorted, e.g. the space types of an index by type. +func (i *Index) Indexes() ([]string, error) { + entries, err := os.ReadDir(filepath.Join(i.root, i.name)) + if err != nil { + return nil, err + } + names := []string{} + for _, e := range entries { + if name, ok := strings.CutSuffix(e.Name(), ".mpk"); ok && e.Type().IsRegular() { + names = append(names, name) + } + } + slices.Sort(names) + return names, nil +} + // Add adds an entry to an index // Consider calling AddAll() when trying to add multiple entries as every Add call has to lock the index func (i *Index) Add(index, key string, value string) error { diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/revisions.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/revisions.go index 3b4fc4ff87..d048b19f6e 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/revisions.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/revisions.go @@ -36,7 +36,6 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" - "github.com/opencloud-eu/reva/v3/pkg/storagespace" "github.com/opencloud-eu/reva/v3/pkg/utils" ) @@ -126,34 +125,17 @@ func (tp *Tree) CreateRevision(ctx context.Context, n *node.Node, version string }); err != nil { return "", err } + // the time the revision was created, which the revision cleanup goes by, see + // node.RevisionCreatedAttr + if err := node.SetRevisionCreated(ctx, tp.lookup.MetadataBackend(), versionNode, time.Now()); err != nil { + return "", err + } return versionPath, nil } -func (tp *Tree) ListRevisions(ctx context.Context, ref *provider.Reference) (revisions []*provider.FileVersion, err error) { - _, span := tracer.Start(ctx, "ListRevisions") - defer span.End() - var n *node.Node - if n, err = tp.lookup.NodeFromResource(ctx, ref); err != nil { - return - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return - } - - rp, err := tp.permissions.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, err - case !rp.ListFileVersions: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - +// ListRevisions lists all revisions of n. It checks no permissions, see node.Tree. +func (tp *Tree) ListRevisions(ctx context.Context, n *node.Node) (revisions []*provider.FileVersion, err error) { revisions = []*provider.FileVersion{} np := n.InternalPath() if items, err := filepath.Glob(np + node.RevisionIDDelimiter + "*"); err == nil { @@ -198,45 +180,28 @@ func (tp *Tree) ListRevisions(ctx context.Context, ref *provider.Reference) (rev return } -// DownloadRevision returns a reader for the specified revision -// FIXME the CS3 api should explicitly allow initiating revision and trash download, a related issue is https://github.com/cs3org/reva/issues/1813 -func (tp *Tree) DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { +// DownloadRevision returns the resource info of the revision revisionKey of n and, if +// openReaderFunc wants it, a reader for its content. It checks no permissions, see node.Tree: +// rp are the permissions of the user on n, for the resource info. +func (tp *Tree) DownloadRevision(ctx context.Context, n *node.Node, revisionKey string, rp *provider.ResourcePermissions, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { _, span := tracer.Start(ctx, "DownloadRevision") defer span.End() - log := appctx.GetLogger(ctx) - // verify revision key format kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) - if len(kp) != 2 || !node.IsValidID(revisionKey) { - log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") + if len(kp) != 2 || kp[0] != n.ID { return nil, nil, errtypes.NotFound(revisionKey) } - log.Debug().Str("revisionKey", revisionKey).Msg("DownloadRevision") - - spaceID := ref.ResourceId.SpaceId - // check if the node is available and has not been deleted - n, err := node.ReadNode(ctx, tp.lookup, spaceID, kp[0], "", false, nil, false) - if err != nil { - return nil, nil, err - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return nil, nil, err - } - - rp, err := tp.permissions.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, nil, err - case !rp.ListFileVersions || !rp.InitiateFileDownload: // TODO add explicit permission in the CS3 api? - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, nil, errtypes.PermissionDenied(f) - } - return nil, nil, errtypes.NotFound(f) - } + spaceID := n.SpaceID baseNode := node.NewBaseNode(spaceID, revisionKey, tp.lookup) + // the revision's metadata may come from a stale cache entry, after another process + // deleted the revision (see Decomposedfs.RestoreRevision) + if _, err := os.Stat(baseNode.InternalPath()); err != nil { + if os.IsNotExist(err) { + return nil, nil, errtypes.NotFound(revisionKey) + } + return nil, nil, err + } blobid, blobsize, err := tp.lookup.ReadBlobIDAndSizeAttr(ctx, baseNode, nil) if err != nil { return nil, nil, errors.Wrapf(err, "Decomposedfs: could not read blob id and size for revision '%s' of node '%s'", kp[1], n.ID) diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/tree.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/tree.go index e5e3ea886f..afa0e9c838 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/tree.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/tree.go @@ -41,6 +41,7 @@ import ( "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/permissions" + "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup" "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/tree/propagator" "github.com/opencloud-eu/reva/v3/pkg/utils" "github.com/pkg/errors" @@ -69,6 +70,8 @@ type Tree struct { idCache store.Store } +var _ node.Tree = &Tree{} + // PermissionCheckFunc defined a function used to check resource permissions type PermissionCheckFunc func(rp *provider.ResourcePermissions) bool @@ -325,6 +328,24 @@ func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) // ListFolder lists the content of a folder node func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, error) { + return t.listFolder(ctx, n, true) +} + +var _ revisioncleanup.Walker = (*Tree)(nil) + +// ListFolderKnownUnchecked lists the children of n that are known to the storage, for +// maintenance, see revisioncleanup.Walker. Unlike ListFolder, it checks no permissions, so it +// needs no user in the context. Known children are the files and folders the storage has +// registered with a node id; it never assimilates (registers) unknown ones. In this tree, every +// child is known, as all files are created through the storage, so it lists all children. The +// distinction matters for posix, where files can be created on disk directly. +func (t *Tree) ListFolderKnownUnchecked(ctx context.Context, n *node.Node) ([]*node.Node, error) { + return t.listFolder(ctx, n, false) +} + +// listFolder lists the children of n, leaving out the ones denied to the user in ctx if +// forUser. +func (t *Tree) listFolder(ctx context.Context, n *node.Node, forUser bool) ([]*node.Node, error) { ctx, span := tracer.Start(ctx, "ListFolder") defer span.End() dir := n.InternalPath() @@ -395,8 +416,10 @@ func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, erro continue } - // prevent listing denied resources - if !child.IsDenied(ctx) { + // prevent listing denied resources, for users only: a listing for maintenance + // (ListFolderKnownUnchecked) has no user in the context, IsDenied would panic + // without one, and it must see all children, also the ones denied to users + if !forUser || !child.IsDenied(ctx) { if child.SpaceRoot == nil { child.SpaceRoot = n.SpaceRoot } diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_auto.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_auto.go new file mode 100644 index 0000000000..8a6165656c --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_auto.go @@ -0,0 +1,202 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "fmt" + "slices" + "time" + + "github.com/rs/zerolog" +) + +const ( + autoStrategy = "auto" +) + +type autoRevisionCleanupStrategy struct { +} + +var _ RevisionCleanupStrategy = &autoRevisionCleanupStrategy{} + +func newAutoRevisionCleanupStrategy() (RevisionCleanupStrategy, error) { + return &autoRevisionCleanupStrategy{}, nil +} + +func newAutoRevisionCleanupStrategyFromString(config string) (RevisionCleanupStrategy, error) { + if config != autoStrategy { + return nil, nil // we don't support this + } + return newAutoRevisionCleanupStrategy() +} + +// bucketPolicy defines a time window and the resolution slot within that window. +type bucketPolicy struct { + name string // value only matters for debugging, but must be unique + description string // the time window in words, for the reasons in the Plan + ageLimit time.Duration // Max age relative to 'now' to belong to this bucket + interval time.Duration // Slot duration (<=0 means keep all) + maxKeep int // Max revisions to keep per slot (<=0 means keep all, >0 caps per slot) +} + +// Standard GFS (Grandfather-Father-Son) style retention tiers. +var defaultPolicy = []bucketPolicy{ + { + name: "LastMinute", + description: "last minute", + ageLimit: 1 * time.Minute, // last minute + maxKeep: 1, // one version + interval: 10 * time.Second, // is kept every 10 seconds + }, + { + name: "LastHour", + description: "last hour", + ageLimit: 1 * time.Hour, // last hour + maxKeep: 1, // one version + interval: 1 * time.Minute, // is kept every minute + }, + { + name: "Last24H", + description: "last 24 hours", + ageLimit: 24 * time.Hour, // last 24 hours + maxKeep: 1, // one version + interval: 1 * time.Hour, // is kept every hour + }, + { + name: "Last30D", + description: "last 30 days", + ageLimit: 30 * 24 * time.Hour, // last 30 days + maxKeep: 1, // one version + interval: 24 * time.Hour, // is kept every day + }, + { + name: "Older30D", + description: "older than 30 days", + ageLimit: 0, // older than 30 days (0 AgeLimit denotes the catch-all "older" tier) + maxKeep: 1, // one version + interval: 7 * 24 * time.Hour, // s kept every week + }, +} + +// evaluateRetention thins revisions across dynamic time tiers based on interval slots. +// Every decision in the returned Plan comes with a reason that names the tier and, for tiers +// with slots, the slot, so that the outcome of this not quite trivial bucket system can be +// explained (e.g. in the debug log or in verbose output). +func evaluateRetention(revisions []Revision, policies []bucketPolicy, now time.Time) Plan { + // First, iterate over all revisions to group/sort them into discrete, + // mutually exclusive buckets (one revision can only ever be in one bucket). + // One bucket (of revisions) corresponds to one bucketPolicy. + bucket := make(map[string][]Revision) + for _, rev := range revisions { + t := rev.CreationTime() + age := now.Sub(t) + + matched := false + for _, policy := range policies { + if policy.ageLimit > 0 && age <= policy.ageLimit { + bucket[policy.name] = append(bucket[policy.name], rev) + matched = true + break + } + } + + // if we couldn't find a fitting bucket for this rev yet, + // then put it into the last bucket, which is assumed to be the + // "catch-all" one for "older than": + if !matched && len(policies) > 0 { + lastPolicy := policies[len(policies)-1] + bucket[lastPolicy.name] = append(bucket[lastPolicy.name], rev) + } + } + + plan := NewSimplePlan() + + // Thin each bucket according to its interval resolution and MaxKeep limit + for _, policy := range policies { + items := bucket[policy.name] + if len(items) == 0 { + continue // let's stop right here, nothing to do + } + kept := fmt.Sprintf("kept by %q (%s): ", autoStrategy, policy.description) + deleted := fmt.Sprintf("deleted by %q (%s): ", autoStrategy, policy.description) + + if policy.interval <= 0 { + // if interval is not set (<=0), then we just keep maxKeep items across the whole bucket: + // keep the first maxKeep, and delete everything else (keeping in mind that revisions + // are sorted in newest-first order) + switch { + case policy.maxKeep <= 0: + // if maxKeep is not set (<=0), then we retain *all* of the revisions in the bucket + plan.Retain(kept+"all revisions are kept", items...) + case policy.maxKeep < len(items): + // we keep less revisions than we have in total in this bucket + // => we need to do something: since they are sorted in newest-first order, + // we can simply split the revisions slice in two: + retain := items[:policy.maxKeep] // the first ones up to maxKeep are retained + delete := items[policy.maxKeep:] // everything after maxKeep is deleted + plan.Retain(kept+fmt.Sprintf("one of the %d newest", policy.maxKeep), retain...) + plan.Delete(deleted+fmt.Sprintf("beyond the %d newest", policy.maxKeep), delete...) + default: + // maxKeep is larger than the number of items => retain everything + plan.Retain(kept+fmt.Sprintf("one of the %d newest", policy.maxKeep), items...) + } + } else { + // interval is set for this bucket, in which case we need to apply the slightly + // more complex policy of putting revisions within this bucket into slots of + // duration of ${interval}, and then count the number of revisions in each slot + // to determine which to delete (or not) + + // we will use unix nano timestamps as the keys for the map of slots, + // just as a performance improvement to avoid using time.Duration objects + slotCounts := make(map[int64]int) + + // The oldest revisions of each slot are kept, so the revisions are visited oldest + // first. The time of a revision is when it was created, i.e. when its content was + // replaced: the oldest revision of a slot holds the content the file had when the + // slot began. Keeping the newest instead would delete a version that was current + // for months as soon as the file is saved twice within the same slot, keeping only + // the content of the few seconds in between. + for _, rev := range slices.Backward(items) { + // we take the revision's time, but truncate it to the interval for this + // bucket (e.g. 1m or 1h), in order to count how many revisions we have + // in each slot within the bucket; note that we also transform the + // time.Duration into an int64 to use that as the key in the slot map + slotKey := rev.CreationTime().Truncate(policy.interval).UnixNano() + slot := fmt.Sprintf("its slot of %s starting %s", humanDuration(policy.interval), formatTime(time.Unix(0, slotKey).UTC())) + + count := slotCounts[slotKey] + switch { + case policy.maxKeep <= 0: + // if maxKeep is not set (<=0), then we keep them all anyways + plan.Retain(kept+"all revisions are kept", rev) + case count < policy.maxKeep: + // if the current count of revisions in this slot is smaller than maxKeep, + // then we also keep this revision + slotCounts[slotKey] = count + 1 + if policy.maxKeep == 1 { + plan.Retain(kept+"the oldest in "+slot, rev) + } else { + plan.Retain(kept+fmt.Sprintf("one of the %d oldest in %s", policy.maxKeep, slot), rev) + } + default: + // if maxKeep is set (>0) and the count of revisions within its assigned + // slot is higher than maxKeep, then the revision must be deleted + if policy.maxKeep == 1 { + plan.Delete(deleted+slot+" already keeps an older revision", rev) + } else { + plan.Delete(deleted+fmt.Sprintf("%s already keeps %d older revisions", slot, policy.maxKeep), rev) + } + } + } + } + } + + return plan +} + +func (s *autoRevisionCleanupStrategy) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + // no need to sort revisions, they are guaranteed to be sorted from newest to oldest + return evaluateRetention(revs, defaultPolicy, now), nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_chain.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_chain.go new file mode 100644 index 0000000000..cece35b722 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_chain.go @@ -0,0 +1,78 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "slices" + "time" + + "github.com/rs/zerolog" +) + +// A RevisionCleanupStrategy that applies a sequence of strategies one after the other. +// +// Every strategy in the chain only gets to see the revisions that the previous ones +// retained: revisions that were deleted or safeguarded by an earlier strategy are final. +type chainRevisionCleanupStrategy struct { + chain []RevisionCleanupStrategy +} + +// chainAwareStrategy is implemented by strategies whose decision depends on how many +// revisions the earlier strategies of a chain have already safeguarded. +// +// This is needed for count based deletion: in "7d, 10", "10" means "keep at most 10 +// revisions in total", not "keep 10 more on top of the ones younger than 7 days". As +// the chain only passes on the remaining revisions, the strategy needs to be told how +// many revisions it has to count in addition. Safeguarded revisions are always newer +// than the remaining ones (both safeguarding strategies protect the newest revisions), +// so they are exactly the ones counting towards the limit first. +type chainAwareStrategy interface { + cleanupInChain(now time.Time, revs []Revision, safeguarded int, ctx context.Context, logger *zerolog.Logger) (Plan, error) +} + +var _ RevisionCleanupStrategy = &chainRevisionCleanupStrategy{} + +func newChainRevisionCleanupStrategy(chain []RevisionCleanupStrategy) (RevisionCleanupStrategy, error) { + return &chainRevisionCleanupStrategy{ + chain: chain, + }, nil +} + +func (s *chainRevisionCleanupStrategy) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + masterPlan := NewSimplePlan() + remaining := slices.Clone(revs) + var last Plan + for _, strategy := range s.chain { + var plan Plan + var err error + if aware, ok := strategy.(chainAwareStrategy); ok { + plan, err = aware.cleanupInChain(now, remaining, len(masterPlan.Safeguarded()), ctx, logger) + } else { + plan, err = strategy.Cleanup(now, remaining, ctx, logger) + } + if err != nil { + return nil, err + } + + // the decisions of this step are final, they keep the reasons this step gave + for _, rev := range plan.Deleted() { + masterPlan.Delete(plan.Reason(rev.Key()), rev) + } + for _, rev := range plan.Safeguarded() { + masterPlan.Safeguard(plan.Reason(rev.Key()), rev) + } + remaining = slices.Clone(plan.Retained()) + last = plan + } + // the revisions no step decided about are kept, with the reason the last step gave + for _, rev := range remaining { + reason := "kept: not decided by any rule" + if last != nil && last.Reason(rev.Key()) != "" { + reason = last.Reason(rev.Key()) + } + masterPlan.Retain(reason, rev) + } + return masterPlan, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_deletion.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_deletion.go new file mode 100644 index 0000000000..c00b9e3584 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_deletion.go @@ -0,0 +1,67 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/rs/zerolog" +) + +// A RevisionCleanupStrategy that keeps at most a given number of revisions, the newest +// ones, and deletes all older revisions. +// +// Within a chain the limit is absolute: revisions safeguarded by earlier strategies of +// the chain count towards it (see chainAwareStrategy). +type countDeletionRevisionCleanupStrategy struct { + maxVersionsPerFile int +} + +var _ RevisionCleanupStrategy = &countDeletionRevisionCleanupStrategy{} + +var _ chainAwareStrategy = &countDeletionRevisionCleanupStrategy{} + +func newCountDeletionRevisionCleanupStrategy(maxVersionsPerFile int) (RevisionCleanupStrategy, error) { + return &countDeletionRevisionCleanupStrategy{ + maxVersionsPerFile: maxVersionsPerFile, + }, nil +} + +func newCountDeletionRevisionCleanupStrategyFromString(config string) (RevisionCleanupStrategy, error) { + if match, maxVersionsPerFile, err := countFromConfig(config); !match { + return nil, nil + } else if err != nil { + return nil, err + } else { + return newCountDeletionRevisionCleanupStrategy(maxVersionsPerFile) + } +} + +func (s *countDeletionRevisionCleanupStrategy) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + return s.cleanupInChain(now, revs, 0, ctx, logger) +} + +func (s *countDeletionRevisionCleanupStrategy) cleanupInChain(now time.Time, revs []Revision, safeguarded int, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + plan := NewSimplePlan() + // the safeguarded revisions already use up part of the limit, and if there are more + // of them than the limit allows, all remaining revisions have to go + keep := max(s.maxVersionsPerFile-safeguarded, 0) + spec := strconv.Itoa(s.maxVersionsPerFile) + counted := "" + if safeguarded > 0 { + counted = fmt.Sprintf(", counting the %d protected ones", safeguarded) + } + retained := fmt.Sprintf("kept by %q: one of the %d newest%s", spec, s.maxVersionsPerFile, counted) + if len(revs) <= keep { + plan.Retain(retained, revs...) + return plan, nil + } + // no need to sort revisions, they are guaranteed to be sorted from newest to oldest + plan.Delete(fmt.Sprintf("deleted by %q: beyond the %d newest%s", spec, s.maxVersionsPerFile, counted), revs[keep:]...) + plan.Retain(retained, revs[:keep]...) + return plan, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_retention.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_retention.go new file mode 100644 index 0000000000..ae606c6813 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_count_retention.go @@ -0,0 +1,44 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/rs/zerolog" +) + +type countRetentionRevisionCleanupStrategy struct { + versionsToSafeguard int +} + +var _ RevisionCleanupStrategy = &countRetentionRevisionCleanupStrategy{} + +func newCountRetentionRevisionCleanupStrategy(maxVersionsPerFile int) (RevisionCleanupStrategy, error) { + return &countRetentionRevisionCleanupStrategy{ + versionsToSafeguard: maxVersionsPerFile, + }, nil +} + +func newCountRetentionRevisionCleanupStrategyFromString(config string) (RevisionCleanupStrategy, error) { + if match, maxVersionsPerFile, err := countFromConfig(config); !match { + return nil, nil + } else if err != nil { + return nil, err + } else { + return newCountRetentionRevisionCleanupStrategy(maxVersionsPerFile) + } +} + +func (s *countRetentionRevisionCleanupStrategy) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + plan := NewSimplePlan() + n := min(s.versionsToSafeguard, len(revs)) + spec := strconv.Itoa(s.versionsToSafeguard) + plan.Safeguard(fmt.Sprintf("protected by %q: one of the %d newest", spec, s.versionsToSafeguard), revs[:n]...) + plan.Retain(fmt.Sprintf("not protected by %q: not one of the %d newest", spec, s.versionsToSafeguard), revs[n:]...) + return plan, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_deletion.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_deletion.go new file mode 100644 index 0000000000..c70cf6383d --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_deletion.go @@ -0,0 +1,68 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/rs/zerolog" +) + +// A RevisionCleanupStrategy that deletes files that are older than a given duration. +// +// With truncateToMidnight ("ND" or "NW" instead of "Nd" or "Nw"), the cutoff is aligned to +// local midnight instead of being exactly the duration before now, see computeCutoffFromRetention. +type durationDeletionRevisionCleanupStrategy struct { + retention time.Duration + truncateToMidnight bool + // spec is the duration as configured, e.g. "7d", for the reasons in the Plan; when empty, + // it is derived from retention, which would turn "7d" into "1w" + spec string +} + +var _ RevisionCleanupStrategy = &durationDeletionRevisionCleanupStrategy{} + +func newDurationDeletionRevisionCleanupStrategy(retention time.Duration, truncateToMidnight bool) (RevisionCleanupStrategy, error) { + return &durationDeletionRevisionCleanupStrategy{ + retention: retention, + truncateToMidnight: truncateToMidnight, + }, nil +} + +func newDurationDeletionRevisionCleanupStrategyFromString(config string) (RevisionCleanupStrategy, error) { + if matches, duration, truncateToMidnight, err := durationFromConfig(config); !matches { + return nil, nil + } else if err != nil { + return nil, err + } else { + strategy, err := newDurationDeletionRevisionCleanupStrategy(duration, truncateToMidnight) + if err != nil { + return nil, err + } + strategy.(*durationDeletionRevisionCleanupStrategy).spec = strings.TrimSpace(config) + return strategy, nil + } +} + +func (s *durationDeletionRevisionCleanupStrategy) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + cutoff := computeCutoffFromRetention(now, -s.retention, s.truncateToMidnight) + spec := s.spec + if spec == "" { + spec = formatDurationSpec(s.retention, s.truncateToMidnight) + } + deleted := fmt.Sprintf("deleted by %q: older than %s", spec, formatTime(cutoff)) + retained := fmt.Sprintf("kept by %q: not older than %s", spec, formatTime(cutoff)) + plan := NewSimplePlan() + for _, rev := range revs { + if rev.CreationTime().Before(cutoff) { + plan.Delete(deleted, rev) + } else { + plan.Retain(retained, rev) + } + } + return plan, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_retention.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_retention.go new file mode 100644 index 0000000000..441120f9ca --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/cleanup_strategy_duration_retention.go @@ -0,0 +1,74 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/rs/zerolog" +) + +// A RevisionCleanupStrategy that retains files that are older than a given duration. +// +// With truncateToMidnight ("ND" or "NW" instead of "Nd" or "Nw"), the cutoff is aligned to +// local midnight instead of being exactly the duration before now, see computeCutoffFromRetention. +type durationRetentionRevisionCleanupStrategy struct { + retention time.Duration + truncateToMidnight bool + // spec is the duration as configured, e.g. "7d", for the reasons in the Plan; when empty, + // it is derived from retention, which would turn "7d" into "1w" + spec string +} + +var _ RevisionCleanupStrategy = &durationRetentionRevisionCleanupStrategy{} + +func newDurationRetentionRevisionCleanupStrategy(retention time.Duration, truncateToMidnight bool) (RevisionCleanupStrategy, error) { + return &durationRetentionRevisionCleanupStrategy{ + retention: retention, + truncateToMidnight: truncateToMidnight, + }, nil +} + +func newDurationRetentionRevisionCleanupStrategyFromString(config string) (RevisionCleanupStrategy, error) { + if matches, duration, truncateToMidnight, err := durationFromConfig(config); !matches { + return nil, nil + } else if err != nil { + return nil, err + } else { + strategy, err := newDurationRetentionRevisionCleanupStrategy(duration, truncateToMidnight) + if err != nil { + return nil, err + } + strategy.(*durationRetentionRevisionCleanupStrategy).spec = strings.TrimSpace(config) + return strategy, nil + } +} + +func (s *durationRetentionRevisionCleanupStrategy) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + cutoff := computeCutoffFromRetention(now, -s.retention, s.truncateToMidnight) + spec := s.spec + if spec == "" { + spec = formatDurationSpec(s.retention, s.truncateToMidnight) + } + safeguarded := fmt.Sprintf("protected by %q: newer than %s", spec, formatTime(cutoff)) + retained := fmt.Sprintf("not protected by %q: not newer than %s", spec, formatTime(cutoff)) + plan := NewSimplePlan() + for _, rev := range revs { + if rev.CreationTime().After(cutoff) { + // revision is younger than the cutoff time: + // do nothing in order to drop the revision from the revisions that + // need to be processed by following-up strategies + plan.Safeguard(safeguarded, rev) + } else { + // revision is older than the cutoff time: + // mark it for retention, in order to be processed by any + // strategy that comes next + plan.Retain(retained, rev) + } + } + return plan, nil +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model.go new file mode 100644 index 0000000000..9469071a37 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model.go @@ -0,0 +1,44 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "context" + "time" + + "github.com/rs/zerolog" +) + +type Revision interface { + Key() string + // CreationTime is when the revision was created, i.e. when its content was replaced, not + // the modification time of that content: the strategies order the revisions by it and + // measure their age from it, see revisioncleanup.revisionTimes. + CreationTime() time.Time + Size() uint64 +} + +// Plan is the outcome of a RevisionCleanupStrategy: which revisions to delete, which to +// retain (keep, or hand on to the next strategy of a chain) and which to safeguard (keep +// for sure). +// +// Every decision comes with a human readable reason, e.g. `deleted by "30d": older than +// 2026-09-14T10:00:00Z`, so that it can be explained why a revision was deleted or kept, +// in the debug log of the cleanup or in verbose output. The reasons name the rule in the +// syntax of the configuration and the concrete boundary it was evaluated with. +type Plan interface { + Delete(reason string, revs ...Revision) + Retain(reason string, revs ...Revision) + Safeguard(reason string, revs ...Revision) + Deleted() []Revision + Retained() []Revision + Safeguarded() []Revision + // Reason returns the reason for the decision about the revision with the given key, + // "" if the plan has no decision about it. + Reason(key string) string +} + +type RevisionCleanupStrategy interface { + Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model_simple.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model_simple.go new file mode 100644 index 0000000000..b6a97cc787 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/model_simple.go @@ -0,0 +1,59 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +type SimplePlan struct { + retained []Revision + deleted []Revision + safeguarded []Revision + reasons map[string]string // by revision key +} + +var _ Plan = &SimplePlan{} + +func NewSimplePlan() Plan { + return &SimplePlan{ + retained: []Revision{}, + deleted: []Revision{}, + safeguarded: []Revision{}, + reasons: map[string]string{}, + } +} + +func (p *SimplePlan) Delete(reason string, revs ...Revision) { + p.deleted = append(p.deleted, revs...) + p.setReason(reason, revs) +} + +func (p *SimplePlan) Retain(reason string, revs ...Revision) { + p.retained = append(p.retained, revs...) + p.setReason(reason, revs) +} + +func (p *SimplePlan) Safeguard(reason string, revs ...Revision) { + p.safeguarded = append(p.safeguarded, revs...) + p.setReason(reason, revs) +} + +func (p *SimplePlan) setReason(reason string, revs []Revision) { + for _, rev := range revs { + p.reasons[rev.Key()] = reason + } +} + +func (p *SimplePlan) Deleted() []Revision { + return p.deleted +} + +func (p *SimplePlan) Retained() []Revision { + return p.retained +} + +func (p *SimplePlan) Safeguarded() []Revision { + return p.safeguarded +} + +func (p *SimplePlan) Reason(key string) string { + return p.reasons[key] +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/registry.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/registry.go new file mode 100644 index 0000000000..724fefbf95 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/registry.go @@ -0,0 +1,298 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "fmt" + "regexp" + "strconv" + "strings" + "time" +) + +// valuePattern matches a single value X: a number of versions, or a duration with a unit +// suffix, where durations in days or weeks with an uppercase unit (D, W) are aligned to midnight. +const valuePattern = `\d+[wdhmsDW]?` + +var ( + configPatternAutoOnly = regexp.MustCompile(`^(auto)$`) + configPatternDeleteOnly = regexp.MustCompile(`^(` + valuePattern + `)$`) + configPatternSafeguardThenAuto = regexp.MustCompile(`^(` + valuePattern + `)\s*,\s*(auto)$`) + configPatternAutoThenDelete = regexp.MustCompile(`^(auto)\s*,\s*(` + valuePattern + `)$`) + configPatternSafeguardThenDelete = regexp.MustCompile(`^(` + valuePattern + `)\s*,\s*(` + valuePattern + `)$`) + configPatternSafeguardAutoAndDelete = regexp.MustCompile(`^(` + valuePattern + `)\s*,\s*(auto)\s*,\s*(` + valuePattern + `)$`) + + configPatternCount = regexp.MustCompile(`^\d+$`) +) + +// This is the entry point for instantiating a strategy that may be composed of multiple ones. +// +// The config parameter is a string that denotes which strategy/ies to use, as a comma separated +// list of specifications. +// +// Each X is either a plain number, which is a number of revisions, or a number with a unit +// suffix (w for weeks, d for days, h for hours, m for minutes, s for seconds), which is a +// duration. A number of revisions always refers to the newest revisions. +// +// A duration in days or weeks with an uppercase unit (D, W) is aligned to midnight in the server's +// local time zone: "1d" means the last 24 hours, while "1D" means since yesterday 00:00, so +// today and yesterday; "0D" means since today 00:00, and "1W" since 00:00 seven days ago. +// Depending on the time of day, "ND" thus spans between N and N+1 days. +// +// Supported forms: +// - "auto": Default, default clean-up pattern applies +// - "X": Delete all versions beyond X: keep the X newest versions, or delete versions +// that are older than X, without any further thinning +// "0" deletes all versions: unlike disabling versioning, which only stops new versions +// from being created, this also removes the versions that have accumulated so far. +// - "X, auto": Keeps versions within X, apply default clean-up pattern to all other versions +// - "auto, X": Delete all versions beyond X, apply the default clean-up pattern to the others +// - "X1, X2": Keep versions within X1 and delete versions beyond X2. X1 and X2 must be of +// different kinds, i.e. one number of versions and one duration, e.g. "5, 30d" (delete +// versions older than 30 days, but always keep the 5 newest) or "7d, 10" (keep at most +// 10 versions, but never delete versions younger than 7 days). +// Two values of the same kind are rejected, as one of them would have no effect: +// "5, 10" is the same as "10", and "7d, 30d" is the same as "30d". +// - "X1, auto, X2": Keep versions within X1, delete versions beyond X2, and apply the +// default clean-up pattern to the versions in between, e.g. "7d, auto, 90d". +// If X1 and X2 are of the same kind, X1 must be smaller than X2, otherwise the default +// clean-up pattern would never apply. +// +// "disabled" and an empty specification are not strategies: the callers handle them +// without parsing a strategy (see revisioncleanup.New), as there is nothing to plan. +// +// A deletion by number of versions is absolute: in "7d, 10" the versions younger than 7 +// days count towards the 10 versions to keep. +// +// In "auto, N" and "X1, auto, N", the number N applies before "auto", not after: "auto, 10" +// first deletes all but the 10 newest versions, and then thins out those 10, so it usually +// keeps fewer than 10, and possibly fewer than "auto" alone would. If the 10 newest versions +// were all saved within the same minute yesterday, "auto, 10" keeps a single version, while +// "auto" would keep one of them plus older ones. This is easily misread as "thin out first, +// then keep at most 10", which is not what it means. +// +// The age of a version, which durations are compared with, and the order of the versions are +// given by Revision.CreationTime: the time the version was created, i.e. when its content +// was replaced, by the clock of the server for the storage drivers, not the +// modification time of its content, which clients can choose (see +// revisioncleanup.revisionTimes). A version created today from content that was unchanged for +// two months is a few seconds old. +func NewRevisionCleanupStrategy(config string) (RevisionCleanupStrategy, error) { + config = strings.TrimSpace(config) + + // "auto": Default, default clean-up pattern applies + if m := configPatternAutoOnly.FindStringSubmatch(config); len(m) > 0 { + auto := m[1] + return newAutoRevisionCleanupStrategyFromString(auto) + } + + // "X": Delete all versions beyond X, no thinning + if m := configPatternDeleteOnly.FindStringSubmatch(config); len(m) > 0 { + return parseDelete(m[1]) + } + + // "X, auto": Keeps versions within X, apply default clean-up pattern to all other versions + if m := configPatternSafeguardThenAuto.FindStringSubmatch(config); len(m) > 0 { + return parseChain( + func() (RevisionCleanupStrategy, error) { return parseKeep(m[1]) }, + func() (RevisionCleanupStrategy, error) { return parseAuto(m[2]) }, + ) + } + + // "auto, X": Delete all versions beyond X, apply the default clean-up pattern to the others. + // The deletion comes first in the chain, so a number of versions is applied before the + // thinning, see the doc comment above. + if m := configPatternAutoThenDelete.FindStringSubmatch(config); len(m) > 0 { + return parseChain( + func() (RevisionCleanupStrategy, error) { return parseDelete(m[2]) }, + func() (RevisionCleanupStrategy, error) { return parseAuto(m[1]) }, + ) + } + + // "X1, X2": Keep versions within X1 and delete versions beyond X2 + if m := configPatternSafeguardThenDelete.FindStringSubmatch(config); len(m) > 0 { + keep, delete := m[1], m[2] + if sameKind(keep, delete) { + equivalent, err := sameKindEquivalent(keep, delete) + if err != nil { + return nil, err + } + return nil, fmt.Errorf("unsupported revision cleanup strategy specification %q: "+ + "%q and %q are both %s, so one of them has no effect and it is the same as %s; "+ + "combine a number of versions with a duration instead, e.g. \"5, 30d\" or \"7d, 10\"", + config, keep, delete, kindName(keep), equivalent) + } + return parseChain( + func() (RevisionCleanupStrategy, error) { return parseKeep(keep) }, + func() (RevisionCleanupStrategy, error) { return parseDelete(delete) }, + ) + } + + // "X1, auto, X2": Keep versions within X1, delete versions beyond X2, thin out the ones in between. + // As in "auto, X", a number of versions X2 is applied before the thinning. + if m := configPatternSafeguardAutoAndDelete.FindStringSubmatch(config); len(m) > 0 { + keep, auto, delete := m[1], m[2], m[3] + if sameKind(keep, delete) { + smaller, err := alwaysSmaller(keep, delete) + if err != nil { + return nil, err + } + if !smaller { + return nil, fmt.Errorf("unsupported revision cleanup strategy specification %q: "+ + "%q must be smaller than %q at any time of day, otherwise the default clean-up "+ + "pattern does not apply in between", config, keep, delete) + } + } + return parseChain( + func() (RevisionCleanupStrategy, error) { return parseKeep(keep) }, + func() (RevisionCleanupStrategy, error) { return parseDelete(delete) }, + func() (RevisionCleanupStrategy, error) { return parseAuto(auto) }, + ) + } + + return nil, fmt.Errorf("unsupported revision cleanup strategy specification %q", config) +} + +// parseChain parses the given strategies and chains them in that order. +func parseChain(parsers ...func() (RevisionCleanupStrategy, error)) (RevisionCleanupStrategy, error) { + chain := make([]RevisionCleanupStrategy, len(parsers)) + for i, parse := range parsers { + strategy, err := parse() + if err != nil { + return nil, err + } + chain[i] = strategy + } + return newChainRevisionCleanupStrategy(chain) +} + +// sameKind tells whether both values are numbers of versions, or both are durations. +func sameKind(a, b string) bool { + return configPatternCount.MatchString(a) == configPatternCount.MatchString(b) +} + +func kindName(value string) string { + if configPatternCount.MatchString(value) { + return "numbers of versions" + } + return "durations" +} + +// valueRange returns the smallest and the largest extent a value can have, as a number of +// versions for counts and in nanoseconds for durations. They are the same, except for durations +// aligned to midnight: "ND" covers between N days and just under N+1 days, depending on the +// time of day. +// +// A day counts as 24 hours here, although the days on which daylight saving time begins or ends +// have 23 or 25 hours. The comparisons based on it can therefore be off by up to an hour on those +// days, e.g. "1D, auto, 2d" is accepted, although "1D" can reach slightly beyond "2d" in the +// night after the clocks were set back. That is deliberate: rejecting such strategies for the +// sake of one hour a year would be worse, and during that hour, the versions in question are +// only kept, never deleted, as protecting them comes first in the chain. +func valueRange(value string) (int64, int64, error) { + if configPatternCount.MatchString(value) { + n, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return 0, 0, fmt.Errorf("invalid number of versions %q: %w", value, err) + } + return n, n, nil + } + truncated := strings.HasSuffix(value, "D") || strings.HasSuffix(value, "W") + d, err := parseDuration(strings.ToLower(value)) + if err != nil { + return 0, 0, err + } + if truncated { + return int64(d), int64(d + 24*time.Hour - 1), nil + } + return int64(d), int64(d), nil +} + +// alwaysSmaller tells whether a is smaller than b at any time of day (but see valueRange about +// daylight saving time). Both must be of the same kind. Values that only reach each other at a +// single instant count as smaller, e.g. "1d" and "1D", which are equal only at midnight; values +// that are always equal, e.g. "1w" and "7d", don't. +func alwaysSmaller(a, b string) (bool, error) { + aMin, aMax, err := valueRange(a) + if err != nil { + return false, err + } + bMin, bMax, err := valueRange(b) + if err != nil { + return false, err + } + return aMax < bMin || (aMax == bMin && (aMin < aMax || bMin < bMax)), nil +} + +// sameKindEquivalent describes what an "X1, X2" pair of values of the same kind is equivalent to: +// the larger of the two, as the smaller one has no effect. If the order depends on the time of +// day, as with "1D, 30h", it is the larger of the two at any given moment. +func sameKindEquivalent(a, b string) (string, error) { + aMin, aMax, err := valueRange(a) + if err != nil { + return "", err + } + bMin, bMax, err := valueRange(b) + if err != nil { + return "", err + } + // a value that is never larger than the other one has no effect: "1d" is never larger than + // "1D", so "1d, 1D" and "1D, 1d" are both the same as "1D" + switch { + case aMax <= bMin: + return fmt.Sprintf("%q", b), nil + case bMax <= aMin, aMin == bMin && aMax == bMax: + return fmt.Sprintf("%q", a), nil + default: + return fmt.Sprintf("%q or %q, depending on the time of day", a, b), nil + } +} + +func parseKeep(retain string) (RevisionCleanupStrategy, error) { + strategy, err := newDurationRetentionRevisionCleanupStrategyFromString(retain) + if err != nil { + return nil, err + } + if strategy != nil { + return strategy, nil + } + strategy, err = newCountRetentionRevisionCleanupStrategyFromString(retain) + if err != nil { + return nil, err + } + if strategy != nil { + return strategy, nil + } + // doesn't match either + return nil, fmt.Errorf("unsupported revision safeguarding specification %q", retain) +} + +func parseDelete(delete string) (RevisionCleanupStrategy, error) { + strategy, err := newDurationDeletionRevisionCleanupStrategyFromString(delete) + if err != nil { + return nil, err + } + if strategy != nil { + return strategy, nil + } + strategy, err = newCountDeletionRevisionCleanupStrategyFromString(delete) + if err != nil { + return nil, err + } + if strategy != nil { + return strategy, nil + } + // doesn't match either + return nil, fmt.Errorf("unsupported revision deletion specification %q", delete) +} + +func parseAuto(auto string) (RevisionCleanupStrategy, error) { + if strategy, err := newAutoRevisionCleanupStrategyFromString(auto); err != nil { + return nil, err + } else if strategy != nil { + return strategy, nil + } else { + return nil, fmt.Errorf("unsupported revision 'auto' specification %q", auto) + } +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/utils.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/utils.go new file mode 100644 index 0000000000..a4700e9bc4 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/revisions/utils.go @@ -0,0 +1,307 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package revisions + +import ( + "cmp" + "context" + "errors" + "fmt" + "math" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "github.com/rs/zerolog" +) + +// Compares two Revisions, newest first. +// +// Revisions with the same time are told apart by their keys, so that the order, and with it +// which of them a strategy keeps, never depends on the order they were listed in. When the +// posix driver creates a revision whose key is already taken, it renames the existing +// revision to ".", with N one higher than any existing suffix, and creates the new +// one under the plain key. The plain key is therefore the newest, followed by the suffixed +// ones from the highest N down. +func CompareNewestFirst[T Revision](a, b T) int { + if c := b.CreationTime().Compare(a.CreationTime()); c != 0 { + return c + } + if c := cmp.Compare(collisionRank(b.Key()), collisionRank(a.Key())); c != 0 { + return c + } + return strings.Compare(a.Key(), b.Key()) +} + +// collisionRank ranks revisions with the same time, see CompareNewestFirst: the higher, the +// newer. A key ending in "." ranks N, any other key ranks above all of those. A timestamp +// ending in fractions of a second ("...05.123Z") is not mistaken for a suffix, as it ends in +// "Z" or a time zone offset. +func collisionRank(key string) int { + i := strings.LastIndexByte(key, '.') + if i < 0 { + return math.MaxInt + } + n, err := strconv.Atoi(key[i+1:]) + if err != nil || n < 0 { + return math.MaxInt + } + return n +} + +// Sorts a slice of Revisions canonically: newest first. +func SortRevisionsCanonically[T Revision](revisions []T) { + slices.SortFunc(revisions, CompareNewestFirst) +} + +// CleanupStrategyFunc is an adapter to use an ordinary function as a RevisionCleanupStrategy, +// like http.HandlerFunc: CleanupStrategyFunc(f) is a RevisionCleanupStrategy that calls f. +type CleanupStrategyFunc func(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) + +var _ RevisionCleanupStrategy = CleanupStrategyFunc(nil) + +// Cleanup calls f(now, revs, ctx, logger). +func (f CleanupStrategyFunc) Cleanup(now time.Time, revs []Revision, ctx context.Context, logger *zerolog.Logger) (Plan, error) { + return f(now, revs, ctx, logger) +} + +// Takes a RevisionCleanupStrategy and acts as a glue to piece everything together, +// except the deletion of Revisions itself, that it delegates to the cleanup function +// that is passed as a parameter, together with the reason the strategy gave for deleting +// the revision (see Plan). +// +// It returns the Plan of the strategy, so that callers can report on all revisions, also +// the ones that were kept or protected, together with the errors of the cleanup function. +// The Plan is nil if the strategy failed. +// +// Note that this implementation is assuming that it is used in a single-threaded +// fashion as it does not perform any locking of anything. +func ExecuteCleanupStrategy(now time.Time, strategy RevisionCleanupStrategy, revs []Revision, ctx context.Context, logger *zerolog.Logger, + cleanup func(rev Revision, reason string) error, +) (Plan, error) { + revs = slices.Clone(revs) + SortRevisionsCanonically(revs) + + plan, err := strategy.Cleanup(now, revs, ctx, logger) + if err != nil { + return nil, err + } + plan = withFutureDates(plan, revs, now, logger) + + deleted := plan.Deleted() + + errs := make([]error, len(deleted)) + for i, rev := range deleted { + err := cleanup(rev, plan.Reason(rev.Key())) + errs[i] = err + } + return plan, errors.Join(errs...) +} + +var ( + durationParserRegex = regexp.MustCompile(`^(\d+)([wdhms])$`) +) + +func parseDuration(s string) (time.Duration, error) { + s = strings.TrimSpace(s) + m := durationParserRegex.FindStringSubmatch(s) + if len(m) < 1 { + return 0, fmt.Errorf("invalid duration number: %q", s) + } + value := m[1] + unit := m[2] + + n, err := strconv.Atoi(value) + if err != nil { + return 0, fmt.Errorf("invalid duration number: %w", err) + } + + var u time.Duration + switch unit { + case "w": + u = 7 * 24 * time.Hour + case "d": + u = 24 * time.Hour + case "h": + u = time.Hour + case "m": + u = time.Minute + case "s": + u = time.Second + default: + return 0, fmt.Errorf("unknown duration unit: %q", unit) + } + // A time.Duration holds at most about 292 years. Beyond that the multiplication would + // silently overflow, e.g. into a negative duration, which would put the cutoff into the + // future and delete all revisions instead of keeping them. + if limit := int64(math.MaxInt64 / u); int64(n) > limit { + return 0, fmt.Errorf("duration %q is too large, at most %d%s is supported", s, limit, unit) + } + return time.Duration(n) * u, nil +} + +var ( + // A duration: a number with a unit suffix (w, d, h, m, s). Durations in days or weeks + // with an uppercase unit (D, W) align the cutoff to midnight (see computeCutoffFromRetention). + durationSpec = regexp.MustCompile(`^\d+[wdhmsDW]$`) +) + +func durationFromConfig(config string) (bool, time.Duration, bool, error) { + config = strings.TrimSpace(config) + if !durationSpec.MatchString(config) { + return false, 0, false, nil + } + + truncateToMidnight := false + if unit := config[len(config)-1]; unit == 'D' || unit == 'W' { + config = strings.ToLower(config) + truncateToMidnight = true + } + + duration, err := parseDuration(config) + if err != nil { + return true, 0, false, err + } + + return true, duration, truncateToMidnight, nil +} + +// computeCutoffFromRetention computes the point in time that separates the revisions within a +// duration from the ones beyond it. d is the negative duration, e.g. -48h for "2d". +// +// With truncateToMidnight, the cutoff is aligned to midnight in the time zone of now (the server's +// local time zone in practice): it is today's midnight minus the given number of days, so "0D" +// means "since today 00:00", "1D" "since yesterday 00:00" and "1W" "since 00:00 seven days ago" +// (not since the start of the calendar week). Calendar arithmetic is used rather than subtracting +// d, so that the cutoff is exactly at midnight also across daylight saving time changes. +// Only durations in days or weeks can be truncated to midnight (see durationSpec), so d is always +// a multiple of 24h in that case. +func computeCutoffFromRetention(now time.Time, d time.Duration, truncateToMidnight bool) time.Time { + if truncateToMidnight { + year, month, day := now.Date() + midnight := time.Date(year, month, day, 0, 0, 0, 0, now.Location()) + return midnight.AddDate(0, 0, int(d/(24*time.Hour))) + } + return now.Add(d) +} + +var ( + countConfigFormat = regexp.MustCompile(`^(\d+)$`) +) + +func countFromConfig(config string) (bool, int, error) { + if m := countConfigFormat.FindStringSubmatch(config); len(m) > 1 { + if maxVersionsPerFile, err := strconv.Atoi(m[1]); err != nil { + return true, 0, err + } else if maxVersionsPerFile < 0 { + return true, 0, fmt.Errorf("invalid value for maxVersionsPerFile: %q", m[1]) + } else { + return true, maxVersionsPerFile, nil + } + } else { + return false, 0, nil + } +} + +const ( + day = 24 * time.Hour + week = 7 * day +) + +// formatDurationSpec renders a duration in the syntax of the configuration, e.g. "7d", "2w" or +// "1D" when aligned to midnight, for the reasons in a Plan. +func formatDurationSpec(d time.Duration, truncateToMidnight bool) string { + var spec string + switch { + case d == 0 && truncateToMidnight: + spec = "0d" + case d == 0: + spec = "0s" + case d%week == 0: + spec = fmt.Sprintf("%dw", d/week) + case d%day == 0: + spec = fmt.Sprintf("%dd", d/day) + case d%time.Hour == 0: + spec = fmt.Sprintf("%dh", d/time.Hour) + case d%time.Minute == 0: + spec = fmt.Sprintf("%dm", d/time.Minute) + default: + spec = fmt.Sprintf("%ds", d/time.Second) + } + if truncateToMidnight { + spec = strings.ToUpper(spec) + } + return spec +} + +// humanDuration renders a duration in words, e.g. "1 minute" or "10 seconds", for the +// reasons in a Plan. +func humanDuration(d time.Duration) string { + unit := func(n time.Duration, name string) string { + if n == 1 { + return "1 " + name + } + return fmt.Sprintf("%d %ss", n, name) + } + switch { + case d >= week && d%week == 0: + return unit(d/week, "week") + case d >= day && d%day == 0: + return unit(d/day, "day") + case d >= time.Hour && d%time.Hour == 0: + return unit(d/time.Hour, "hour") + case d >= time.Minute && d%time.Minute == 0: + return unit(d/time.Minute, "minute") + case d >= time.Second && d%time.Second == 0: + return unit(d/time.Second, "second") + default: + return d.String() + } +} + +// formatTime renders a point in time for the reasons in a Plan. +func formatTime(t time.Time) string { + return t.Format(time.RFC3339) +} + +// withFutureDates points out the revisions dated in the future in the reasons of plan, and +// logs a warning about each of them. +// +// For the storage drivers, a revision's time is when it was created, by the clock of the server +// (see revisioncleanup.revisionTimes), so this only happens when that clock was set back, e.g. +// after it was ahead. A revision dated in the future counts as the newest one: it takes the +// first places of a number of versions to keep, and no duration deletes it before its date has +// passed. That is kept as it is, but made visible, so that the admin can look into the clock. +func withFutureDates(plan Plan, revs []Revision, now time.Time, logger *zerolog.Logger) Plan { + future := map[string]time.Time{} + for _, rev := range revs { + if t := rev.CreationTime(); t.After(now) { + future[rev.Key()] = t + if logger != nil { + logger.Warn().Str("revision", rev.Key()).Time("time", t). + Msg("revision cleanup: revision dated in the future, it counts as the newest one") + } + } + } + if len(future) == 0 { + return plan + } + return &futureDatesPlan{Plan: plan, future: future} +} + +// futureDatesPlan adds a note to the reasons of the revisions dated in the future. +type futureDatesPlan struct { + Plan + future map[string]time.Time +} + +func (p *futureDatesPlan) Reason(key string) string { + reason := p.Plan.Reason(key) + if t, ok := p.future[key]; ok && reason != "" { + reason += fmt.Sprintf("; dated in the future (%s), so it counts as the newest", formatTime(t)) + } + return reason +} diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/uploads.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/uploads.go index 01fd08e83f..c30923714c 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/uploads.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/uploads.go @@ -68,6 +68,17 @@ type NodeCreator interface { PrepareCreatesNode() bool } +// UploadFinishedHandler defines the interface for FS implementations that act once an +// upload has finished: its content is committed and the node no longer marked as being +// processed by it. The coordinator calls it for every successful upload, inline or after +// postprocessing, never for one that was rolled back. +type UploadFinishedHandler interface { + // HandleUploadFinished is called once the upload sessionID to ref has finished. + // versionCreated reports whether the upload superseded existing content, keeping it + // as a revision. It must not fail the upload, so it returns nothing. + HandleUploadFinished(ctx context.Context, ref *provider.Reference, sessionID string, versionCreated bool) +} + // UploadSession is the interface that storage drivers need to return whan listing upload sessions. type UploadSession interface { // ID returns the upload id diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/utils/middleware/middleware.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/utils/middleware/middleware.go index 348b691799..e6c7607596 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/utils/middleware/middleware.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/storage/utils/middleware/middleware.go @@ -67,6 +67,14 @@ func (f *FS) PrepareCreatesNode() bool { nc, ok := f.next.(storage.NodeCreator) return ok && nc.PrepareCreatesNode() } + +// HandleUploadFinished passes the end of an upload on to the wrapped driver, if it +// handles it, see storage.UploadFinishedHandler. +func (f *FS) HandleUploadFinished(ctx context.Context, ref *provider.Reference, sessionID string, versionCreated bool) { + if h, ok := f.next.(storage.UploadFinishedHandler); ok { + h.HandleUploadFinished(ctx, ref, sessionID, versionCreated) + } +} func (f *FS) GetHome(ctx context.Context) (string, error) { var ( err error diff --git a/vendor/github.com/opencloud-eu/reva/v3/pkg/upload/coordinator.go b/vendor/github.com/opencloud-eu/reva/v3/pkg/upload/coordinator.go index b0d0390fcb..5e48ff3998 100644 --- a/vendor/github.com/opencloud-eu/reva/v3/pkg/upload/coordinator.go +++ b/vendor/github.com/opencloud-eu/reva/v3/pkg/upload/coordinator.go @@ -666,6 +666,11 @@ func (c *coordinator) finished(ctx context.Context, session Session) *provider.R session.Cleanup(ctx, true, true) metrics.UploadSessionsFinalized.Inc() + if h, ok := c.fs.(storage.UploadFinishedHandler); ok { + ref := session.Reference() + h.HandleUploadFinished(ctx, &ref, session.ID(), session.VersionCreated()) + } + ri := c.uploadedResourceInfo(ctx, session) c.publishUploadReady(ctx, session, ri) return ri diff --git a/vendor/modules.txt b/vendor/modules.txt index 44ba192516..df45f97848 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1360,7 +1360,7 @@ github.com/opencloud-eu/icap-client # github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 ## explicit; go 1.23 github.com/opencloud-eu/libre-graph-api-go -# github.com/opencloud-eu/reva/v3 v3.0.2-0.20261117134925-37496dc6abd3 +# github.com/opencloud-eu/reva/v3 v3.0.2-0.20261119121328-0093d72f4c9d ## explicit; go 1.26.0 github.com/opencloud-eu/reva/v3/cmd/revad/internal/grace github.com/opencloud-eu/reva/v3/cmd/revad/runtime @@ -1646,6 +1646,7 @@ github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/mtimesyncedcache github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/node github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/permissions +github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/spaceidindex github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/timemanager github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/trashbin @@ -1656,6 +1657,7 @@ github.com/opencloud-eu/reva/v3/pkg/storage/registry/loader github.com/opencloud-eu/reva/v3/pkg/storage/registry/registry github.com/opencloud-eu/reva/v3/pkg/storage/registry/spaces github.com/opencloud-eu/reva/v3/pkg/storage/registry/static +github.com/opencloud-eu/reva/v3/pkg/storage/revisions github.com/opencloud-eu/reva/v3/pkg/storage/utils/ace github.com/opencloud-eu/reva/v3/pkg/storage/utils/acl github.com/opencloud-eu/reva/v3/pkg/storage/utils/chunking