chore(OCISDEV-900): bump reva to pr7-switchover, add upload_directory and mount_id to revaconfig
- bump github.com/owncloud/reva/v2 to 4717d97b0e (OCISDEV-900-pr7-switchover) - set upload_directory in OCM dataprovider and storageprovider revaconfig - add mount_id to storage-users dataprovider revaconfig
This commit is contained in:
1 parent
3fe6545ffd
commit
0197ab199d
30 files changed
+2307
-1311
No files matched your search
@@ -67,7 +67,7 @@ require (
|
||||
github.com/open-policy-agent/opa v1.19.0
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260917145219-ba14a94a3c7a
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260916115339-d8ba9085f572
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
|
||||
@@ -736,8 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260917145219-ba14a94a3c7a h1:QnKAz6PPmeMgF+w5UJ70InpsrtUeW/6GX+ikkb61XVs=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260917145219-ba14a94a3c7a/go.mod h1:VohDRQV33rVDiofWNngHqQK7tsgtYJpQBNWsn41j/LM=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260916115339-d8ba9085f572 h1:3mo2qYum2yUHDKvMDnFVO1l4tiKYkfeuqkLvc12LeBc=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260916115339-d8ba9085f572/go.mod h1:VohDRQV33rVDiofWNngHqQK7tsgtYJpQBNWsn41j/LM=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
|
||||
|
||||
@@ -3,6 +3,7 @@ package revaconfig
|
||||
import (
|
||||
"math"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/cors"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
@@ -100,8 +101,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
|
||||
"service_account_secret": cfg.ServiceAccount.Secret,
|
||||
},
|
||||
"dataprovider": map[string]interface{}{
|
||||
"prefix": "data",
|
||||
"driver": "ocmreceived",
|
||||
"prefix": "data",
|
||||
"driver": "ocmreceived",
|
||||
"upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"),
|
||||
"drivers": map[string]interface{}{
|
||||
"ocmreceived": map[string]interface{}{
|
||||
"insecure": cfg.OCMStorageProvider.Insecure,
|
||||
@@ -190,7 +192,8 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
|
||||
},
|
||||
},
|
||||
"storageprovider": map[string]interface{}{
|
||||
"driver": "ocmreceived",
|
||||
"driver": "ocmreceived",
|
||||
"upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"),
|
||||
"drivers": map[string]interface{}{
|
||||
"ocmreceived": map[string]interface{}{
|
||||
"insecure": cfg.OCMStorageProvider.Insecure,
|
||||
|
||||
@@ -87,6 +87,7 @@ func StorageUsersConfigFromStruct(cfg *config.Config) map[string]interface{} {
|
||||
"prefix": cfg.HTTP.Prefix,
|
||||
"driver": cfg.Driver,
|
||||
"drivers": DataProviderDrivers(cfg),
|
||||
"mount_id": cfg.MountID,
|
||||
"nats_address": cfg.Events.Addr,
|
||||
"nats_clusterID": cfg.Events.ClusterID,
|
||||
"nats_tls_insecure": cfg.Events.TLSInsecure,
|
||||
|
||||
Generated
Vendored
+20
-8
@@ -47,6 +47,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/upload"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
@@ -71,6 +72,7 @@ type config struct {
|
||||
MountID string `mapstructure:"mount_id"`
|
||||
UploadExpiration int64 `mapstructure:"upload_expiration" docs:"0;Duration for how long uploads will be valid."`
|
||||
Events eventconfig `mapstructure:"events" docs:"0;Event stream configuration"`
|
||||
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
|
||||
}
|
||||
|
||||
type eventconfig struct {
|
||||
@@ -106,6 +108,7 @@ func (c *config) init() {
|
||||
type Service struct {
|
||||
conf *config
|
||||
Storage storage.FS
|
||||
Coordinator upload.Coordinator
|
||||
dataServerURL *url.URL
|
||||
availableXS []*provider.ResourceChecksumPriority
|
||||
}
|
||||
@@ -175,7 +178,14 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
|
||||
|
||||
c.init()
|
||||
|
||||
fs, err := getFS(c, log)
|
||||
// One stream for both the driver and the coordinator: a second one would open a
|
||||
// second nats connection for the same events.
|
||||
evstream, err := estreamFromConfig(c.Events)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fs, err := getFS(c, evstream, log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -202,9 +212,16 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// storageprovider only initiates uploads; the data path assembles chunks, so no chunking here.
|
||||
coord, err := upload.NewCoordinatorFromConfig(c.UploadDirectory, c.Drivers[c.Driver], fs, evstream, log, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("storageprovider: %w", err)
|
||||
}
|
||||
|
||||
service := &Service{
|
||||
conf: c,
|
||||
Storage: fs,
|
||||
Coordinator: coord,
|
||||
dataServerURL: u,
|
||||
availableXS: xsTypes,
|
||||
}
|
||||
@@ -423,7 +440,7 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
|
||||
metadata["expires"] = strconv.Itoa(int(expirationTimestamp.Seconds))
|
||||
}
|
||||
|
||||
uploadIDs, err := s.Storage.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
|
||||
uploadIDs, err := s.Coordinator.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
|
||||
if err != nil {
|
||||
var st *rpc.Status
|
||||
switch err.(type) {
|
||||
@@ -1305,12 +1322,7 @@ func (s *Service) addMissingStorageProviderID(resourceID *provider.ResourceId, s
|
||||
}
|
||||
}
|
||||
|
||||
func getFS(c *config, log *zerolog.Logger) (storage.FS, error) {
|
||||
evstream, err := estreamFromConfig(c.Events)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func getFS(c *config, evstream events.Stream, log *zerolog.Logger) (storage.FS, error) {
|
||||
if f, ok := registry.NewFuncs[c.Driver]; ok {
|
||||
driverConf := c.Drivers[c.Driver]
|
||||
driverConf["mount_id"] = c.MountID // pass the mount id to the driver
|
||||
|
||||
Generated
Vendored
+19
-3
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/router"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/upload"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -51,6 +52,7 @@ type config struct {
|
||||
NatsEnableTLS bool `mapstructure:"nats_enable_tls"`
|
||||
NatsUsername string `mapstructure:"nats_username"`
|
||||
NatsPassword string `mapstructure:"nats_password"`
|
||||
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
|
||||
}
|
||||
|
||||
func (c *config) init() {
|
||||
@@ -104,7 +106,21 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dataTXs, err := getDataTXs(conf, fs, evstream, log)
|
||||
// the data path assembles chunks, so enable chunking
|
||||
coord, err := upload.NewCoordinatorFromConfig(conf.UploadDirectory, conf.Drivers[conf.Driver], fs, evstream, log, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dataprovider: %w", err)
|
||||
}
|
||||
|
||||
// only the data path consumes postprocessing results: one consumer group gets
|
||||
// one copy of each event, so a second subscriber would take half of them
|
||||
if ac := upload.AsyncConfFromDriverConf(conf.Drivers[conf.Driver]); ac.Enabled {
|
||||
if err := coord.StartPostprocessing(evstream, ac.ConsumerGroup, ac.MountID, ac.NumConsumers); err != nil {
|
||||
return nil, fmt.Errorf("dataprovider: could not start postprocessing: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
dataTXs, err := getDataTXs(conf, coord, fs, evstream, log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -126,7 +142,7 @@ func getFS(c *config, stream events.Stream, log *zerolog.Logger) (storage.FS, er
|
||||
return nil, fmt.Errorf("driver not found: %s", c.Driver)
|
||||
}
|
||||
|
||||
func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
|
||||
func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
|
||||
if c.DataTXs == nil {
|
||||
c.DataTXs = make(map[string]map[string]interface{})
|
||||
}
|
||||
@@ -146,7 +162,7 @@ func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerol
|
||||
for t := range c.DataTXs {
|
||||
if f, ok := datatxregistry.NewFuncs[t]; ok {
|
||||
if tx, err := f(c.DataTXs[t], publisher, log); err == nil {
|
||||
if handler, err := tx.Handler(fs); err == nil {
|
||||
if handler, err := tx.Handler(coord, fs); err == nil {
|
||||
txs[t] = handler
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -319,7 +319,8 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http.
|
||||
sReq.Ref.Path = uReq.Ref.GetPath()
|
||||
sReq.Ref.ResourceId = nil
|
||||
} else {
|
||||
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil {
|
||||
// new files have no node id yet; keep the path-based ref instead
|
||||
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil && resid.GetOpaqueId() != "" {
|
||||
sReq.Ref = &provider.Reference{
|
||||
ResourceId: &resid,
|
||||
}
|
||||
|
||||
+4
-1
@@ -28,12 +28,15 @@ import (
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/upload"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
// DataTX provides an abstraction around various data transfer protocols.
|
||||
type DataTX interface {
|
||||
Handler(fs storage.FS) (http.Handler, error)
|
||||
// Handler serves the protocol's data path. Uploads go through coord, which
|
||||
// owns the upload lifecycle for every driver; downloads read from driver.
|
||||
Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error)
|
||||
}
|
||||
|
||||
// EmitFileUploadedEvent is a helper function which publishes a FileUploaded event
|
||||
|
||||
+5
-4
@@ -24,8 +24,8 @@ import (
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
@@ -40,6 +40,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/cache"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/upload"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
@@ -78,7 +79,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) {
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sublog := m.log.With().Str("path", r.URL.Path).Logger()
|
||||
r = r.WithContext(appctx.WithLogger(r.Context(), &sublog))
|
||||
@@ -92,7 +93,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
metrics.DownloadsActive.Sub(1)
|
||||
}()
|
||||
}
|
||||
download.GetOrHeadFile(w, r, fs, "")
|
||||
download.GetOrHeadFile(w, r, driver, "")
|
||||
case "PUT":
|
||||
metrics.UploadsActive.Add(1)
|
||||
defer func() {
|
||||
@@ -114,7 +115,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
ctx = ctxpkg.ContextSetLockID(ctx, lockID)
|
||||
}
|
||||
|
||||
info, err := fs.Upload(ctx, storage.UploadRequest{
|
||||
info, err := coord.Upload(ctx, storage.UploadRequest{
|
||||
Ref: ref,
|
||||
Body: r.Body,
|
||||
Length: r.ContentLength,
|
||||
|
||||
+4
-3
@@ -42,6 +42,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/cache"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/upload"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
@@ -80,7 +81,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) {
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var spaceID string
|
||||
spaceID, r.URL.Path = router.ShiftPath(r.URL.Path)
|
||||
@@ -97,7 +98,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
metrics.DownloadsActive.Sub(1)
|
||||
}()
|
||||
}
|
||||
download.GetOrHeadFile(w, r, fs, spaceID)
|
||||
download.GetOrHeadFile(w, r, driver, spaceID)
|
||||
case "PUT":
|
||||
metrics.UploadsActive.Add(1)
|
||||
defer func() {
|
||||
@@ -117,7 +118,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
Path: fn,
|
||||
}
|
||||
var info *provider.ResourceInfo
|
||||
info, err = fs.Upload(ctx, storage.UploadRequest{
|
||||
info, err = coord.Upload(ctx, storage.UploadRequest{
|
||||
Ref: ref,
|
||||
Body: r.Body,
|
||||
Length: r.ContentLength,
|
||||
|
||||
+34
-45
@@ -33,13 +33,13 @@ import (
|
||||
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/datatx"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/manager/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/upload"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -87,20 +87,14 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
composable, ok := fs.(storage.ComposableFS)
|
||||
if !ok {
|
||||
return nil, errtypes.NotSupported("file system does not support the tus protocol")
|
||||
}
|
||||
|
||||
func (m *manager) Handler(coord upload.Coordinator, _ storage.FS) (http.Handler, error) {
|
||||
// A storage backend for tusd may consist of multiple different parts which
|
||||
// handle upload creation, locking, termination and so on. The composer is a
|
||||
// place where all those separated pieces are joined together. In this example
|
||||
// we only use the file store but you may plug in multiple.
|
||||
// place where all those separated pieces are joined together.
|
||||
composer := tusd.NewStoreComposer()
|
||||
|
||||
// let the composable storage tell tus which extensions it supports
|
||||
composable.UseIn(composer)
|
||||
// the coordinator serves the tus protocol on behalf of every driver
|
||||
coord.UseIn(composer)
|
||||
|
||||
config := tusd.Config{
|
||||
StoreComposer: composer,
|
||||
@@ -130,33 +124,29 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if usl, ok := fs.(storage.UploadSessionLister); ok {
|
||||
// We can currently only send updates if the fs is decomposedfs as we read very specific keys from the storage map of the tus info
|
||||
go func() {
|
||||
for {
|
||||
ev := <-handler.CompleteUploads
|
||||
// We should be able to get the upload progress with fs.GetUploadProgress, but currently tus will erase the info files
|
||||
// so we create a Progress instance here that is used to read the correct properties
|
||||
ups, err := usl.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
|
||||
if err != nil {
|
||||
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
|
||||
} else {
|
||||
if len(ups) < 1 {
|
||||
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
|
||||
continue
|
||||
}
|
||||
up := ups[0]
|
||||
executant := up.Executant()
|
||||
ref := up.Reference()
|
||||
if m.publisher != nil {
|
||||
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
|
||||
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
ev := <-handler.CompleteUploads
|
||||
// tus erases its info files, so read the session back for the event's properties
|
||||
ups, err := coord.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
|
||||
if err != nil {
|
||||
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
|
||||
continue
|
||||
}
|
||||
if len(ups) < 1 {
|
||||
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
|
||||
continue
|
||||
}
|
||||
up := ups[0]
|
||||
executant := up.Executant()
|
||||
ref := up.Reference()
|
||||
if m.publisher != nil {
|
||||
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
|
||||
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
h := handler.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sublog := m.log.With().Str("uploadid", r.URL.Path).Logger()
|
||||
@@ -174,7 +164,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
metrics.UploadsActive.Sub(1)
|
||||
}()
|
||||
// set etag, mtime and file id
|
||||
setHeaders(fs, w, r)
|
||||
setHeaders(coord, w, r)
|
||||
handler.PostFile(w, r)
|
||||
case "HEAD":
|
||||
handler.HeadFile(w, r)
|
||||
@@ -184,7 +174,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
metrics.UploadsActive.Sub(1)
|
||||
}()
|
||||
// set etag, mtime and file id
|
||||
setHeaders(fs, w, r)
|
||||
setHeaders(coord, w, r)
|
||||
handler.PatchFile(w, r)
|
||||
case "DELETE":
|
||||
handler.DelFile(w, r)
|
||||
@@ -205,15 +195,10 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
|
||||
return h, nil
|
||||
}
|
||||
|
||||
func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
|
||||
func setHeaders(coord upload.Coordinator, w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
id := path.Base(r.URL.Path)
|
||||
datastore, ok := fs.(tusd.DataStore)
|
||||
if !ok {
|
||||
appctx.GetLogger(ctx).Error().Interface("fs", fs).Msg("storage is not a tus datastore")
|
||||
return
|
||||
}
|
||||
upload, err := datastore.GetUpload(ctx, id)
|
||||
upload, err := coord.GetUpload(ctx, id)
|
||||
if err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Msg("could not get upload from storage")
|
||||
return
|
||||
@@ -227,6 +212,10 @@ func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
|
||||
if expires != "" {
|
||||
w.Header().Set(net.HeaderTusUploadExpires, expires)
|
||||
}
|
||||
// the node id is only valid once the upload commits; skip the header for new files
|
||||
if info.Storage["NodeExists"] != "true" {
|
||||
return
|
||||
}
|
||||
resourceid := &provider.ResourceId{
|
||||
StorageId: info.MetaData["providerID"],
|
||||
SpaceId: info.Storage["SpaceRoot"],
|
||||
|
||||
-5
@@ -42,11 +42,6 @@ var (
|
||||
Name: "reva_upload_sessions_aborted",
|
||||
Help: "Number of uploads sessions that have aborted by postprocessing",
|
||||
})
|
||||
// UploadSessionsCommitFailed is the number of upload sessions whose blob commit failed after retries and were reverted
|
||||
UploadSessionsCommitFailed = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "reva_upload_sessions_commit_failed",
|
||||
Help: "Number of upload sessions whose blob commit failed after retries and were reverted",
|
||||
})
|
||||
// UploadSessionsDeleted is the number of upload sessions that have been deleted
|
||||
UploadSessionsDeleted = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "reva_upload_sessions_deleted",
|
||||
|
||||
+58
-406
@@ -1,21 +1,14 @@
|
||||
package kiteworks
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
@@ -46,8 +39,6 @@ type Driver struct {
|
||||
apiToken string
|
||||
storageID string
|
||||
log zerolog.Logger
|
||||
// TODO: lock tokens are ephemeral; lost on restart and not shared across nodes.
|
||||
locks sync.Map // nodeID → *provider.Lock
|
||||
}
|
||||
|
||||
// New returns a read-only Kiteworks storage driver.
|
||||
@@ -92,30 +83,22 @@ func (d *Driver) toResourceInfo(fi *kwlib.FileInfo, spaceID, spaceRootPath strin
|
||||
if !strings.HasPrefix(relPath, "/") {
|
||||
relPath = "/" + relPath
|
||||
}
|
||||
spaceRoot := &provider.ResourceId{
|
||||
StorageId: d.storageID,
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: spaceID,
|
||||
}
|
||||
ri := &provider.ResourceInfo{
|
||||
Id: &provider.ResourceId{
|
||||
StorageId: d.storageID,
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: fi.ID,
|
||||
},
|
||||
Space: &provider.StorageSpace{Root: spaceRoot},
|
||||
Name: fi.Name,
|
||||
Path: relPath,
|
||||
Etag: fi.ETag(),
|
||||
Mtime: utils.TimeToTS(fi.MTime()),
|
||||
PermissionSet: permissionSet(fi),
|
||||
}
|
||||
if fi.ParentID != nil && *fi.ParentID != "" && *fi.ParentID != "0" {
|
||||
ri.ParentId = &provider.ResourceId{
|
||||
StorageId: d.storageID,
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: *fi.ParentID,
|
||||
}
|
||||
Name: fi.Name,
|
||||
Path: relPath,
|
||||
Etag: fi.ETag(),
|
||||
Mtime: utils.TimeToTS(fi.MTime()),
|
||||
PermissionSet: &provider.ResourcePermissions{
|
||||
Stat: true,
|
||||
GetPath: true,
|
||||
InitiateFileDownload: fi.IsFile(),
|
||||
ListContainer: fi.IsDir(),
|
||||
},
|
||||
}
|
||||
if fi.IsDir() {
|
||||
ri.Type = provider.ResourceType_RESOURCE_TYPE_CONTAINER
|
||||
@@ -129,17 +112,11 @@ func (d *Driver) toResourceInfo(fi *kwlib.FileInfo, spaceID, spaceRootPath strin
|
||||
return ri
|
||||
}
|
||||
|
||||
// Capabilities omits Trash, Sharing and ArbitraryMetadata: those methods still
|
||||
// reject with NotSupported.
|
||||
// Capabilities declares kiteworks read-only: every write method rejects with
|
||||
// NotSupported. The zero value is the declaration, so any capability added later
|
||||
// stays false here without an edit.
|
||||
func (d *Driver) Capabilities(_ context.Context) storage.Capabilities {
|
||||
return storage.Capabilities{
|
||||
Upload: true,
|
||||
CreateContainer: true,
|
||||
Delete: true,
|
||||
Move: true,
|
||||
Versioning: true,
|
||||
Locking: true,
|
||||
}
|
||||
return storage.Capabilities{}
|
||||
}
|
||||
|
||||
// --- Read methods ---
|
||||
@@ -153,20 +130,9 @@ func (d *Driver) ListStorageSpaces(ctx context.Context, _ []*provider.ListStorag
|
||||
return nil, err
|
||||
}
|
||||
|
||||
u, hasUser := ctxpkg.ContextGetUser(ctx)
|
||||
|
||||
spaces := make([]*provider.StorageSpace, 0, len(dirs.Data))
|
||||
for i := range dirs.Data {
|
||||
fi := &dirs.Data[i]
|
||||
opaque := utils.AppendPlainToOpaque(nil, "spaceAlias", "project/"+fi.Name)
|
||||
if hasUser && u.GetId().GetOpaqueId() != "" {
|
||||
grants := map[string]*provider.ResourcePermissions{
|
||||
u.Id.OpaqueId: spaceRole(fi),
|
||||
}
|
||||
if b, err := json.Marshal(grants); err == nil {
|
||||
opaque.Map["grants"] = &types.OpaqueEntry{Decoder: "json", Value: b}
|
||||
}
|
||||
}
|
||||
spaces = append(spaces, &provider.StorageSpace{
|
||||
Id: &provider.StorageSpaceId{OpaqueId: fi.ID},
|
||||
Name: fi.Name,
|
||||
@@ -178,7 +144,7 @@ func (d *Driver) ListStorageSpaces(ctx context.Context, _ []*provider.ListStorag
|
||||
},
|
||||
RootInfo: d.toResourceInfo(fi, fi.ID, fi.Path),
|
||||
Mtime: utils.TimeToTS(fi.MTime()),
|
||||
Opaque: opaque,
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "spaceAlias", "project/"+fi.Name),
|
||||
})
|
||||
}
|
||||
return spaces, nil
|
||||
@@ -192,6 +158,7 @@ func (d *Driver) resolveRef(ctx context.Context, ref *provider.Reference) (nodeI
|
||||
if nodeID == "" {
|
||||
nodeID = spaceID
|
||||
}
|
||||
|
||||
relPath := strings.Trim(strings.TrimPrefix(ref.GetPath(), "./"), "/.")
|
||||
if relPath == "" {
|
||||
return nodeID, spaceID, nil
|
||||
@@ -232,9 +199,6 @@ func (d *Driver) spaceRootPath(ctx context.Context, spaceID string) (string, err
|
||||
}
|
||||
|
||||
func (d *Driver) GetMD(ctx context.Context, ref *provider.Reference, _, _ []string) (*provider.ResourceInfo, error) {
|
||||
if vr, ok := parseVersionRef(ref); ok {
|
||||
return d.getVersionMD(ctx, ref, vr)
|
||||
}
|
||||
nodeID, spaceID, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -287,7 +251,7 @@ func (d *Driver) ListFolder(ctx context.Context, ref *provider.Reference, _, _ [
|
||||
for i := range items {
|
||||
ri := d.toResourceInfo(&items[i], spaceID, rootPath)
|
||||
// ocdav does path.Join(requestPath, info.Path) for ListFolder results,
|
||||
// so Path must be just the filename, not the space-root-relative path.
|
||||
// so Path must be just the filename — not the space-root-relative path.
|
||||
ri.Path = ri.Name
|
||||
infos = append(infos, ri)
|
||||
}
|
||||
@@ -295,9 +259,6 @@ func (d *Driver) ListFolder(ctx context.Context, ref *provider.Reference, _, _ [
|
||||
}
|
||||
|
||||
func (d *Driver) Download(ctx context.Context, ref *provider.Reference, openReaderFunc func(*provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) {
|
||||
if vr, ok := parseVersionRef(ref); ok {
|
||||
return d.downloadVersion(ctx, ref, vr, openReaderFunc)
|
||||
}
|
||||
nodeID, spaceID, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -339,63 +300,31 @@ func (d *Driver) ListGrants(_ context.Context, _ *provider.Reference) ([]*provid
|
||||
return []*provider.Grant{}, nil
|
||||
}
|
||||
|
||||
// TODO: this maps only one of Kiteworks' two quota models.
|
||||
//
|
||||
// 1. System quota: a per-folder limit on a top-level folder. Matches the oCIS per-space
|
||||
// quota.
|
||||
// 2. Total folder quota: one pool shared by every folder the account owns. No oCIS
|
||||
// equivalent.
|
||||
//
|
||||
// The choice is per-folder and defaults to total folder quota. So out of the box every
|
||||
// space reports the same total and used (the account pool), and an unlimited pool makes
|
||||
// every space report unrestricted.
|
||||
//
|
||||
// Both come back under the same field names (storage_quota, storage_used,
|
||||
// storage_available), so this endpoint cannot tell them apart. Read useFolderQuota from
|
||||
// GET /rest/folders/{id} and treat the pooled case as "no real space quota".
|
||||
//
|
||||
// Enabling system quota:
|
||||
// - Admin > Users > Profiles > Standard > Collaboration > Enable Folders That Use System Quota
|
||||
// - Per folder, at creation time: Folder quota > Use system storage quota
|
||||
//
|
||||
// Total folder quota is set on the same profile page.
|
||||
func (d *Driver) GetQuota(ctx context.Context, ref *provider.Reference) (uint64, uint64, uint64, error) {
|
||||
nodeID, _, err := d.resolveRef(ctx, ref)
|
||||
if err != nil || nodeID == "" {
|
||||
return 0, 0, math.MaxUint64, nil
|
||||
}
|
||||
q, err := d.client(ctx).GetFolderQuota(nodeID)
|
||||
func (d *Driver) GetQuota(ctx context.Context, _ *provider.Reference) (uint64, uint64, uint64, error) {
|
||||
q, err := d.client(ctx).GetQuotaInfo()
|
||||
if err != nil {
|
||||
// The endpoint requires file_add on the folder, so viewers get a 403.
|
||||
// Quota is informational, so report unlimited rather than fail the caller.
|
||||
return 0, 0, math.MaxUint64, nil
|
||||
// Non-fatal for read-only driver; return zero quota rather than failing.
|
||||
return 0, 0, 0, nil
|
||||
}
|
||||
total := uint64(max(q.StorageQuota, 0))
|
||||
used := uint64(max(q.StorageUsed, 0))
|
||||
// total=0 means no quota is applied to the folder. Signal unlimited remaining
|
||||
// so the graph service doesn't compute 0/0 = NaN and report "exceeded".
|
||||
if total == 0 {
|
||||
return 0, used, math.MaxUint64, nil
|
||||
total := uint64(q.FolderQuotaAllowed)
|
||||
used := uint64(q.FolderQuotaUsed)
|
||||
var remaining uint64
|
||||
if total > used {
|
||||
remaining = total - used
|
||||
}
|
||||
return total, used, uint64(max(q.StorageAvailable, 0)), nil
|
||||
return total, used, remaining, nil
|
||||
}
|
||||
|
||||
func (d *Driver) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) {
|
||||
nodeID, _, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := d.client(ctx).GetFileByID(nodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.Locked {
|
||||
return nil, nil
|
||||
}
|
||||
if v, ok := d.locks.Load(nodeID); ok {
|
||||
return v.(*provider.Lock), nil
|
||||
}
|
||||
return &provider.Lock{LockId: "kw-" + nodeID, Type: provider.LockType_LOCK_TYPE_EXCL}, nil
|
||||
func (d *Driver) GetLock(_ context.Context, _ *provider.Reference) (*provider.Lock, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d *Driver) ListRevisions(_ context.Context, _ *provider.Reference) ([]*provider.FileVersion, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) DownloadRevision(_ context.Context, _ *provider.Reference, _ string, _ func(*provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) {
|
||||
return nil, nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) ListRecycle(_ context.Context, _ *provider.Reference, _, _ string) ([]*provider.RecycleItem, error) {
|
||||
@@ -408,186 +337,20 @@ func (d *Driver) CreateReference(_ context.Context, _ string, _ *url.URL) error
|
||||
return errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
parentRef := &provider.Reference{
|
||||
ResourceId: ref.GetResourceId(),
|
||||
Path: path.Dir(ref.GetPath()),
|
||||
}
|
||||
parentID, spaceID, err := d.resolveRef(ctx, parentRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
name := path.Base(ref.GetPath())
|
||||
if name == "" || name == "." {
|
||||
return nil, errtypes.BadRequest("kiteworks: CreateDir requires a folder name")
|
||||
}
|
||||
|
||||
folderID, err := d.client(ctx).CreateFolder(parentID, kwlib.CreateDirRequest{Name: name})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{
|
||||
SpaceID: spaceID,
|
||||
ResourceID: &provider.ResourceId{
|
||||
StorageId: d.storageID,
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: folderID,
|
||||
},
|
||||
}, nil
|
||||
func (d *Driver) CreateDir(_ context.Context, _ *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) {
|
||||
parentRef := &provider.Reference{
|
||||
ResourceId: ref.GetResourceId(),
|
||||
Path: path.Dir(ref.GetPath()),
|
||||
}
|
||||
parentID, spaceID, err := d.resolveRef(ctx, parentRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
name := path.Base(ref.GetPath())
|
||||
if name == "" || name == "." {
|
||||
return nil, errtypes.BadRequest("kiteworks: TouchFile requires a filename")
|
||||
}
|
||||
|
||||
c := d.client(ctx)
|
||||
upload, err := c.InitializeUpload(parentID, name, 0, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := c.UploadChunk(ctx, upload.URI, name, bytes.NewReader(nil), 0, 0, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.TouchFileResult{
|
||||
SpaceID: spaceID,
|
||||
ResourceID: &provider.ResourceId{
|
||||
StorageId: d.storageID,
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: fi.ID,
|
||||
},
|
||||
}, nil
|
||||
func (d *Driver) TouchFile(_ context.Context, _ *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
nodeID, spaceID, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := d.client(ctx)
|
||||
err = c.DeleteFolder(nodeID)
|
||||
if err != nil {
|
||||
var ce *kwlib.ClientError
|
||||
if !errors.As(err, &ce) || ce.StatusCode != http.StatusNotFound {
|
||||
return nil, err
|
||||
}
|
||||
if err = c.DeleteFile(nodeID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
d.locks.Delete(nodeID)
|
||||
return &storage.DeleteResult{
|
||||
ResourceId: &provider.ResourceId{
|
||||
StorageId: d.storageID,
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: nodeID,
|
||||
},
|
||||
}, nil
|
||||
func (d *Driver) Delete(_ context.Context, _ *provider.Reference) (*storage.DeleteResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
// rawNodeInfo fetches the raw KW FileInfo for a node, trying folder first.
|
||||
// Used by write methods that need ParentID or type without a full toResourceInfo conversion.
|
||||
func (d *Driver) rawNodeInfo(ctx context.Context, nodeID string) (*kwlib.FileInfo, error) {
|
||||
c := d.client(ctx)
|
||||
fi, err := c.GetFolderByID(nodeID)
|
||||
if err == nil {
|
||||
return fi, nil
|
||||
}
|
||||
var ce *kwlib.ClientError
|
||||
if !errors.As(err, &ce) || (ce.StatusCode != http.StatusNotFound && ce.StatusCode != http.StatusForbidden) {
|
||||
return nil, err
|
||||
}
|
||||
return c.GetFileByID(nodeID)
|
||||
}
|
||||
|
||||
func moveNode(c *kwlib.APIClient, fi *kwlib.FileInfo, parentID string) error {
|
||||
if fi.IsDir() {
|
||||
return c.MoveFolder(fi.ID, parentID)
|
||||
}
|
||||
_, err := c.Move(fi, &kwlib.FileInfo{ID: parentID}, false)
|
||||
return err
|
||||
}
|
||||
|
||||
func renameNode(c *kwlib.APIClient, fi *kwlib.FileInfo, name string) error {
|
||||
if fi.IsDir() {
|
||||
_, err := c.RenameFolder(fi, name)
|
||||
return err
|
||||
}
|
||||
_, err := c.RenameFile(fi, name, false)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Driver) Move(ctx context.Context, src, dst *provider.Reference) (*storage.MoveResult, error) {
|
||||
dstName := path.Base(dst.GetPath())
|
||||
if dstName == "" || dstName == "." || dstName == "/" {
|
||||
return nil, errtypes.BadRequest("kiteworks: Move requires a destination name")
|
||||
}
|
||||
|
||||
srcNodeID, _, err := d.resolveRef(ctx, src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dstParentID, _, err := d.resolveRef(ctx, &provider.Reference{
|
||||
ResourceId: dst.GetResourceId(),
|
||||
Path: path.Dir(dst.GetPath()),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dstParentID == srcNodeID {
|
||||
return nil, errtypes.BadRequest("kiteworks: cannot move a resource into itself")
|
||||
}
|
||||
|
||||
srcFI, err := d.rawNodeInfo(ctx, srcNodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
srcParentID := ""
|
||||
if srcFI.ParentID != nil {
|
||||
srcParentID = *srcFI.ParentID
|
||||
}
|
||||
|
||||
// KW has no combined move+rename. Rename first: it is the undoable step, and
|
||||
// the new name cannot collide in a parent the node has not left yet.
|
||||
c := d.client(ctx)
|
||||
renamed := dstName != srcFI.Name
|
||||
if renamed {
|
||||
if err := renameNode(c, srcFI, dstName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if srcParentID != dstParentID {
|
||||
if err := moveNode(c, srcFI, dstParentID); err != nil {
|
||||
if renamed {
|
||||
if rbErr := renameNode(c, srcFI, srcFI.Name); rbErr != nil {
|
||||
d.log.Error().Err(rbErr).Str("nodeID", srcNodeID).Msg("could not restore the original name after a failed move")
|
||||
return nil, fmt.Errorf("kiteworks: move failed and %q is left renamed to %q: %w", srcFI.Name, dstName, err)
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &storage.MoveResult{
|
||||
OldReference: src,
|
||||
NewReference: dst,
|
||||
}, nil
|
||||
func (d *Driver) Move(_ context.Context, _, _ *provider.Reference) (*storage.MoveResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) InitiateUpload(_ context.Context, _ *provider.Reference, _ int64, _ map[string]string) (map[string]string, error) {
|
||||
@@ -598,110 +361,26 @@ func (d *Driver) Upload(_ context.Context, _ storage.UploadRequest, _ storage.Up
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
// MarkProcessing is a no-op: KW controls its own file metadata so there is no
|
||||
// reliable way to mark a node as "in-flight" without abusing the checkout-lock
|
||||
// API (which would block concurrent uploads and leave orphaned locks on crash).
|
||||
// Trade-off: a file touched by TouchFile is downloadable as a zero-byte stub
|
||||
// until CommitUpload replaces it.
|
||||
func (d *Driver) MarkProcessing(_ context.Context, _ *provider.Reference, _ bool, _ string) error {
|
||||
return nil
|
||||
return errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
// TODO: large uploads still fail for the client in the sync path.
|
||||
//
|
||||
// There are two legs, and their speeds are unrelated:
|
||||
//
|
||||
// client -> oCIS TUS PATCHes, staged to a local bin file
|
||||
// oCIS -> KW this method, 8 MiB chunks over a KW upload session
|
||||
//
|
||||
// async: no problem. CommitUpload runs after the client is already done, so it
|
||||
// is bound to no request.
|
||||
//
|
||||
// sync: problem. The whole oCIS -> KW transfer happens inside the client's last
|
||||
// chunk request. That transfer can take minutes; the request is not meant to
|
||||
// live that long.
|
||||
//
|
||||
// Ideas:
|
||||
// 1. Always run the KW driver with async enabled. asyncfileuploads is not
|
||||
// wired into revaconfig, so the commit currently always runs inline.
|
||||
// 2. Make sync partly async: answer the client before the file is fully in KW.
|
||||
// Sensible, but needs verifying against real clients.
|
||||
// 3. Let the last chunk request run arbitrarily long for big files. Doubtful,
|
||||
// timeouts exist for a reason.
|
||||
// 4. Commit chunk by chunk instead of at the end. Far from the current
|
||||
// architecture, and TUS resume does not map onto KW's sequential chunks.
|
||||
// 5. Upload client -> KW directly and only register the file here. Drops
|
||||
// antivirus and checksums.
|
||||
func (d *Driver) CommitUpload(ctx context.Context, ref *provider.Reference, _ string, source storage.UploadSource) error {
|
||||
if source.Body == nil {
|
||||
return errtypes.BadRequest("kiteworks: CommitUpload requires a non-nil body")
|
||||
}
|
||||
// the client connection's lifetime must not abort a commit already in flight
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
nodeID, _, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c := d.client(ctx)
|
||||
fi, err := c.GetFileByID(nodeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = c.UploadFileVersion(ctx, nodeID, fi.Name, source.Body, source.Length); err != nil {
|
||||
return err
|
||||
}
|
||||
if !source.NodeExisted {
|
||||
d.deletePlaceholderVersion(c, nodeID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deletePlaceholderVersion removes the zero-byte stub version created by TouchFile,
|
||||
// leaving only the real content at version 1. Best-effort: all errors are logged,
|
||||
// never returned; the upload already succeeded before this is called.
|
||||
func (d *Driver) deletePlaceholderVersion(c *kwlib.APIClient, fileID string) {
|
||||
log := d.log.With().Str("fileID", fileID).Logger()
|
||||
|
||||
versions, err := c.GetFileVersions(fileID)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("placeholder cleanup: could not list versions")
|
||||
return
|
||||
}
|
||||
for _, v := range versions {
|
||||
if v.VersionNumber > 0 && v.Size == 0 {
|
||||
if err := c.DeleteFileVersion(fileID, v.ID); err != nil {
|
||||
ce := kwlib.AsClientError(err)
|
||||
switch ce.StatusCode {
|
||||
case http.StatusNotFound: // already gone, fine
|
||||
case http.StatusUnprocessableEntity: // last version: real bytes not uploaded, leave it
|
||||
log.Warn().Msg("placeholder cleanup: cannot delete last version, real upload may have failed")
|
||||
default:
|
||||
log.Warn().Err(err).Msg("placeholder cleanup: delete version failed")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
func (d *Driver) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error {
|
||||
return errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
|
||||
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
|
||||
}
|
||||
|
||||
func (d *Driver) RollbackUpload(ctx context.Context, _ *provider.Reference, _ string, info storage.RollbackInfo) error {
|
||||
// the prior version stays current, so there is nothing to undo
|
||||
if info.NodeExisted {
|
||||
return nil
|
||||
}
|
||||
if err := d.client(ctx).DeleteFile(info.NodeID); err != nil {
|
||||
if kwlib.AsClientError(err).StatusCode == http.StatusNotFound {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (d *Driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Driver) RestoreRevision(_ context.Context, _ *provider.Reference, _ string) (*storage.RestoreRevisionResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) RestoreRecycleItem(_ context.Context, _ *provider.Reference, _, _ string, _ *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
@@ -738,43 +417,16 @@ func (d *Driver) UnsetArbitraryMetadata(_ context.Context, _ *provider.Reference
|
||||
return errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
nodeID, spaceID, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := d.client(ctx).LockFile(nodeID); err != nil {
|
||||
var ce *kwlib.ClientError
|
||||
if errors.As(err, &ce) && ce.StatusCode == http.StatusForbidden {
|
||||
return nil, errtypes.PreconditionFailed("kiteworks: file already locked")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
d.locks.Store(nodeID, lock)
|
||||
return &storage.SetLockResult{SpaceID: spaceID}, nil
|
||||
func (d *Driver) SetLock(_ context.Context, _ *provider.Reference, _ *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
// RefreshLock is a no-op. KW has no lock-refresh endpoint, locks carry no
|
||||
// expiry, and re-calling the lock endpoint on an already-locked file returns
|
||||
// 403 even when the caller owns the lock.
|
||||
func (d *Driver) RefreshLock(_ context.Context, _ *provider.Reference, _ *provider.Lock, _ string) error {
|
||||
return nil
|
||||
return errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
nodeID, spaceID, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := d.client(ctx).UnlockFile(nodeID); err != nil {
|
||||
var ce *kwlib.ClientError
|
||||
if errors.As(err, &ce) && ce.StatusCode == http.StatusForbidden {
|
||||
return nil, errtypes.PreconditionFailed("kiteworks: file not locked or locked by another user")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
d.locks.Delete(nodeID)
|
||||
return &storage.UnlockResult{SpaceID: spaceID}, nil
|
||||
func (d *Driver) Unlock(_ context.Context, _ *provider.Reference, _ *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("kiteworks: read-only driver")
|
||||
}
|
||||
|
||||
func (d *Driver) CreateStorageSpace(_ context.Context, _ *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) {
|
||||
|
||||
+30
-178
@@ -2,7 +2,6 @@ package kwlib
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -19,8 +18,6 @@ import (
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
const uploadChunkSize = 8 << 20 // 8 MiB
|
||||
|
||||
func NewClientFactory(server, agentString string, insecure bool) *APIClientFactory {
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
@@ -39,35 +36,28 @@ func NewClientFactory(server, agentString string, insecure bool) *APIClientFacto
|
||||
// #nosec
|
||||
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
}
|
||||
|
||||
uploadTransport := transport.Clone()
|
||||
uploadTransport.ResponseHeaderTimeout = 30 * time.Second
|
||||
|
||||
return &APIClientFactory{
|
||||
server: server,
|
||||
agentString: agentString,
|
||||
httpClient: &http.Client{Transport: transport, Timeout: 15 * time.Second},
|
||||
uploadClient: &http.Client{Transport: uploadTransport},
|
||||
server: server,
|
||||
agentString: agentString,
|
||||
httpClient: &http.Client{Transport: transport, Timeout: 15 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
type APIClientFactory struct {
|
||||
server string
|
||||
agentString string
|
||||
httpClient *http.Client
|
||||
uploadClient *http.Client
|
||||
server string
|
||||
agentString string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type APIClient struct {
|
||||
server string
|
||||
agentString string
|
||||
logger *zerolog.Logger
|
||||
host string
|
||||
token string
|
||||
requestId string
|
||||
remoteAddr string
|
||||
httpClient *http.Client
|
||||
uploadClient *http.Client
|
||||
server string
|
||||
agentString string
|
||||
logger *zerolog.Logger
|
||||
host string
|
||||
token string
|
||||
requestId string
|
||||
remoteAddr string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func decodeJSON(body io.ReadCloser, out any) error {
|
||||
@@ -77,14 +67,13 @@ func decodeJSON(body io.ReadCloser, out any) error {
|
||||
|
||||
func (f *APIClientFactory) Build(host, requestId, remoteAddr, token string, l *zerolog.Logger) *APIClient {
|
||||
return &APIClient{
|
||||
token: token,
|
||||
server: f.server,
|
||||
host: host,
|
||||
logger: l,
|
||||
requestId: requestId,
|
||||
remoteAddr: remoteAddr,
|
||||
httpClient: f.httpClient,
|
||||
uploadClient: f.uploadClient,
|
||||
token: token,
|
||||
server: f.server,
|
||||
host: host,
|
||||
logger: l,
|
||||
requestId: requestId,
|
||||
remoteAddr: remoteAddr,
|
||||
httpClient: f.httpClient,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +94,7 @@ func (c *APIClient) GetTopFolders() (*DirectoryInfo, error) {
|
||||
}
|
||||
|
||||
func (c *APIClient) GetFolderByID(id string) (*FileInfo, error) {
|
||||
request, err := c.NewGetRequest(fmt.Sprintf("/rest/folders/%s?with=(permissions)", id))
|
||||
request, err := c.NewGetRequest(fmt.Sprintf("/rest/folders/%s", id))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -159,7 +148,7 @@ func (c *APIClient) Search(path string) (*FileInfo, error) {
|
||||
}
|
||||
|
||||
func (c *APIClient) GetFileByID(id string) (*FileInfo, error) {
|
||||
request, err := c.NewGetRequest(fmt.Sprintf("/rest/files/%s?with=(permissions,lockUser)", id))
|
||||
request, err := c.NewGetRequest(fmt.Sprintf("/rest/files/%s", id))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -205,8 +194,8 @@ func (c *APIClient) GetUser(id string) (*User, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) GetFolderQuota(folderID string) (*FolderQuota, error) {
|
||||
request, err := c.NewGetRequest(fmt.Sprintf("/rest/folders/%s/quota", folderID))
|
||||
func (c *APIClient) GetQuotaInfo() (*QuotaInfo, error) {
|
||||
request, err := c.NewGetRequest("/rest/quotas")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -214,7 +203,7 @@ func (c *APIClient) GetFolderQuota(folderID string) (*FolderQuota, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := &FolderQuota{}
|
||||
out := &QuotaInfo{}
|
||||
if err := decodeJSON(response.Body, out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -262,20 +251,12 @@ func (c *APIClient) CreateFolder(id string, payload CreateDirRequest) (string, e
|
||||
}
|
||||
|
||||
func (c *APIClient) InitializeUpload(parentID, name string, size int64, numberOfChunks int) (*UploadResult, error) {
|
||||
return c.initializeUpload(fmt.Sprintf("/rest/folders/%s/actions/initiateUpload", parentID), name, size, numberOfChunks)
|
||||
}
|
||||
|
||||
func (c *APIClient) InitializeVersionUpload(fileID, name string, size int64, numberOfChunks int) (*UploadResult, error) {
|
||||
return c.initializeUpload(fmt.Sprintf("/rest/files/%s/actions/initiateUpload", fileID), name, size, numberOfChunks)
|
||||
}
|
||||
|
||||
func (c *APIClient) initializeUpload(path, name string, size int64, numberOfChunks int) (*UploadResult, error) {
|
||||
payload := InitializeUpload{
|
||||
FileName: name,
|
||||
TotalSize: size,
|
||||
TotalChunks: numberOfChunks,
|
||||
}
|
||||
request, err := c.NewPostRequest(path, payload)
|
||||
request, err := c.NewPostRequest(fmt.Sprintf("/rest/folders/%s/actions/initiateUpload", parentID), payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -290,20 +271,7 @@ func (c *APIClient) initializeUpload(path, name string, size int64, numberOfChun
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) TerminateUpload(uploadID int64) error {
|
||||
request, err := c.newRequest("DELETE", fmt.Sprintf("/rest/uploads/%d", uploadID), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := c.SendRequest(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response.Body.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *APIClient) UploadChunk(ctx context.Context, uploadURI, name string, file io.Reader, chunkIndex int, chunk int64, isLastChunk bool) (*FileInfo, error) {
|
||||
func (c *APIClient) UploadChunk(uploadURI, name string, file io.Reader, chunkIndex int, chunk int64, isLastChunk bool) (*FileInfo, error) {
|
||||
body := new(bytes.Buffer)
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreateFormFile("content", name)
|
||||
@@ -328,14 +296,13 @@ func (c *APIClient) UploadChunk(ctx context.Context, uploadURI, name string, fil
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request = request.WithContext(ctx)
|
||||
request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
if isLastChunk {
|
||||
q := request.URL.Query()
|
||||
q.Add("returnEntity", "true")
|
||||
request.URL.RawQuery = q.Encode()
|
||||
}
|
||||
response, err := c.sendWith(c.uploadClient, request)
|
||||
response, err := c.SendRequest(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -346,121 +313,10 @@ func (c *APIClient) UploadChunk(ctx context.Context, uploadURI, name string, fil
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
// drained so the connection can be reused across chunks
|
||||
_, _ = io.Copy(io.Discard, response.Body)
|
||||
response.Body.Close()
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) MoveFolder(id, destinationFolderID string) error {
|
||||
request, err := c.NewPostRequest(
|
||||
fmt.Sprintf("/rest/folders/%s/actions/move", id),
|
||||
MoveFolderRequest{DestinationFolderID: destinationFolderID},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.SendRequest(request)
|
||||
return err
|
||||
}
|
||||
|
||||
// name must be the file's current name: the server requires it even for a version upload.
|
||||
func (c *APIClient) UploadFileVersion(ctx context.Context, fileID, name string, body io.Reader, length int64) error {
|
||||
chunks := chunkCount(length)
|
||||
session, err := c.InitializeVersionUpload(fileID, name, length, chunks)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < chunks; i++ {
|
||||
size := int64(uploadChunkSize)
|
||||
if remaining := length - int64(i)*uploadChunkSize; remaining < size {
|
||||
size = remaining
|
||||
}
|
||||
if _, err := c.UploadChunk(ctx, session.URI, name, body, i, size, i == chunks-1); err != nil {
|
||||
if termErr := c.TerminateUpload(session.ID); termErr != nil {
|
||||
c.logger.Warn().Err(termErr).Int64("uploadID", session.ID).Msg("could not terminate kiteworks upload session")
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func chunkCount(length int64) int {
|
||||
if length <= 0 {
|
||||
return 1
|
||||
}
|
||||
return int((length + uploadChunkSize - 1) / uploadChunkSize)
|
||||
}
|
||||
|
||||
func (c *APIClient) GetFileVersions(fileID string) ([]Version, error) {
|
||||
req, err := c.NewGetRequest(fmt.Sprintf("/rest/files/%s/versions", fileID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.SendRequest(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := &VersionList{}
|
||||
if err := decodeJSON(resp.Body, out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out.Data, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) DeleteFileVersion(fileID, versionID string) error {
|
||||
req, err := c.newRequest("DELETE", fmt.Sprintf("/rest/files/%s/versions/%s", fileID, versionID), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.SendRequest(req)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *APIClient) PromoteFileVersion(fileID, versionID string) error {
|
||||
req, err := c.newRequest("POST", fmt.Sprintf("/rest/files/%s/versions/%s/actions/promote", fileID, versionID), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.SendRequest(req)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *APIClient) GetVersionContents(fileID, versionID string) (*http.Response, error) {
|
||||
req, err := c.NewGetRequest(fmt.Sprintf("/rest/files/%s/versions/%s/content", fileID, versionID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.SendRequest(req)
|
||||
}
|
||||
|
||||
func (c *APIClient) LockFile(fileID string) error {
|
||||
req, err := c.newRequest("PATCH", fmt.Sprintf("/rest/files/%s/actions/lock", fileID), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.SendRequest(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *APIClient) UnlockFile(fileID string) error {
|
||||
req, err := c.newRequest("PATCH", fmt.Sprintf("/rest/files/%s/actions/unlock", fileID), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := c.SendRequest(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *APIClient) DeleteFolder(id string) error {
|
||||
request, err := c.newRequest("DELETE", fmt.Sprintf("/rest/folders/%s", id), nil)
|
||||
if err != nil {
|
||||
@@ -576,11 +432,7 @@ func (c *APIClient) newRequest(method, path string, body io.Reader) (*http.Reque
|
||||
}
|
||||
|
||||
func (c *APIClient) SendRequest(req *http.Request) (*http.Response, error) {
|
||||
return c.sendWith(c.httpClient, req)
|
||||
}
|
||||
|
||||
func (c *APIClient) sendWith(client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
response, err := client.Do(req)
|
||||
response, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
c.logger.Debug().Str("method", req.Method).Str("path", req.URL.String()).Err(err).Msg("kiteworks API call errored")
|
||||
return nil, err
|
||||
|
||||
+7
-47
@@ -15,24 +15,7 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
PermDownload = "download"
|
||||
PermView = "view"
|
||||
PermPropertiesView = "properties_view"
|
||||
PermUserView = "user_view"
|
||||
PermUserAdd = "user_add"
|
||||
PermUserEdit = "user_edit"
|
||||
PermUserRemove = "user_remove"
|
||||
PermRename = "rename"
|
||||
PermFolderAdd = "folder_add"
|
||||
PermFileAdd = "file_add"
|
||||
PermFolderDelete = "folder_delete"
|
||||
PermFolderMove = "folder_move"
|
||||
PermVersionView = "version_view"
|
||||
PermVersionCreate = "version_create"
|
||||
PermVersionPromote = "version_promote"
|
||||
PermVersionDelete = "version_delete"
|
||||
PermFileDelete = "file_delete"
|
||||
PermFileMove = "file_move"
|
||||
DownloadPermission = "download"
|
||||
)
|
||||
|
||||
type FileSearch struct {
|
||||
@@ -86,8 +69,6 @@ type FileInfo struct {
|
||||
PermaLink string `json:"permalink"`
|
||||
Permissions []Permission `json:"permissions"`
|
||||
Creator User `json:"creator"`
|
||||
Locked bool `json:"locked"`
|
||||
LockUser *User `json:"lockUser"`
|
||||
}
|
||||
|
||||
type FileFingerPrints []FileFingerPrint
|
||||
@@ -162,15 +143,13 @@ func (fi *FileInfo) IsSyncAble() bool {
|
||||
return *fi.SyncAble
|
||||
}
|
||||
|
||||
// HasPermission returns true if the named permission is present and allowed.
|
||||
// Absent permissions are treated as denied.
|
||||
func (fi *FileInfo) HasPermission(name string) bool {
|
||||
func (fi *FileInfo) HasDownloadPermission() bool {
|
||||
if fi == nil {
|
||||
return false
|
||||
}
|
||||
for i := range fi.Permissions {
|
||||
if fi.Permissions[i].Name == name {
|
||||
return fi.Permissions[i].Allowed
|
||||
if fi.Permissions[i].Name == DownloadPermission {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
@@ -209,12 +188,9 @@ type UploadResult struct {
|
||||
TotalSize int64 `json:"totalSize"`
|
||||
}
|
||||
|
||||
// FolderQuota is the response of GET /rest/folders/{id}/quota.
|
||||
// StorageQuota is 0 when no quota is applied to the folder.
|
||||
type FolderQuota struct {
|
||||
StorageQuota int64 `json:"storage_quota"`
|
||||
StorageUsed int64 `json:"storage_used"`
|
||||
StorageAvailable int64 `json:"storage_available"`
|
||||
type QuotaInfo struct {
|
||||
FolderQuotaAllowed int64 `json:"folder_quota_allowed"`
|
||||
FolderQuotaUsed int64 `json:"folder_quota_used"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
@@ -248,19 +224,3 @@ type FileUpdateRequest struct {
|
||||
type FolderUpdatePutRequest struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
type MoveFolderRequest struct {
|
||||
DestinationFolderID string `json:"destinationFolderId"`
|
||||
}
|
||||
|
||||
// Version represents a single version entry from GET /rest/files/{id}/versions.
|
||||
type Version struct {
|
||||
ID string `json:"id"`
|
||||
VersionNumber int `json:"versionNumber"`
|
||||
Size int64 `json:"size"`
|
||||
Created Time `json:"created"`
|
||||
}
|
||||
|
||||
type VersionList struct {
|
||||
Data []Version `json:"data"`
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package kiteworks
|
||||
|
||||
import (
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/conversions"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/kiteworks/kwlib"
|
||||
)
|
||||
|
||||
// permissionSet returns the CS3 ResourcePermissions for fi based on its KW permissions.
|
||||
func permissionSet(fi *kwlib.FileInfo) *provider.ResourcePermissions {
|
||||
if fi.IsDir() {
|
||||
return folderPermissions(fi)
|
||||
}
|
||||
return filePermissions(fi)
|
||||
}
|
||||
|
||||
func folderPermissions(fi *kwlib.FileInfo) *provider.ResourcePermissions {
|
||||
canView := fi.HasPermission(kwlib.PermPropertiesView)
|
||||
return &provider.ResourcePermissions{
|
||||
Stat: canView,
|
||||
GetPath: canView,
|
||||
ListContainer: canView,
|
||||
InitiateFileDownload: fi.HasPermission(kwlib.PermDownload),
|
||||
InitiateFileUpload: fi.HasPermission(kwlib.PermFileAdd),
|
||||
CreateContainer: fi.HasPermission(kwlib.PermFolderAdd),
|
||||
Delete: fi.HasPermission(kwlib.PermFolderDelete),
|
||||
Move: fi.HasPermission(kwlib.PermFolderMove),
|
||||
ListGrants: fi.HasPermission(kwlib.PermUserView),
|
||||
AddGrant: fi.HasPermission(kwlib.PermUserAdd),
|
||||
UpdateGrant: fi.HasPermission(kwlib.PermUserEdit),
|
||||
RemoveGrant: fi.HasPermission(kwlib.PermUserRemove),
|
||||
}
|
||||
}
|
||||
|
||||
func filePermissions(fi *kwlib.FileInfo) *provider.ResourcePermissions {
|
||||
canView := fi.HasPermission(kwlib.PermView)
|
||||
return &provider.ResourcePermissions{
|
||||
Stat: canView,
|
||||
GetPath: canView,
|
||||
InitiateFileDownload: fi.HasPermission(kwlib.PermDownload),
|
||||
InitiateFileUpload: fi.HasPermission(kwlib.PermVersionCreate),
|
||||
ListFileVersions: fi.HasPermission(kwlib.PermVersionView),
|
||||
RestoreFileVersion: fi.HasPermission(kwlib.PermVersionPromote),
|
||||
Delete: fi.HasPermission(kwlib.PermFileDelete),
|
||||
Move: fi.HasPermission(kwlib.PermFileMove),
|
||||
}
|
||||
}
|
||||
|
||||
// spaceRole returns the CS3 role for the current user on a space root folder.
|
||||
// Used to build the grants opaque in ListStorageSpaces.
|
||||
// Precedence: Manager > Editor > Viewer.
|
||||
func spaceRole(fi *kwlib.FileInfo) *provider.ResourcePermissions {
|
||||
switch {
|
||||
case fi.HasPermission(kwlib.PermUserAdd):
|
||||
return conversions.NewManagerRole().CS3ResourcePermissions()
|
||||
case fi.HasPermission(kwlib.PermFileAdd):
|
||||
return conversions.NewEditorRole().CS3ResourcePermissions()
|
||||
default:
|
||||
return conversions.NewViewerRole().CS3ResourcePermissions()
|
||||
}
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
package kiteworks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/kiteworks/kwlib"
|
||||
)
|
||||
|
||||
// versionRef identifies a specific KW file version. Version keys are encoded
|
||||
// as "<fileID>@<versionID>" so that GetMD and Download can distinguish them
|
||||
// from regular file references and look up the right KW resource.
|
||||
type versionRef struct {
|
||||
fileID string
|
||||
versionID string
|
||||
}
|
||||
|
||||
// parseVersionRef returns a versionRef if ref.OpaqueId encodes a version
|
||||
// ("fileID@versionID"), and false otherwise.
|
||||
func parseVersionRef(ref *provider.Reference) (versionRef, bool) {
|
||||
fileID, versionID, ok := strings.Cut(ref.GetResourceId().GetOpaqueId(), "@")
|
||||
if !ok {
|
||||
return versionRef{}, false
|
||||
}
|
||||
return versionRef{fileID: fileID, versionID: versionID}, true
|
||||
}
|
||||
|
||||
// getVersionMD returns a minimal ResourceInfo for a version reference.
|
||||
// Calls GetFileByID on the parent file to verify access; the returned info
|
||||
// carries only what handleGet requires (Type=FILE, no "processing" status).
|
||||
func (d *Driver) getVersionMD(ctx context.Context, ref *provider.Reference, vr versionRef) (*provider.ResourceInfo, error) {
|
||||
if _, err := d.client(ctx).GetFileByID(vr.fileID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &provider.ResourceInfo{
|
||||
Id: ref.GetResourceId(),
|
||||
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// downloadVersion streams the content of a specific version, used by Download
|
||||
// when the ref carries a version OpaqueId.
|
||||
func (d *Driver) downloadVersion(ctx context.Context, ref *provider.Reference, vr versionRef, openReaderFunc func(*provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) {
|
||||
fi, err := d.client(ctx).GetFileByID(vr.fileID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !fi.HasPermission(kwlib.PermDownload) {
|
||||
return nil, nil, errtypes.PermissionDenied(vr.fileID)
|
||||
}
|
||||
// Fetch content first to read Content-Length from the response headers.
|
||||
// This is required because the dataprovider uses ri.Size to set Content-Length,
|
||||
// and an empty size causes browsers to receive a zero-byte file.
|
||||
resp, err := d.client(ctx).GetVersionContents(vr.fileID, vr.versionID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ri := &provider.ResourceInfo{
|
||||
Id: ref.GetResourceId(),
|
||||
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
|
||||
Name: fi.Name,
|
||||
Path: fi.Path,
|
||||
Size: uint64(max(resp.ContentLength, 0)),
|
||||
}
|
||||
if !openReaderFunc(ri) {
|
||||
resp.Body.Close()
|
||||
return ri, nil, nil
|
||||
}
|
||||
return ri, resp.Body, nil
|
||||
}
|
||||
|
||||
// ListRevisions returns file versions as CS3 FileVersion entries.
|
||||
// Keys are encoded as "<fileID>@<versionID>" so that GetMD and Download
|
||||
// can route version download requests to the right KW endpoint.
|
||||
func (d *Driver) ListRevisions(ctx context.Context, ref *provider.Reference) ([]*provider.FileVersion, error) {
|
||||
nodeID, _, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := d.client(ctx).GetFileByID(nodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.HasPermission(kwlib.PermVersionView) {
|
||||
return nil, errtypes.PermissionDenied(nodeID)
|
||||
}
|
||||
versions, err := d.client(ctx).GetFileVersions(nodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
revs := make([]*provider.FileVersion, 0, len(versions))
|
||||
for _, v := range versions {
|
||||
revs = append(revs, &provider.FileVersion{
|
||||
Key: nodeID + "@" + v.ID,
|
||||
Mtime: uint64(time.Time(v.Created).Unix()),
|
||||
Size: uint64(v.Size),
|
||||
})
|
||||
}
|
||||
return revs, nil
|
||||
}
|
||||
|
||||
// RestoreRevision promotes revisionKey to be the current version of the file.
|
||||
// revisionKey is "<fileID>@<versionID>" as returned by ListRevisions.
|
||||
// ocdav passes the space-root ResourceId as ref (opaque_id == space_id), so we
|
||||
// use the fileID embedded in the key rather than resolveRef.
|
||||
func (d *Driver) RestoreRevision(ctx context.Context, _ *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
fileID, versionID, ok := strings.Cut(revisionKey, "@")
|
||||
if !ok {
|
||||
return nil, errtypes.BadRequest("kiteworks: invalid revision key: " + revisionKey)
|
||||
}
|
||||
fi, err := d.client(ctx).GetFileByID(fileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !fi.HasPermission(kwlib.PermVersionPromote) {
|
||||
return nil, errtypes.PermissionDenied(fileID)
|
||||
}
|
||||
if err := d.client(ctx).PromoteFileVersion(fileID, versionID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{}, nil
|
||||
}
|
||||
|
||||
// DownloadRevision streams the content of the revision identified by revisionKey.
|
||||
// revisionKey is "<fileID>@<versionID>" as returned by ListRevisions.
|
||||
func (d *Driver) DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string, openReaderFunc func(*provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) {
|
||||
nodeID, _, err := d.resolveRef(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fi, err := d.client(ctx).GetFileByID(nodeID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !fi.HasPermission(kwlib.PermDownload) {
|
||||
return nil, nil, errtypes.PermissionDenied(nodeID)
|
||||
}
|
||||
_, versionID, _ := strings.Cut(revisionKey, "@")
|
||||
resp, err := d.client(ctx).GetVersionContents(nodeID, versionID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ri := &provider.ResourceInfo{
|
||||
Id: ref.GetResourceId(),
|
||||
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
|
||||
Name: fi.Name,
|
||||
Path: fi.Path,
|
||||
Size: uint64(max(resp.ContentLength, 0)),
|
||||
}
|
||||
if !openReaderFunc(ri) {
|
||||
resp.Body.Close()
|
||||
return ri, nil, nil
|
||||
}
|
||||
return ri, resp.Body, nil
|
||||
}
|
||||
Generated
Vendored
+12
-1
@@ -74,6 +74,11 @@ var responses = map[string]Response{
|
||||
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/EmptyRecycle `: {200, ``, serverStateEmpty},
|
||||
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetQuota `: {200, `{"totalBytes":456,"usedBytes":123}`, serverStateEmpty},
|
||||
|
||||
// the parent of an upload target, stated for its permissions and its id
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":[]} EMPTY`: {200, `{"opaque":{},"type":2,"id":{"opaque_id":"fileid-/"},"checksum":{},"etag":"deadbeef","mime_type":"httpd/unix-directory","mtime":{"seconds":1234567890},"path":"/","permission_set":{"initiate_file_upload":true,"stat":true,"list_container":true},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
|
||||
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} EMPTY`: {404, ``, serverStateEmpty},
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} HOME`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}`, serverStateHome},
|
||||
|
||||
@@ -111,7 +116,13 @@ var responses = map[string]Response{
|
||||
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetPathByID {"storage_id":"00000000-0000-0000-0000-000000000000","opaque_id":"fileid-/some/path"} EMPTY`: {200, "/subdir", serverStateEmpty},
|
||||
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
|
||||
// the coordinator resolves the upload target itself: the file does not exist yet,
|
||||
// so it stats the parent for the permissions and the parent id
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":[]}`: {404, ``, serverStateEmpty},
|
||||
// a zero-length upload finishes at once, so the node is created and read back here
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/TouchFile {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"markprocessing":false,"mtime":"1234567890"}`: {200, ``, serverStateEmpty},
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"mdKeys":[]}`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/file"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/file","permission_set":{},"size":0,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"path":"/file"},"uploadLength":0,"metadata":{"providerID":""}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":1,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
|
||||
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":2,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
|
||||
|
||||
+2
-3
@@ -259,9 +259,8 @@ type DeleteStorageSpaceResult struct {
|
||||
|
||||
// UploadSource carries the staged bytes for a CommitUpload call.
|
||||
type UploadSource struct {
|
||||
Body io.ReadCloser
|
||||
Length int64
|
||||
NodeExisted bool
|
||||
Body io.ReadCloser
|
||||
Length int64
|
||||
|
||||
// ScanResult is the antivirus verdict: empty means clean.
|
||||
ScanResult string
|
||||
|
||||
Generated
Vendored
+8
-352
@@ -28,9 +28,7 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/jellydator/ttlcache/v2"
|
||||
@@ -41,7 +39,6 @@ import (
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/autoprop"
|
||||
@@ -50,7 +47,6 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/logger"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/chunking"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/aspects"
|
||||
@@ -79,16 +75,12 @@ const (
|
||||
CtxKeySpaceGID CtxKey = iota
|
||||
)
|
||||
|
||||
const maxCommitRetryBackoff = 2 * time.Minute
|
||||
|
||||
var (
|
||||
tracer trace.Tracer
|
||||
|
||||
// the coordinator consumes the postprocessing events; reverting a revision is
|
||||
// the driver's own business
|
||||
_registeredEvents = []events.Unmarshaller{
|
||||
events.PostprocessingFinished{},
|
||||
events.PostprocessingStepFinished{},
|
||||
events.RestartPostprocessing{},
|
||||
events.CleanUpload{},
|
||||
events.RevertRevision{},
|
||||
}
|
||||
)
|
||||
@@ -133,9 +125,6 @@ type Decomposedfs struct {
|
||||
groupSpaceIndex *spaceidindex.Index
|
||||
spaceTypeIndex *spaceidindex.Index
|
||||
|
||||
// commitLimiter caps concurrent async blob commits at NumConsumers.
|
||||
commitLimiter *semaphore.Weighted
|
||||
|
||||
log *zerolog.Logger
|
||||
}
|
||||
|
||||
@@ -273,7 +262,9 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
|
||||
return nil, errors.New("need nats for async file processing")
|
||||
}
|
||||
|
||||
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup, _registeredEvents...)
|
||||
// a group of its own: the coordinator holds o.Events.ConsumerGroup, and one
|
||||
// group gets one copy of each event
|
||||
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup+"-revisions", _registeredEvents...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -282,18 +273,16 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
|
||||
o.Events.NumConsumers = 1
|
||||
}
|
||||
|
||||
fs.commitLimiter = semaphore.NewWeighted(int64(o.Events.NumConsumers))
|
||||
|
||||
for i := 0; i < o.Events.NumConsumers; i++ {
|
||||
go fs.Postprocessing(ch)
|
||||
go fs.ConsumeRevisionEvents(ch)
|
||||
}
|
||||
}
|
||||
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
// Postprocessing starts the postprocessing result collector
|
||||
func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) {
|
||||
// ConsumeRevisionEvents starts the revision event collector
|
||||
func (fs *Decomposedfs) ConsumeRevisionEvents(ch <-chan events.Event) {
|
||||
log := logger.New()
|
||||
for event := range ch {
|
||||
evCtx := context.Background()
|
||||
@@ -301,219 +290,12 @@ func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) {
|
||||
}
|
||||
}
|
||||
|
||||
// finalizeWithRetry commits the staged bytes, retrying blobstore failures with
|
||||
// capped exponential backoff.
|
||||
func (fs *Decomposedfs) finalizeWithRetry(ctx context.Context, session *upload.OcisSession, log *zerolog.Logger) error {
|
||||
maxAttempts := fs.o.Events.CommitMaxRetries + 1
|
||||
backoff := fs.o.Events.CommitRetryBackoff
|
||||
var err error
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
if err = session.Finalize(ctx); err == nil {
|
||||
return nil
|
||||
}
|
||||
ev := log.Warn().Err(err).
|
||||
Int("attempt", attempt).Int("maxAttempts", maxAttempts).
|
||||
Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID())
|
||||
if attempt == maxAttempts {
|
||||
ev.Msg("blob commit failed, giving up")
|
||||
break
|
||||
}
|
||||
// clamp before use: this bounds backoff to maxCommitRetryBackoff every
|
||||
// iteration, so the backoff *= 2 below can never grow past 2*max and
|
||||
// cannot overflow the int64 duration.
|
||||
backoff = min(backoff, maxCommitRetryBackoff)
|
||||
ev.Dur("backoff", backoff).Msg("blob commit failed, retrying after backoff")
|
||||
timer := time.NewTimer(backoff)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
// backoff elapsed, fall through to the next attempt
|
||||
}
|
||||
backoff *= 2
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// completePostprocessing reverts (failed) or finalizes the node, unmarks
|
||||
// processing, and publishes UploadReady. keepUpload keeps the staged bytes. May
|
||||
// run detached, so it touches no consumer-loop state.
|
||||
func (fs *Decomposedfs) completePostprocessing(ctx context.Context, session *upload.OcisSession, n *node.Node, ev events.PostprocessingFinished, failed, keepUpload bool, sublog zerolog.Logger) {
|
||||
now := time.Now()
|
||||
if failed {
|
||||
// if no other upload session is in progress (processing id != session id) or has finished (processing id == "")
|
||||
latestSession, err := n.ProcessingID(ctx)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("reading node for session failed")
|
||||
}
|
||||
if latestSession == session.ID() {
|
||||
// propagate reverted sizeDiff after failed postprocessing
|
||||
if err := fs.tp.Propagate(ctx, n, -session.SizeDiff()); err != nil {
|
||||
sublog.Error().Err(err).Msg("could not propagate tree size change")
|
||||
}
|
||||
}
|
||||
} else if p, err := n.Parent(ctx); err != nil {
|
||||
sublog.Error().Err(err).Msg("could not read parent")
|
||||
} else if p != nil {
|
||||
// update parent tmtime to propagate etag change after successful postprocessing
|
||||
_ = p.SetTMTime(ctx, &now)
|
||||
if err := fs.tp.Propagate(ctx, p, 0); err != nil {
|
||||
sublog.Error().Err(err).Msg("could not propagate etag change")
|
||||
}
|
||||
}
|
||||
|
||||
// unmark processing; a leftover marker keeps downloads at 425
|
||||
session.Cleanup(failed, !keepUpload, !keepUpload, true)
|
||||
|
||||
var isVersion bool
|
||||
if session.NodeExists() {
|
||||
info, err := session.GetInfo(ctx)
|
||||
if err == nil && info.MetaData["versionsPath"] != "" {
|
||||
isVersion = true
|
||||
}
|
||||
}
|
||||
|
||||
if err := events.Publish(
|
||||
ctx,
|
||||
fs.stream,
|
||||
events.UploadReady{
|
||||
UploadID: ev.UploadID,
|
||||
Failed: failed,
|
||||
ExecutingUser: ev.ExecutingUser,
|
||||
Filename: ev.Filename,
|
||||
FileRef: &provider.Reference{
|
||||
ResourceId: &provider.ResourceId{
|
||||
StorageId: session.ProviderID(),
|
||||
SpaceId: session.SpaceID(),
|
||||
OpaqueId: session.SpaceID(),
|
||||
},
|
||||
Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())),
|
||||
},
|
||||
ResourceID: &provider.ResourceId{
|
||||
StorageId: session.ProviderID(),
|
||||
SpaceId: session.SpaceID(),
|
||||
OpaqueId: session.NodeID(),
|
||||
},
|
||||
Timestamp: utils.TimeToTS(now),
|
||||
SpaceOwner: n.SpaceOwnerOrManager(ctx),
|
||||
IsVersion: isVersion,
|
||||
ImpersonatingUser: ev.ImpersonatingUser,
|
||||
},
|
||||
); err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to publish UploadReady event")
|
||||
}
|
||||
}
|
||||
|
||||
func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event, log *zerolog.Logger) {
|
||||
ctx, span := events.TraceEventConsumerWithTracer(evCtx, tracer, event)
|
||||
ctx = autoprop.SetMetaToContext(ctx, event.ExtraInfo)
|
||||
defer span.End()
|
||||
|
||||
switch ev := event.Event.(type) {
|
||||
case events.PostprocessingFinished:
|
||||
sublog := log.With().Str("event", "PostprocessingFinished").Str("uploadid", ev.UploadID).Logger()
|
||||
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
|
||||
sublog.Debug().Msg("ignoring event for different storage")
|
||||
return
|
||||
}
|
||||
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to get upload")
|
||||
return // NOTE: since we can't get the upload, we can't delete the blob
|
||||
}
|
||||
|
||||
ctx = session.Context(ctx)
|
||||
|
||||
n, err := session.Node(ctx)
|
||||
if err != nil {
|
||||
// The node metadata is unreadable, so this upload can never finish:
|
||||
// the destination cannot be resolved. Clean the session up instead of
|
||||
// leaving it behind to be retried forever. Cleanup falls back to the
|
||||
// session metadata to release the quota.
|
||||
sublog.Error().Err(err).Msg("could not read node, cleaning up orphaned session")
|
||||
session.Cleanup(true, true, true, false)
|
||||
return
|
||||
}
|
||||
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
|
||||
if !n.Exists {
|
||||
sublog.Debug().Msg("node no longer exists")
|
||||
session.Cleanup(false, true, true, false)
|
||||
return
|
||||
}
|
||||
|
||||
switch ev.Outcome {
|
||||
default:
|
||||
sublog.Error().Str("outcome", string(ev.Outcome)).Msg("unknown postprocessing outcome - aborting")
|
||||
fallthrough
|
||||
case events.PPOutcomeAbort:
|
||||
metrics.UploadSessionsAborted.Inc()
|
||||
fs.completePostprocessing(ctx, session, n, ev, true, true, sublog)
|
||||
case events.PPOutcomeContinue:
|
||||
// commit re-uploads the whole file and can block for the retry window;
|
||||
// run it detached (bounded by commitLimiter) to not stall the consumer
|
||||
go func() {
|
||||
if err := fs.commitLimiter.Acquire(ctx, 1); err != nil {
|
||||
sublog.Error().Err(err).Msg("could not acquire commit slot")
|
||||
return
|
||||
}
|
||||
defer fs.commitLimiter.Release(1)
|
||||
|
||||
if err := fs.finalizeWithRetry(ctx, session, &sublog); err != nil {
|
||||
sublog.Error().Err(err).Msg("could not finalize upload after retries, reverting to a recoverable failed state")
|
||||
// revert like an abort: clears the 425 marker, frees quota, keeps bytes
|
||||
metrics.UploadSessionsCommitFailed.Inc()
|
||||
fs.completePostprocessing(ctx, session, n, ev, true, true, sublog)
|
||||
return
|
||||
}
|
||||
metrics.UploadSessionsFinalized.Inc()
|
||||
fs.completePostprocessing(ctx, session, n, ev, false, false, sublog)
|
||||
}()
|
||||
case events.PPOutcomeDelete:
|
||||
metrics.UploadSessionsDeleted.Inc()
|
||||
fs.completePostprocessing(ctx, session, n, ev, true, false, sublog)
|
||||
}
|
||||
case events.RestartPostprocessing:
|
||||
sublog := log.With().Str("event", "RestartPostprocessing").Str("uploadid", ev.UploadID).Logger()
|
||||
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to get upload")
|
||||
return
|
||||
}
|
||||
n, err := session.Node(ctx)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("could not read node")
|
||||
return
|
||||
}
|
||||
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
|
||||
s, err := session.URL(ctx)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("could not create url")
|
||||
return
|
||||
}
|
||||
|
||||
metrics.UploadSessionsRestarted.Inc()
|
||||
|
||||
// restart postprocessing
|
||||
if err := events.Publish(ctx, fs.stream, events.BytesReceived{
|
||||
UploadID: session.ID(),
|
||||
URL: s,
|
||||
SpaceOwner: n.SpaceOwnerOrManager(ctx),
|
||||
ExecutingUser: &user.User{Id: &user.UserId{OpaqueId: "postprocessing-restart"}}, // send nil instead?
|
||||
ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID},
|
||||
Filename: session.Filename(),
|
||||
Filesize: uint64(session.Size()),
|
||||
}); err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to publish BytesReceived event")
|
||||
}
|
||||
case events.CleanUpload:
|
||||
sublog := log.With().Str("event", "CleanUpload").Str("uploadid", ev.UploadID).Logger()
|
||||
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to get upload")
|
||||
return // NOTE: since we can't get the upload, we can't delete the blob
|
||||
}
|
||||
session.Cleanup(true, !ev.KeepUpload, !ev.KeepUpload, true)
|
||||
case events.RevertRevision:
|
||||
sublog := log.With().Str("event", "RevertRevision").Interface("nodeid", ev.ResourceID).Logger()
|
||||
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
|
||||
@@ -530,132 +312,6 @@ func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event,
|
||||
sublog.Error().Err(err).Msg("Failed to revert revision")
|
||||
return
|
||||
}
|
||||
case events.PostprocessingStepFinished:
|
||||
sublog := log.With().Str("event", "PostprocessingStepFinished").Str("uploadid", ev.UploadID).Logger()
|
||||
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
|
||||
sublog.Debug().Msg("ignoring event for different storage")
|
||||
return
|
||||
}
|
||||
if ev.FinishedStep != events.PPStepAntivirus {
|
||||
// atm we are only interested in antivirus results
|
||||
return
|
||||
}
|
||||
|
||||
res := ev.Result.(events.VirusscanResult)
|
||||
if res.ErrorMsg != "" {
|
||||
// scan failed somehow
|
||||
// Should we handle this here?
|
||||
return
|
||||
}
|
||||
sublog = log.With().Str("scan_description", res.Description).Bool("infected", res.Infected).Logger()
|
||||
|
||||
var n *node.Node
|
||||
switch ev.UploadID {
|
||||
case "":
|
||||
// uploadid is empty -> this was an on-demand scan
|
||||
/* ON DEMAND SCANNING NOT SUPPORTED ATM
|
||||
ctx := ctxpkg.ContextSetUser(context.Background(), ev.ExecutingUser)
|
||||
ref := &provider.Reference{ResourceId: ev.ResourceID}
|
||||
|
||||
no, err := fs.lu.NodeFromResource(ctx, ref)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to get node after scan")
|
||||
continue
|
||||
|
||||
}
|
||||
n = no
|
||||
if ev.Outcome == events.PPOutcomeDelete {
|
||||
// antivir wants us to delete the file. We must obey and need to
|
||||
|
||||
// check if there a previous versions existing
|
||||
revs, err := fs.ListRevisions(ctx, ref)
|
||||
if len(revs) == 0 {
|
||||
if err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to list revisions. Fallback to delete file")
|
||||
}
|
||||
|
||||
// no versions -> trash file
|
||||
err := fs.Delete(ctx, ref)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to delete infected resource")
|
||||
continue
|
||||
}
|
||||
|
||||
// now purge it from the recycle bin
|
||||
if err := fs.PurgeRecycleItem(ctx, &provider.Reference{ResourceId: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.SpaceID}}, n.ID, "/"); err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to purge infected resource from trash")
|
||||
}
|
||||
|
||||
// remove cache entry in gateway
|
||||
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
|
||||
continue
|
||||
}
|
||||
|
||||
// we have versions - find the newest
|
||||
versions := make(map[uint64]string) // remember all versions - we need them later
|
||||
var nv uint64
|
||||
for _, v := range revs {
|
||||
versions[v.Mtime] = v.Key
|
||||
if v.Mtime > nv {
|
||||
nv = v.Mtime
|
||||
}
|
||||
}
|
||||
|
||||
// restore newest version
|
||||
if err := fs.RestoreRevision(ctx, ref, versions[nv]); err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", versions[nv]).Msg("Failed to restore revision")
|
||||
continue
|
||||
}
|
||||
|
||||
// now find infected version
|
||||
revs, err = fs.ListRevisions(ctx, ref)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Error listing revisions after restore")
|
||||
}
|
||||
|
||||
for _, v := range revs {
|
||||
// we looking for a version that was previously not there
|
||||
if _, ok := versions[v.Mtime]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := fs.DeleteRevision(ctx, ref, v.Key); err != nil {
|
||||
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", v.Key).Msg("Failed to delete revision")
|
||||
}
|
||||
}
|
||||
|
||||
// remove cache entry in gateway
|
||||
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
|
||||
continue
|
||||
}
|
||||
*/
|
||||
default:
|
||||
// uploadid is not empty -> this is an async upload
|
||||
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to get upload")
|
||||
return
|
||||
}
|
||||
|
||||
n, err = session.Node(ctx)
|
||||
if err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to get node after scan")
|
||||
return
|
||||
}
|
||||
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
|
||||
|
||||
session.SetScanData(res.Description, res.Scandate)
|
||||
if err := session.Persist(ctx); err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to persist scan results")
|
||||
}
|
||||
}
|
||||
|
||||
if err := n.SetScanData(ctx, res.Description, res.Scandate); err != nil {
|
||||
sublog.Error().Err(err).Msg("Failed to set scan results")
|
||||
return
|
||||
}
|
||||
|
||||
metrics.UploadSessionsScanned.Inc()
|
||||
default:
|
||||
log.Error().Interface("event", ev).Msg("Unknown event")
|
||||
}
|
||||
|
||||
Generated
Vendored
-9
@@ -105,8 +105,6 @@ type AsyncPropagatorOptions struct {
|
||||
type EventOptions struct {
|
||||
NumConsumers int `mapstructure:"numconsumers"`
|
||||
ConsumerGroup string `mapstructure:"consumer_group"`
|
||||
CommitMaxRetries int `mapstructure:"commit_max_retries"`
|
||||
CommitRetryBackoff time.Duration `mapstructure:"commit_retry_backoff"`
|
||||
}
|
||||
|
||||
// TokenOptions are the configurable option for tokens
|
||||
@@ -179,12 +177,5 @@ func New(m map[string]interface{}) (*Options, error) {
|
||||
o.Events.ConsumerGroup = "dcfs"
|
||||
}
|
||||
|
||||
if o.Events.CommitMaxRetries <= 0 {
|
||||
o.Events.CommitMaxRetries = 3
|
||||
}
|
||||
if o.Events.CommitRetryBackoff <= 0 {
|
||||
o.Events.CommitRetryBackoff = 5 * time.Second
|
||||
}
|
||||
|
||||
return o, nil
|
||||
}
|
||||
-3
@@ -364,9 +364,6 @@ func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, ref *pro
|
||||
|
||||
rn, parent, restoreFunc, err := tb.fs.tp.RestoreRecycleItemFunc(ctx, ref.ResourceId.SpaceId, key, relativePath, targetNode)
|
||||
if err != nil {
|
||||
if errors.Is(err, iofs.ErrNotExist) {
|
||||
return nil, errtypes.NotFound(key)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
+9
-12
@@ -167,20 +167,17 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool,
|
||||
return err
|
||||
}
|
||||
|
||||
// link child name to parent if it is new
|
||||
// link child name to parent, create-only so a concurrent upload of the same
|
||||
// new file cannot silently clobber it: the loser gets AlreadyExists and its
|
||||
// CAS loop re-reads and retries instead of losing the update (OCISDEV-855)
|
||||
childNameLink := filepath.Join(n.ParentPath(), n.Name)
|
||||
var link string
|
||||
link, err = os.Readlink(childNameLink)
|
||||
if err == nil && link != "../"+n.ID {
|
||||
if err = os.Remove(childNameLink); err != nil {
|
||||
return errors.Wrap(err, "Decomposedfs: could not remove symlink child entry")
|
||||
}
|
||||
}
|
||||
if errors.Is(err, fs.ErrNotExist) || link != "../"+n.ID {
|
||||
relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2))
|
||||
if err = os.Symlink(relativeNodePath, childNameLink); err != nil {
|
||||
return errors.Wrap(err, "Decomposedfs: could not symlink child entry")
|
||||
relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2))
|
||||
if err = os.Symlink(relativeNodePath, childNameLink); err != nil {
|
||||
_ = os.Remove(nodePath)
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
return errtypes.AlreadyExists(n.Name)
|
||||
}
|
||||
return errors.Wrap(err, "Decomposedfs: could not symlink child entry")
|
||||
}
|
||||
|
||||
return t.Propagate(ctx, n, 0)
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"github.com/mitchellh/mapstructure"
|
||||
)
|
||||
|
||||
// AsyncConf is how a service asks for async uploads: whether they are enabled,
|
||||
// and the consumer subscription to use if they are.
|
||||
type AsyncConf struct {
|
||||
Enabled bool
|
||||
ConsumerGroup string
|
||||
NumConsumers int
|
||||
// MountID is the storage id this provider answers for, used to drop
|
||||
// postprocessing events belonging to other storages.
|
||||
MountID string
|
||||
}
|
||||
|
||||
// AsyncConfFromDriverConf reads the postprocessing settings off the driver's own
|
||||
// config keys, so the coordinator and the driver cannot disagree about them.
|
||||
func AsyncConfFromDriverConf(driverConf map[string]interface{}) AsyncConf {
|
||||
if driverConf == nil {
|
||||
return AsyncConf{}
|
||||
}
|
||||
var ac struct {
|
||||
AsyncFileUploads bool `mapstructure:"asyncfileuploads"`
|
||||
MountID string `mapstructure:"mount_id"`
|
||||
Events struct {
|
||||
NumConsumers int `mapstructure:"numconsumers"`
|
||||
ConsumerGroup string `mapstructure:"consumer_group"`
|
||||
} `mapstructure:"events"`
|
||||
}
|
||||
_ = mapstructure.Decode(driverConf, &ac)
|
||||
group := ac.Events.ConsumerGroup
|
||||
if group == "" {
|
||||
// decomposedfs's default (options.go:177). The coordinator takes over the
|
||||
// driver's subscription, so it must land in the same group.
|
||||
group = "dcfs"
|
||||
}
|
||||
return AsyncConf{
|
||||
Enabled: ac.AsyncFileUploads,
|
||||
ConsumerGroup: group,
|
||||
NumConsumers: ac.Events.NumConsumers,
|
||||
MountID: ac.MountID,
|
||||
}
|
||||
}
|
||||
+961
@@ -0,0 +1,961 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog"
|
||||
tusd "github.com/tus/tusd/v2/pkg/handler"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/chunking"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
// Coordinator owns the upload lifecycle: initiation, data transfer and listing.
|
||||
type Coordinator interface {
|
||||
// InitiateUpload returns the protocols and ids that bytes can be appended to.
|
||||
InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error)
|
||||
// GetUpload returns the session with the given id as a tusd upload.
|
||||
GetUpload(ctx context.Context, id string) (tusd.Upload, error)
|
||||
// UseIn registers the coordinator as the tusd data store.
|
||||
UseIn(composer *tusd.StoreComposer)
|
||||
// ListUploadSessions returns the upload sessions matching the given filter.
|
||||
ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error)
|
||||
// Upload writes the whole body of a non-resumable (PUT) upload and finishes it.
|
||||
Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error)
|
||||
// StartPostprocessing subscribes to postprocessing results and enables async
|
||||
// uploads. Call once, before serving requests.
|
||||
StartPostprocessing(stream events.Consumer, group, mountID string, numConsumers int) error
|
||||
}
|
||||
|
||||
// coordinator is the concrete implementation of Coordinator.
|
||||
type coordinator struct {
|
||||
fs storage.FS
|
||||
store SessionStore
|
||||
chunkHandler *chunking.ChunkHandler
|
||||
pub events.Publisher
|
||||
// async defers the commit to postprocessing. Only StartPostprocessing sets it.
|
||||
async bool
|
||||
// mountID is the storage this coordinator serves, used to drop postprocessing
|
||||
// events belonging to another one.
|
||||
mountID string
|
||||
}
|
||||
|
||||
// NewCoordinator constructs a coordinator backed by the given driver and store.
|
||||
func NewCoordinator(fs storage.FS, store SessionStore, chunkFolder string, pub events.Publisher) *coordinator {
|
||||
c := &coordinator{fs: fs, store: store, pub: pub}
|
||||
if chunkFolder != "" {
|
||||
c.chunkHandler = chunking.NewChunkHandler(chunkFolder)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// NewCoordinatorFromConfig sets up a coordinator and its file store. Pass
|
||||
// withChunking=false when only initiating uploads: chunk assembly happens on the
|
||||
// data path, so the storageprovider doesn't need it.
|
||||
func NewCoordinatorFromConfig(uploadDir string, driverConf map[string]interface{}, fs storage.FS, pub events.Publisher, log *zerolog.Logger, withChunking bool) (Coordinator, error) {
|
||||
store := NewFileStoreFromConfig(uploadDir, driverConf, log)
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("cannot determine the upload directory, set upload_directory")
|
||||
}
|
||||
if err := store.Setup(); err != nil {
|
||||
return nil, fmt.Errorf("upload directory setup failed: %w", err)
|
||||
}
|
||||
chunkFolder := ""
|
||||
if withChunking {
|
||||
chunkFolder = store.UploadDir()
|
||||
}
|
||||
return NewCoordinator(fs, store, chunkFolder, pub), nil
|
||||
}
|
||||
|
||||
// InitiateUpload resolves the target, then creates and persists the session that
|
||||
// bytes are appended to.
|
||||
func (c *coordinator) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) {
|
||||
t, err := c.resolveTarget(ctx, ref, uploadLength, metadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
session := c.store.New(ctx)
|
||||
if err := c.populateSession(ctx, session, t, uploadLength, metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := session.TouchBin(); err != nil {
|
||||
return nil, fmt.Errorf("coordinator: could not create bin file: %w", err)
|
||||
}
|
||||
if err := session.Persist(ctx); err != nil {
|
||||
session.Cleanup(ctx, true, true)
|
||||
return nil, fmt.Errorf("coordinator: could not persist session: %w", err)
|
||||
}
|
||||
|
||||
metrics.UploadSessionsInitiated.Inc()
|
||||
|
||||
// A zero-length upload has no bytes to append, so finish it here.
|
||||
if uploadLength == 0 {
|
||||
if _, err := c.finishUpload(ctx, session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]string{
|
||||
"simple": session.ID(),
|
||||
"tus": session.ID(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// populateSession writes the resolved target and the request's metadata into a
|
||||
// new session.
|
||||
func (c *coordinator) populateSession(ctx context.Context, session Session, t *uploadTarget, uploadLength int64, metadata map[string]string) error {
|
||||
session.SetMetadata("filename", t.name)
|
||||
session.SetStorageValue("NodeName", t.name)
|
||||
session.SetMetadata("dir", t.dir)
|
||||
session.SetStorageValue("Dir", t.dir)
|
||||
session.SetStorageValue("SpaceRoot", t.spaceID)
|
||||
session.SetStorageValue("NodeParentId", t.parentID)
|
||||
|
||||
if t.exists {
|
||||
session.SetStorageValue("NodeId", t.nodeID)
|
||||
session.SetStorageValue("NodeExists", "true")
|
||||
} else {
|
||||
// A new file has no id yet, and an empty one would resolve to the space root
|
||||
// (lookup.go:191), so mint a placeholder TouchFile replaces.
|
||||
session.SetStorageValue("NodeId", uuid.New().String())
|
||||
}
|
||||
|
||||
if t.spaceOwner != nil {
|
||||
session.SetStorageValue("SpaceOwnerOrManager", t.spaceOwner.GetOpaqueId())
|
||||
session.SetStorageValue("SpaceOwnerIdp", t.spaceOwner.GetIdp())
|
||||
session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(t.spaceOwner.GetType()))
|
||||
}
|
||||
if t.chunkName != "" {
|
||||
session.SetStorageValue("Chunk", t.chunkName)
|
||||
}
|
||||
|
||||
// The ctx is gone by the time the bytes arrive, so record the actor now.
|
||||
session.SetExecutant(ctxpkg.ContextMustGetUser(ctx))
|
||||
lockID, _ := ctxpkg.ContextGetLockID(ctx)
|
||||
session.SetMetadata("lockid", lockID)
|
||||
initiatorID, _ := ctxpkg.ContextGetInitiator(ctx)
|
||||
session.SetMetadata("initiatorid", initiatorID)
|
||||
|
||||
session.SetSize(uploadLength)
|
||||
|
||||
return c.applyRequestMetadata(session, metadata)
|
||||
}
|
||||
|
||||
// applyRequestMetadata stores the client's upload metadata, rejecting a malformed
|
||||
// checksum. Conditional headers are only recorded, and evaluated at finish.
|
||||
func (c *coordinator) applyRequestMetadata(session Session, metadata map[string]string) error {
|
||||
mtime, ok := metadata["mtime"]
|
||||
if !ok || mtime == "null" {
|
||||
mtime = utils.TimeToOCMtime(time.Now())
|
||||
}
|
||||
session.SetMetadata("mtime", mtime)
|
||||
|
||||
session.SetMetadata("providerID", metadata["providerID"])
|
||||
if v, ok := metadata["expires"]; ok && v != "null" {
|
||||
session.SetMetadata("expires", v)
|
||||
}
|
||||
if _, ok := metadata["sizedeferred"]; ok {
|
||||
session.SetSizeIsDeferred(true)
|
||||
}
|
||||
for _, key := range []string{"if-match", "if-none-match", "if-unmodified-since"} {
|
||||
if v := metadata[key]; v != "" {
|
||||
session.SetMetadata(key, v)
|
||||
}
|
||||
}
|
||||
|
||||
checksum, ok := metadata["checksum"]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
parts := strings.SplitN(checksum, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'")
|
||||
}
|
||||
switch parts[0] {
|
||||
case "sha1", "md5", "adler32":
|
||||
session.SetMetadata("checksum", checksum)
|
||||
default:
|
||||
return errtypes.BadRequest("unsupported checksum algorithm: " + parts[0])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Upload writes the whole body of a non-resumable (PUT) upload and finishes it.
|
||||
// req.Ref.Path carries the session id minted by InitiateUpload.
|
||||
func (c *coordinator) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) {
|
||||
// The request path arrives rooted, while session ids are stored unrooted.
|
||||
session, err := c.store.Get(ctx, strings.TrimPrefix(req.Ref.GetPath(), "/"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Behind the data gateway the request carries a transfer token, not the user.
|
||||
ctx = session.Context(ctx)
|
||||
|
||||
if chunk := session.Chunk(); chunk != "" { // legacy chunking v1
|
||||
if c.chunkHandler == nil {
|
||||
return nil, errtypes.NotSupported("coordinator: chunked uploads require a chunk folder")
|
||||
}
|
||||
assembled, assembledSize, done, aErr := c.chunkHandler.Assemble(chunk, req.Body)
|
||||
if aErr != nil {
|
||||
return nil, aErr
|
||||
}
|
||||
if !done {
|
||||
// The bytes accumulate in the chunk folder, so this session holds nothing.
|
||||
session.Cleanup(ctx, true, true)
|
||||
return nil, errtypes.PartialContent(req.Ref.String())
|
||||
}
|
||||
defer assembled.Close()
|
||||
// The declared length covers only the final chunk.
|
||||
req.Body, req.Length = assembled, assembledSize
|
||||
session.SetSize(assembledSize)
|
||||
}
|
||||
|
||||
size, err := session.WriteChunk(ctx, 0, req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size != req.Length {
|
||||
return nil, errtypes.PartialContent("coordinator: unexpected end of stream")
|
||||
}
|
||||
|
||||
ri, err := c.finishUpload(ctx, session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if uff != nil {
|
||||
executant := session.Executant()
|
||||
uff(session.SpaceOwner(), &executant, c.uploadRef(session))
|
||||
}
|
||||
return ri, nil
|
||||
}
|
||||
|
||||
// finishUpload creates the node, validates the staged bytes and commits them, or
|
||||
// hands them to postprocessing.
|
||||
func (c *coordinator) finishUpload(ctx context.Context, session Session) (*provider.ResourceInfo, error) {
|
||||
if err := c.touchNode(ctx, session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.markProcessing(ctx, session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := verifyAndStoreChecksums(ctx, session); err != nil {
|
||||
c.rollbackMarked(ctx, session)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
metrics.UploadSessionsBytesReceived.Inc()
|
||||
|
||||
if err := c.prepare(ctx, session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Without a publisher there is nothing to hand the bytes to, so commit inline.
|
||||
if c.async && c.pub != nil && session.Size() > 0 {
|
||||
if err := c.publishBytesReceived(ctx, session); err != nil {
|
||||
c.rollbackPrepared(ctx, session, session.SizeDiff())
|
||||
return nil, err
|
||||
}
|
||||
// The node stays flagged and the staged bytes are kept: postprocessing needs
|
||||
// both to finish later.
|
||||
return c.uploadedResourceInfo(ctx, session), nil
|
||||
}
|
||||
|
||||
return c.finishSync(ctx, session)
|
||||
}
|
||||
|
||||
// publishBytesReceived hands the staged upload to postprocessing, which downloads
|
||||
// the bytes from a signed URL to scan them before they are committed.
|
||||
func (c *coordinator) publishBytesReceived(ctx context.Context, session Session) error {
|
||||
url, err := session.URL(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return events.Publish(ctx, c.pub, events.BytesReceived{
|
||||
UploadID: session.ID(),
|
||||
URL: url,
|
||||
SpaceOwner: session.SpaceOwner(),
|
||||
ExecutingUser: session.ExecutantUser(),
|
||||
ResourceID: &provider.ResourceId{
|
||||
StorageId: session.ProviderID(),
|
||||
SpaceId: session.SpaceID(),
|
||||
OpaqueId: session.NodeID(),
|
||||
},
|
||||
Filename: session.Filename(),
|
||||
Filesize: uint64(session.Size()),
|
||||
ImpersonatingUser: impersonatingUser(ctx),
|
||||
})
|
||||
}
|
||||
|
||||
// touchNode creates the node a new file's upload writes to.
|
||||
func (c *coordinator) touchNode(ctx context.Context, session Session) error {
|
||||
if session.NodeExists() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The node has no id yet, so address it as a named child of its parent.
|
||||
pathRef := &provider.Reference{
|
||||
ResourceId: &provider.ResourceId{
|
||||
SpaceId: session.SpaceID(),
|
||||
OpaqueId: session.NodeParentID(),
|
||||
},
|
||||
Path: session.Filename(),
|
||||
}
|
||||
// MarkProcessing is the coordinator's own call, hence false here.
|
||||
result, err := c.fs.TouchFile(ctx, pathRef, false, session.Metadata()["mtime"])
|
||||
if err != nil {
|
||||
session.Cleanup(ctx, true, true)
|
||||
if _, ok := err.(errtypes.IsNotFound); ok {
|
||||
// The parent went away, or the share was revoked, while bytes were in flight.
|
||||
return errtypes.PreconditionFailed(err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Replaces the placeholder minted at initiate.
|
||||
session.SetStorageValue("NodeId", result.ResourceID.GetOpaqueId())
|
||||
session.SetStorageValue("SpaceRoot", result.SpaceID)
|
||||
if result.SpaceOwner != nil {
|
||||
session.SetStorageValue("SpaceOwnerOrManager", result.SpaceOwner.GetOpaqueId())
|
||||
session.SetStorageValue("SpaceOwnerIdp", result.SpaceOwner.GetIdp())
|
||||
session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(result.SpaceOwner.GetType()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// markProcessing flags the node as being processed, so clients do not read it
|
||||
// before its bytes are committed.
|
||||
func (c *coordinator) markProcessing(ctx context.Context, session Session) error {
|
||||
ref := session.Reference()
|
||||
if err := c.fs.MarkProcessing(ctx, &ref, true, session.ID()); err != nil {
|
||||
// Never marked, so there is nothing to unmark.
|
||||
session.Cleanup(ctx, true, true)
|
||||
c.deleteTouchedNode(ctx, session, &ref)
|
||||
return err
|
||||
}
|
||||
metrics.UploadProcessing.Inc()
|
||||
|
||||
// The real node id from touchNode must reach the commit, which may run in
|
||||
// another process.
|
||||
if err := session.Persist(ctx); err != nil {
|
||||
c.rollbackMarked(ctx, session)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteTouchedNode removes a node this upload created, for the one path where the
|
||||
// mark itself failed so RollbackUpload has no processing id to key off.
|
||||
func (c *coordinator) deleteTouchedNode(ctx context.Context, session Session, ref *provider.Reference) {
|
||||
if session.NodeExists() {
|
||||
return
|
||||
}
|
||||
// Delete is permission-gated, so an Uploader-only role may leave the empty file behind.
|
||||
if _, err := c.fs.Delete(ctx, ref); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not delete node after failed upload")
|
||||
}
|
||||
}
|
||||
|
||||
// prepare has the driver write the node metadata and snapshot the previous
|
||||
// version, ahead of the commit that writes the bytes.
|
||||
func (c *coordinator) prepare(ctx context.Context, session Session) error {
|
||||
ref := session.Reference()
|
||||
|
||||
info, err := uploadInfo(session)
|
||||
if err != nil {
|
||||
c.rollbackMarked(ctx, session)
|
||||
return err
|
||||
}
|
||||
|
||||
// A failed PrepareUpload has already undone its own writes.
|
||||
prepared, err := c.fs.PrepareUpload(ctx, &ref, session.ID(), info)
|
||||
if err != nil {
|
||||
c.rollbackMarked(ctx, session)
|
||||
return err
|
||||
}
|
||||
|
||||
// Persisted, not just held: the commit may run in another process, which can
|
||||
// only learn these by reading them back.
|
||||
session.SetSizeDiff(prepared.SizeDiff)
|
||||
session.SetVersionCreated(prepared.VersionCreated)
|
||||
if err := session.Persist(ctx); err != nil {
|
||||
c.rollbackPrepared(ctx, session, prepared.SizeDiff)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rollbackInfo describes the upload to undo. The ids come from the session, which
|
||||
// is the only place they survive a node whose own metadata has become unreadable.
|
||||
func rollbackInfo(session Session, sizeDiff int64) storage.RollbackInfo {
|
||||
return storage.RollbackInfo{
|
||||
NodeExisted: session.NodeExists(),
|
||||
SizeDiff: sizeDiff,
|
||||
NodeID: session.NodeID(),
|
||||
ParentID: session.NodeParentID(),
|
||||
Filename: session.Filename(),
|
||||
Size: session.Size(),
|
||||
}
|
||||
}
|
||||
|
||||
// rollbackMarked undoes a finish that failed before PrepareUpload ran, so there is
|
||||
// no revision to revert and nothing was propagated.
|
||||
func (c *coordinator) rollbackMarked(ctx context.Context, session Session) {
|
||||
ref := session.Reference()
|
||||
if !session.NodeExists() {
|
||||
// Before unmarking: RollbackUpload keys off the processing id.
|
||||
if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, 0)); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload")
|
||||
}
|
||||
}
|
||||
c.unmarkProcessing(ctx, session, &ref)
|
||||
metrics.UploadProcessing.Dec()
|
||||
session.Cleanup(ctx, true, true)
|
||||
}
|
||||
|
||||
// rollbackPrepared undoes a finish that failed after PrepareUpload succeeded.
|
||||
func (c *coordinator) rollbackPrepared(ctx context.Context, session Session, sizeDiff int64) {
|
||||
ref := session.Reference()
|
||||
// Before unmarking: RollbackUpload keys off the processing id to confirm the
|
||||
// node is still this upload's.
|
||||
if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, sizeDiff)); err != nil {
|
||||
// The session is the last record of what to undo, so keep it for a retry
|
||||
// rather than leaving the quota consumed with nothing to reclaim it from.
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload, keeping session")
|
||||
return
|
||||
}
|
||||
c.unmarkProcessing(ctx, session, &ref)
|
||||
metrics.UploadProcessing.Dec()
|
||||
session.Cleanup(ctx, true, true)
|
||||
}
|
||||
|
||||
// unmarkProcessing clears the processing flag, tolerating a node the rollback
|
||||
// already purged.
|
||||
func (c *coordinator) unmarkProcessing(ctx context.Context, session Session, ref *provider.Reference) {
|
||||
err := c.fs.MarkProcessing(ctx, ref, false, session.ID())
|
||||
log := appctx.GetLogger(ctx).With().Str("uploadid", session.ID()).Logger()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
case errtypes.IsNotFound:
|
||||
// RollbackUpload purged the node this upload created.
|
||||
log.Debug().Err(err).Msg("could not unmark processing")
|
||||
default:
|
||||
log.Error().Err(err).Msg("could not unmark processing")
|
||||
}
|
||||
}
|
||||
|
||||
// uploadInfo collects what the driver needs to write the node metadata. The
|
||||
// preconditions are re-checked there, because the resource may have changed while
|
||||
// the bytes were being uploaded.
|
||||
func uploadInfo(session Session) (storage.UploadInfo, error) {
|
||||
md := session.Metadata()
|
||||
info := storage.UploadInfo{
|
||||
NodeExisted: session.NodeExists(),
|
||||
Size: session.Size(),
|
||||
Checksums: session.Checksums(),
|
||||
IfMatch: md["if-match"],
|
||||
IfNoneMatch: md["if-none-match"],
|
||||
}
|
||||
if v := md["mtime"]; v != "" {
|
||||
mtime, err := utils.MTimeToTime(v)
|
||||
if err != nil {
|
||||
return info, errtypes.BadRequest("coordinator: invalid mtime: " + v)
|
||||
}
|
||||
info.MTime = mtime
|
||||
}
|
||||
if v := md["if-unmodified-since"]; v != "" {
|
||||
ius, err := time.Parse(time.RFC3339Nano, v)
|
||||
if err != nil {
|
||||
return info, errtypes.BadRequest("coordinator: invalid if-unmodified-since: " + v)
|
||||
}
|
||||
info.IfUnmodifiedSince = ius
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// verifyAndStoreChecksums hashes the staged bytes, checks them against the
|
||||
// checksum the client announced, and stores them for the commit.
|
||||
func verifyAndStoreChecksums(ctx context.Context, session Session) error {
|
||||
sha1h, md5h, adler32h, err := calculateChecksums(ctx, session.BinPath())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The announced checksum is not in Metadata(), so read the raw info.
|
||||
info, err := session.GetInfo(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if checksum := info.MetaData["checksum"]; checksum != "" {
|
||||
parts := strings.SplitN(checksum, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'")
|
||||
}
|
||||
var checkErr error
|
||||
switch parts[0] {
|
||||
case "sha1":
|
||||
checkErr = checkHash(parts[1], sha1h)
|
||||
case "md5":
|
||||
checkErr = checkHash(parts[1], md5h)
|
||||
case "adler32":
|
||||
checkErr = checkHash(parts[1], adler32h)
|
||||
default:
|
||||
checkErr = errtypes.BadRequest("unsupported checksum algorithm: " + parts[0])
|
||||
}
|
||||
if checkErr != nil {
|
||||
return checkErr
|
||||
}
|
||||
}
|
||||
|
||||
session.SetChecksums(sha1h.Sum(nil), md5h.Sum(nil), adler32h.Sum(nil))
|
||||
return nil
|
||||
}
|
||||
|
||||
// finishSync commits the staged bytes for an inline upload, discarding the
|
||||
// session if the commit fails: the client is still waiting and will retry, so
|
||||
// keeping the bytes would only leak them.
|
||||
func (c *coordinator) finishSync(ctx context.Context, session Session) (*provider.ResourceInfo, error) {
|
||||
ri, err := c.commit(ctx, session)
|
||||
if err != nil {
|
||||
c.rollbackPrepared(ctx, session, session.SizeDiff())
|
||||
return nil, err
|
||||
}
|
||||
return ri, nil
|
||||
}
|
||||
|
||||
// finishAsync commits the staged bytes for an upload postprocessing has cleared.
|
||||
// A failure here keeps the node marked and the session on disk, so an admin can
|
||||
// retry with RestartPostprocessing or discard it with CleanUpload. Nobody is
|
||||
// waiting on the response any more, so there is no retry but theirs.
|
||||
func (c *coordinator) finishAsync(ctx context.Context, session Session) error {
|
||||
_, err := c.commit(ctx, session)
|
||||
return err
|
||||
}
|
||||
|
||||
// commit writes the staged bytes through the driver seam and, on success, unmarks
|
||||
// the node and retires the session. It leaves a failure untouched for the caller
|
||||
// to handle, the two finish paths wanting opposite things.
|
||||
func (c *coordinator) commit(ctx context.Context, session Session) (*provider.ResourceInfo, error) {
|
||||
ref := session.Reference()
|
||||
|
||||
f, err := os.Open(session.BinPath())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The verdict rides along with the bytes, so a committed blob always carries
|
||||
// the one it was cleared under. Empty on the inline path, which never scans.
|
||||
scanResult, scanDate := session.ScanData()
|
||||
|
||||
// CommitUpload does not own the body; we opened it, so we close it.
|
||||
err = c.fs.CommitUpload(ctx, &ref, session.ID(), storage.UploadSource{
|
||||
Body: f,
|
||||
Length: session.Size(),
|
||||
ScanResult: scanResult,
|
||||
ScanDate: scanDate,
|
||||
})
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Not unmarkProcessing: the commit succeeded, so a missing node is unexpected.
|
||||
if err := c.fs.MarkProcessing(ctx, &ref, false, session.ID()); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not unmark processing")
|
||||
}
|
||||
metrics.UploadProcessing.Dec()
|
||||
session.Cleanup(ctx, true, true)
|
||||
metrics.UploadSessionsFinalized.Inc()
|
||||
|
||||
ri := c.uploadedResourceInfo(ctx, session)
|
||||
c.publishUploadReady(ctx, session, ri)
|
||||
return ri, nil
|
||||
}
|
||||
|
||||
// uploadedResourceInfo describes the uploaded resource for the caller, which turns
|
||||
// it into PUT response headers.
|
||||
//
|
||||
// TODO: the fallback carries no etag, which a write-only share used to get.
|
||||
// Returning it through the seam is the proper fix.
|
||||
func (c *coordinator) uploadedResourceInfo(ctx context.Context, session Session) *provider.ResourceInfo {
|
||||
ref := session.Reference()
|
||||
// The driver owns the resulting etag and mtime, so read them back.
|
||||
ri, err := c.fs.GetMD(ctx, &ref, nil, nil)
|
||||
if err == nil {
|
||||
// Drivers do not know their own mount id and the dataprovider does not stamp
|
||||
// it, so an unstamped id would not resolve for the client.
|
||||
if ri.GetId().GetStorageId() == "" {
|
||||
ri.Id.StorageId = session.ProviderID()
|
||||
}
|
||||
return ri
|
||||
}
|
||||
|
||||
// GetMD is permission-gated, so a write-only share cannot stat what it just
|
||||
// uploaded. That must not fail the upload.
|
||||
appctx.GetLogger(ctx).Debug().Err(err).Str("uploadid", session.ID()).Msg("could not stat uploaded resource")
|
||||
fallback := &provider.ResourceInfo{Id: ref.GetResourceId(), Size: uint64(session.Size())}
|
||||
if mtime, mErr := utils.MTimeToTime(session.Metadata()["mtime"]); mErr == nil {
|
||||
fallback.Mtime = utils.TimeToTS(mtime)
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// publishUploadReady announces that the file is available. Consumers such as the
|
||||
// search indexer only listen for UploadReady, so without it they would never learn
|
||||
// about an upload the coordinator committed inline.
|
||||
func (c *coordinator) publishUploadReady(ctx context.Context, session Session, ri *provider.ResourceInfo) {
|
||||
if c.pub == nil {
|
||||
return
|
||||
}
|
||||
if err := events.Publish(ctx, c.pub, events.UploadReady{
|
||||
UploadID: session.ID(),
|
||||
Filename: session.Filename(),
|
||||
SpaceOwner: session.SpaceOwner(),
|
||||
ExecutingUser: session.ExecutantUser(),
|
||||
FileRef: c.uploadRef(session),
|
||||
ResourceID: ri.GetId(),
|
||||
Timestamp: utils.TSNow(),
|
||||
IsVersion: session.VersionCreated(),
|
||||
ImpersonatingUser: impersonatingUser(ctx),
|
||||
}); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("failed to publish UploadReady event")
|
||||
}
|
||||
}
|
||||
|
||||
// uploadTarget is what an upload needs to know about its destination
|
||||
type uploadTarget struct {
|
||||
// exists distinguishes an overwrite from a new file.
|
||||
exists bool
|
||||
// chunkName is set for legacy chunking-v1 uploads only.
|
||||
chunkName string
|
||||
|
||||
nodeID string
|
||||
spaceID string
|
||||
parentID string
|
||||
dir string
|
||||
name string
|
||||
spaceOwner *user.UserId
|
||||
}
|
||||
|
||||
// resolveTarget locates the file an upload writes to, and rejects an upload that
|
||||
// may not proceed.
|
||||
func (c *coordinator) resolveTarget(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (*uploadTarget, error) {
|
||||
t := &uploadTarget{}
|
||||
if chunking.IsChunked(ref.GetPath()) { // check legacy chunking v1
|
||||
var err error
|
||||
ref, t.chunkName, err = rewriteChunkedRef(ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: GetMD reports a file hidden by a deny-grant as NotFound, so the upload
|
||||
// fails late with 409 instead of 403. Needs a permission-free resolve.
|
||||
existing, err := c.fs.GetMD(ctx, ref, []string{}, []string{})
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
t.exists = true
|
||||
case errtypes.IsNotFound:
|
||||
t.exists = false
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := c.checkQuota(ctx, ref, uploadLength, existing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if t.exists {
|
||||
if err := c.describeExisting(ctx, ref, existing, metadata, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err := c.describeNew(ctx, ref, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if t.name == "" {
|
||||
return nil, errtypes.BadRequest("coordinator: missing filename in ref")
|
||||
}
|
||||
if t.dir == "" {
|
||||
return nil, errtypes.BadRequest("coordinator: could not determine upload directory")
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// checkQuota rejects an upload that would not fit in the space, counting only
|
||||
// the bytes it adds.
|
||||
func (c *coordinator) checkQuota(ctx context.Context, ref *provider.Reference, uploadLength int64, existing *provider.ResourceInfo) error {
|
||||
if uploadLength < 0 {
|
||||
return nil
|
||||
}
|
||||
spaceRef := &provider.Reference{ResourceId: &provider.ResourceId{
|
||||
StorageId: ref.GetResourceId().GetStorageId(),
|
||||
SpaceId: ref.GetResourceId().GetSpaceId(),
|
||||
}}
|
||||
_, _, remaining, err := c.fs.GetQuota(ctx, spaceRef)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
netRequired := uint64(uploadLength)
|
||||
if existingSize := existing.GetSize(); existingSize < netRequired {
|
||||
netRequired -= existingSize
|
||||
} else {
|
||||
netRequired = 0
|
||||
}
|
||||
if remaining < netRequired {
|
||||
return errtypes.InsufficientStorage("quota exceeded")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// describeExisting fills in the target from the file being overwritten.
|
||||
func (c *coordinator) describeExisting(ctx context.Context, ref *provider.Reference, existing *provider.ResourceInfo, metadata map[string]string, t *uploadTarget) error {
|
||||
if !existing.GetPermissionSet().GetInitiateFileUpload() {
|
||||
return errtypes.PermissionDenied(ref.GetPath())
|
||||
}
|
||||
if existing.GetType() == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
|
||||
return errtypes.PreconditionFailed("resource is not a file")
|
||||
}
|
||||
|
||||
t.nodeID = existing.GetId().GetOpaqueId()
|
||||
t.spaceID = existing.GetId().GetSpaceId()
|
||||
t.parentID = existing.GetParentId().GetOpaqueId()
|
||||
t.name = existing.GetName()
|
||||
t.spaceOwner = c.spaceOwnerOrManager(ctx, existing.GetOwner(), t.spaceID)
|
||||
|
||||
// GetMD returns only the basename for id-based refs, so ask for the full path.
|
||||
relPath := existing.GetPath()
|
||||
if utils.IsRelativeReference(ref) {
|
||||
if full, err := c.fs.GetPathByID(ctx, existing.GetId()); err == nil {
|
||||
relPath = full
|
||||
}
|
||||
}
|
||||
t.dir = filepath.Dir(relPath)
|
||||
|
||||
// Lock before precondition, the order main checks them in (upload.go:293-302).
|
||||
if err := c.checkLock(ctx, ref); err != nil {
|
||||
return err
|
||||
}
|
||||
if metadata["if-none-match"] == "*" {
|
||||
return errtypes.Aborted(fmt.Sprintf("parent %s already has a child %s, id %s", t.parentID, t.name, t.nodeID))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// spaceOwnerOrManager resolves the space owner, falling back to a manager.
|
||||
func (c *coordinator) spaceOwnerOrManager(ctx context.Context, owner *user.UserId, spaceID string) *user.UserId {
|
||||
// A space with no personal owner stores a SPACE_OWNER placeholder (spaces.go:145).
|
||||
if owner != nil && owner.GetType() != user.UserType_USER_TYPE_SPACE_OWNER {
|
||||
return owner
|
||||
}
|
||||
|
||||
grants, err := c.fs.ListGrants(ctx, &provider.Reference{ResourceId: &provider.ResourceId{
|
||||
SpaceId: spaceID,
|
||||
OpaqueId: spaceID,
|
||||
}})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Grants come back in map order, so several managers resolve to an arbitrary one.
|
||||
for _, g := range grants {
|
||||
// Group grants carry no user id.
|
||||
uid := g.GetGrantee().GetUserId()
|
||||
if uid == nil {
|
||||
continue
|
||||
}
|
||||
p := g.GetPermissions()
|
||||
if p.GetStat() && p.GetListContainer() && p.GetInitiateFileDownload() {
|
||||
return uid
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkLock rejects an upload that conflicts with a lock held on the file.
|
||||
func (c *coordinator) checkLock(ctx context.Context, ref *provider.Reference) error {
|
||||
// An unlocked file and a driver without locks both error, so only a lock we
|
||||
// actually read counts as one.
|
||||
diskLock, err := c.fs.GetLock(ctx, ref)
|
||||
if err != nil {
|
||||
diskLock = nil
|
||||
}
|
||||
contextLockID, _ := ctxpkg.ContextGetLockID(ctx)
|
||||
|
||||
switch {
|
||||
case diskLock == nil && contextLockID != "":
|
||||
return errtypes.Aborted("not locked")
|
||||
case diskLock == nil:
|
||||
return nil
|
||||
case contextLockID == "":
|
||||
return errtypes.Locked(diskLock.LockId)
|
||||
case contextLockID != diskLock.LockId:
|
||||
return errtypes.Aborted("mismatching lock")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// describeNew fills in the target for a file that does not exist yet, from its
|
||||
// parent directory.
|
||||
func (c *coordinator) describeNew(ctx context.Context, ref *provider.Reference, t *uploadTarget) error {
|
||||
t.spaceID = ref.GetResourceId().GetSpaceId()
|
||||
t.dir = filepath.Dir(ref.GetPath())
|
||||
t.name = filepath.Base(ref.GetPath())
|
||||
|
||||
parentRef := &provider.Reference{ResourceId: ref.GetResourceId(), Path: t.dir}
|
||||
parentMD, err := c.fs.GetMD(ctx, parentRef, []string{}, []string{})
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
case errtypes.IsNotFound:
|
||||
return c.missingParentError(ctx, ref, t.dir, err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
if !parentMD.GetPermissionSet().GetInitiateFileUpload() {
|
||||
return errtypes.PermissionDenied(ref.GetPath())
|
||||
}
|
||||
t.parentID = parentMD.GetId().GetOpaqueId()
|
||||
t.spaceID = parentMD.GetId().GetSpaceId()
|
||||
|
||||
// An id-based ref yields a relative dir ("."), so ask for the parent's full path.
|
||||
if utils.IsRelativeReference(ref) {
|
||||
if parentPath, pErr := c.fs.GetPathByID(ctx, parentMD.GetId()); pErr == nil {
|
||||
t.dir = parentPath
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// missingParentError tells a missing directory apart from one that is only
|
||||
// invisible to the caller: a visible ancestor means it is missing.
|
||||
func (c *coordinator) missingParentError(ctx context.Context, ref *provider.Reference, dir string, notFound error) error {
|
||||
for ancestor := dir; ancestor != "." && ancestor != "/"; {
|
||||
ancestor = filepath.Dir(ancestor)
|
||||
ancestorRef := &provider.Reference{ResourceId: ref.GetResourceId(), Path: ancestor}
|
||||
if _, err := c.fs.GetMD(ctx, ancestorRef, []string{}, []string{}); err == nil {
|
||||
return errtypes.PreconditionFailed(notFound.Error())
|
||||
}
|
||||
}
|
||||
return errtypes.PermissionDenied(ref.GetPath())
|
||||
}
|
||||
|
||||
// rewriteChunkedRef turns a legacy chunking-v1 path into a reference to the real
|
||||
// target file, plus the chunk name.
|
||||
func rewriteChunkedRef(ref *provider.Reference) (*provider.Reference, string, error) {
|
||||
ci, err := chunking.GetChunkBLOBInfo(ref.GetPath())
|
||||
if err != nil {
|
||||
return nil, "", errtypes.BadRequest(err.Error())
|
||||
}
|
||||
return &provider.Reference{ResourceId: ref.ResourceId, Path: ci.Path}, filepath.Base(ref.GetPath()), nil
|
||||
}
|
||||
|
||||
// ListUploadSessions returns the upload sessions matching the given filter.
|
||||
func (c *coordinator) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) {
|
||||
// Only the driver can resolve a session's node, so the orphaned filter needs a
|
||||
// driver that answers the question. Assert once rather than per session.
|
||||
var orphanChecker storage.OrphanChecker
|
||||
if filter.Orphaned != nil {
|
||||
var ok bool
|
||||
if orphanChecker, ok = c.fs.(storage.OrphanChecker); !ok {
|
||||
return nil, errtypes.NotSupported("coordinator: the orphaned filter is not supported")
|
||||
}
|
||||
}
|
||||
|
||||
var sessions []Session
|
||||
if filter.ID != nil && *filter.ID != "" {
|
||||
session, err := c.store.Get(ctx, *filter.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sessions = []Session{session}
|
||||
} else {
|
||||
var err error
|
||||
sessions, err = c.store.List(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
filtered := []storage.UploadSession{}
|
||||
now := time.Now()
|
||||
for _, session := range sessions {
|
||||
if filter.Processing != nil && *filter.Processing != session.IsProcessing() {
|
||||
continue
|
||||
}
|
||||
if filter.Expired != nil {
|
||||
if *filter.Expired {
|
||||
if now.Before(session.Expires()) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if now.After(session.Expires()) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if filter.HasVirus != nil {
|
||||
sr, _ := session.ScanData()
|
||||
infected := sr != ""
|
||||
if *filter.HasVirus != infected {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// evaluated last: unlike the other filters this reads the node metadata
|
||||
// from disk, so it is only done for sessions that passed all other filters
|
||||
if filter.Orphaned != nil {
|
||||
ref := session.Reference()
|
||||
if *filter.Orphaned != orphanChecker.IsOrphaned(ctx, &ref) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
filtered = append(filtered, session)
|
||||
}
|
||||
return filtered, nil
|
||||
}
|
||||
|
||||
// uploadRef builds the reference upload events carry: the space root, plus the
|
||||
// file's path within it.
|
||||
func (c *coordinator) uploadRef(session Session) *provider.Reference {
|
||||
return &provider.Reference{
|
||||
ResourceId: &provider.ResourceId{
|
||||
StorageId: session.ProviderID(),
|
||||
SpaceId: session.SpaceID(),
|
||||
OpaqueId: session.SpaceID(),
|
||||
},
|
||||
Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())),
|
||||
}
|
||||
}
|
||||
|
||||
// impersonatingUser returns the real actor behind a borrowed identity, which
|
||||
// public link and OCM auth record in the request user's opaque.
|
||||
func impersonatingUser(ctx context.Context) *user.User {
|
||||
u, ok := ctxpkg.ContextGetUser(ctx)
|
||||
if !ok || !utils.ExistsInOpaque(u.GetOpaque(), "impersonating-user") {
|
||||
return nil
|
||||
}
|
||||
impersonating := &user.User{}
|
||||
if err := utils.ReadJSONFromOpaque(u.GetOpaque(), "impersonating-user", impersonating); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Msg("could not read impersonating user")
|
||||
return nil
|
||||
}
|
||||
return impersonating
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
iofs "io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
tusd "github.com/tus/tusd/v2/pkg/handler"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
)
|
||||
|
||||
// TokenOptions carries the JWT-signing configuration needed to produce transfer
|
||||
// URLs for the postprocessing service.
|
||||
type TokenOptions struct {
|
||||
DownloadEndpoint string
|
||||
DataGatewayEndpoint string
|
||||
TransferSharedSecret string
|
||||
TransferExpires int64
|
||||
}
|
||||
|
||||
// SessionStore abstracts upload-session persistence for the Coordinator.
|
||||
type SessionStore interface {
|
||||
New(ctx context.Context) Session
|
||||
Get(ctx context.Context, id string) (Session, error)
|
||||
List(ctx context.Context) ([]Session, error)
|
||||
}
|
||||
|
||||
// FileStore is a filesystem-backed SessionStore. Sessions are stored as a pair
|
||||
// of files in the upload directory:
|
||||
//
|
||||
// - <id>.info — JSON-encoded tusd.FileInfo
|
||||
// - <id> — staged binary bytes
|
||||
//
|
||||
// This is the same on-disk format used by OcisStore so existing sessions
|
||||
// survive a rolling deploy that switches to FileStore.
|
||||
type FileStore struct {
|
||||
uploadDir string
|
||||
opts TokenOptions
|
||||
log *zerolog.Logger
|
||||
}
|
||||
|
||||
// FileStoreFromDriverConf builds a FileStore from a reva driver config map.
|
||||
// Returns nil if the config carries no upload path (driver does not support
|
||||
// coordinated uploads). Each service that mounts the same driver calls this
|
||||
// independently.
|
||||
func FileStoreFromDriverConf(driverConf map[string]interface{}, log *zerolog.Logger) *FileStore {
|
||||
if driverConf == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// storage_root is the ocm driver's spelling of root; it stages uploads under
|
||||
// the same <root>/uploads/ layout the decomposedfs family uses.
|
||||
type driverRootConf struct {
|
||||
Root string `mapstructure:"root"`
|
||||
UploadDirectory string `mapstructure:"upload_directory"`
|
||||
StorageRoot string `mapstructure:"storage_root"`
|
||||
}
|
||||
var rc driverRootConf
|
||||
_ = mapstructure.Decode(driverConf, &rc)
|
||||
|
||||
// upload_directory already names the upload directory itself, the way
|
||||
// decomposedfs reads it (options.go:172, posix tree.go:168). The other two are
|
||||
// storage roots that stage uploads in a subdirectory, so only they get joined.
|
||||
if rc.UploadDirectory != "" {
|
||||
return newFileStoreWithTokens(rc.UploadDirectory, driverConf, log)
|
||||
}
|
||||
|
||||
root := rc.Root
|
||||
if root == "" {
|
||||
root = rc.StorageRoot
|
||||
}
|
||||
if root == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
return newFileStoreWithTokens(filepath.Join(root, "uploads"), driverConf, log)
|
||||
}
|
||||
|
||||
// NewFileStoreFromConfig builds a FileStore staging uploads in uploadDir when
|
||||
// set, falling back to the active driver config. This allows drivers that have
|
||||
// no local root (e.g. KW) to still get a coordinator by setting
|
||||
// upload_directory at the service level rather than inside the driver.
|
||||
// Returns nil only when neither source resolves to a non-empty path.
|
||||
func NewFileStoreFromConfig(uploadDir string, driverConf map[string]interface{}, log *zerolog.Logger) *FileStore {
|
||||
if uploadDir != "" {
|
||||
// Still take the tokens from the driver config: they sign the transfer URL
|
||||
// that postprocessing downloads the staged bytes from, and a service-level
|
||||
// upload directory says nothing about them.
|
||||
return newFileStoreWithTokens(uploadDir, driverConf, log)
|
||||
}
|
||||
return FileStoreFromDriverConf(driverConf, log)
|
||||
}
|
||||
|
||||
func newFileStoreWithTokens(uploadDir string, driverConf map[string]interface{}, log *zerolog.Logger) *FileStore {
|
||||
type tokenConf struct {
|
||||
DownloadEndpoint string `mapstructure:"download_endpoint"`
|
||||
DataGatewayEndpoint string `mapstructure:"datagateway_endpoint"`
|
||||
TransferSharedSecret string `mapstructure:"transfer_shared_secret"`
|
||||
TransferExpires int64 `mapstructure:"transfer_expires"`
|
||||
}
|
||||
var tc tokenConf
|
||||
if tokens, ok := driverConf["tokens"]; ok {
|
||||
_ = mapstructure.Decode(tokens, &tc)
|
||||
}
|
||||
return NewFileStore(uploadDir, TokenOptions{
|
||||
DownloadEndpoint: tc.DownloadEndpoint,
|
||||
DataGatewayEndpoint: tc.DataGatewayEndpoint,
|
||||
TransferSharedSecret: tc.TransferSharedSecret,
|
||||
TransferExpires: tc.TransferExpires,
|
||||
}, log)
|
||||
}
|
||||
|
||||
// NewFileStore creates a FileStore staging uploads in uploadDir.
|
||||
// uploadDir must be on a shared filesystem when multiple pods handle the same space.
|
||||
func NewFileStore(uploadDir string, opts TokenOptions, log *zerolog.Logger) *FileStore {
|
||||
return &FileStore{uploadDir: uploadDir, opts: opts, log: log}
|
||||
}
|
||||
|
||||
// UploadDir returns the directory this FileStore stages uploads in.
|
||||
func (fs *FileStore) UploadDir() string {
|
||||
return fs.uploadDir
|
||||
}
|
||||
|
||||
// Setup creates the upload directory eagerly so permission problems are caught
|
||||
// at startup rather than on the first upload.
|
||||
func (fs *FileStore) Setup() error {
|
||||
return os.MkdirAll(fs.uploadDir, 0700)
|
||||
}
|
||||
|
||||
// New allocates a fresh session with a new UUID.
|
||||
func (fs *FileStore) New(_ context.Context) Session {
|
||||
return &FileSession{
|
||||
store: fs,
|
||||
info: tusd.FileInfo{
|
||||
ID: uuid.New().String(),
|
||||
Storage: map[string]string{
|
||||
"Type": "OCISStore",
|
||||
},
|
||||
MetaData: tusd.MetaData{},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Get loads the session with the given id from disk.
|
||||
func (fs *FileStore) Get(ctx context.Context, id string) (Session, error) {
|
||||
infoPath := fileSessionPath(fs.uploadDir, id)
|
||||
|
||||
data, err := os.ReadFile(infoPath)
|
||||
if err != nil {
|
||||
if pathErr, ok := err.(*os.PathError); ok && pathErr.Err == syscall.ESTALE {
|
||||
return nil, tusd.ErrNotFound
|
||||
}
|
||||
if errors.Is(err, iofs.ErrNotExist) {
|
||||
return nil, tusd.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var info tusd.FileInfo
|
||||
if err := json.Unmarshal(data, &info); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
session := &FileSession{store: fs, info: info}
|
||||
|
||||
stat, err := os.Stat(session.binPath())
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, tusd.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
session.info.Offset = stat.Size()
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// List returns all sessions found in the upload directory.
|
||||
func (fs *FileStore) List(ctx context.Context) ([]Session, error) {
|
||||
infoFiles, err := filepath.Glob(filepath.Join(fs.uploadDir, "*.info"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sessions := make([]Session, 0, len(infoFiles))
|
||||
for _, path := range infoFiles {
|
||||
id := strings.TrimSuffix(filepath.Base(path), ".info")
|
||||
session, err := fs.Get(ctx, id)
|
||||
if err != nil {
|
||||
appctx.GetLogger(ctx).Error().Str("path", path).Err(err).Msg("filestore: could not load session")
|
||||
continue
|
||||
}
|
||||
sessions = append(sessions, session)
|
||||
}
|
||||
return sessions, nil
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
// This file holds the postprocessing result collector: the second half of an
|
||||
// async upload. finishUpload stages the bytes and publishes BytesReceived; the
|
||||
// postprocessing service scans them and reports back here, and only then are the
|
||||
// bytes committed through the driver seam.
|
||||
//
|
||||
// It is driver-agnostic on purpose: this logic used to live inside decomposedfs,
|
||||
// which meant only that driver could offer async uploads.
|
||||
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
// RegisteredEvents are the postprocessing events the coordinator consumes.
|
||||
var RegisteredEvents = []events.Unmarshaller{
|
||||
events.PostprocessingFinished{},
|
||||
events.PostprocessingStepFinished{},
|
||||
events.RestartPostprocessing{},
|
||||
events.CleanUpload{},
|
||||
}
|
||||
|
||||
// StartPostprocessing subscribes to postprocessing results and switches the
|
||||
// coordinator over to async uploads: from here on finished uploads stage their
|
||||
// bytes and wait for a scan verdict instead of committing inline.
|
||||
//
|
||||
// The two go together on purpose. Deferring a commit is only safe if something
|
||||
// will arrive to finish it, so there is no way to enable async without a running
|
||||
// consumer, and none to run a consumer that never receives work.
|
||||
//
|
||||
// mountID is the storage id this provider serves. Postprocessing events are
|
||||
// broadcast to every provider, so events for other storages must be dropped;
|
||||
// pass "" only in tests, where a single provider sees a private stream.
|
||||
//
|
||||
// numConsumers goroutines share the subscription. Call once, before serving
|
||||
// requests. Fails without a publisher: nothing would hand uploads to
|
||||
// postprocessing, so every one of them would wait for a verdict that never comes.
|
||||
func (c *coordinator) StartPostprocessing(stream events.Consumer, group, mountID string, numConsumers int) error {
|
||||
if c.pub == nil {
|
||||
return errors.New("coordinator: async uploads need an event publisher")
|
||||
}
|
||||
ch, err := events.Consume(stream, group, RegisteredEvents...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if numConsumers <= 0 {
|
||||
numConsumers = 1
|
||||
}
|
||||
c.mountID = mountID
|
||||
c.async = true
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
go c.Postprocessing(ch)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Postprocessing consumes postprocessing results until ch is closed. Run it in
|
||||
// its own goroutine, one per configured consumer.
|
||||
func (c *coordinator) Postprocessing(ch <-chan events.Event) {
|
||||
for event := range ch {
|
||||
c.processEvent(context.Background(), event)
|
||||
}
|
||||
}
|
||||
|
||||
// servesStorage reports whether an event is for the storage this coordinator
|
||||
// serves. Postprocessing runs as a separate service and broadcasts its results to
|
||||
// every storage provider, so each has to recognise its own. Events that name no
|
||||
// storage predate this and are accepted.
|
||||
func (c *coordinator) servesStorage(id *provider.ResourceId) bool {
|
||||
if c.mountID == "" || id.GetStorageId() == "" {
|
||||
return true
|
||||
}
|
||||
return id.GetStorageId() == c.mountID
|
||||
}
|
||||
|
||||
func (c *coordinator) processEvent(ctx context.Context, event events.Event) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
switch ev := event.Event.(type) {
|
||||
case events.PostprocessingFinished:
|
||||
if !c.servesStorage(ev.ResourceID) {
|
||||
return
|
||||
}
|
||||
c.onPostprocessingFinished(ctx, ev, log)
|
||||
case events.RestartPostprocessing:
|
||||
c.onRestartPostprocessing(ctx, ev, log)
|
||||
case events.CleanUpload:
|
||||
session, err := c.store.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("CleanUpload: could not load session")
|
||||
return
|
||||
}
|
||||
if !ev.KeepUpload {
|
||||
c.rollbackPrepared(ctx, session, session.SizeDiff())
|
||||
} else {
|
||||
c.rollbackNode(ctx, session)
|
||||
metrics.UploadProcessing.Dec()
|
||||
}
|
||||
case events.PostprocessingStepFinished:
|
||||
if !c.servesStorage(ev.ResourceID) {
|
||||
return
|
||||
}
|
||||
if ev.FinishedStep != events.PPStepAntivirus {
|
||||
// only the antivirus result is recorded on the session
|
||||
return
|
||||
}
|
||||
res, ok := ev.Result.(events.VirusscanResult)
|
||||
if !ok || res.ErrorMsg != "" {
|
||||
// the scan itself failed; PostprocessingFinished decides the outcome
|
||||
return
|
||||
}
|
||||
session, err := c.store.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
// an empty upload id means an on-demand scan, which has no session
|
||||
if ev.UploadID != "" {
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("PostprocessingStepFinished: could not load session")
|
||||
}
|
||||
return
|
||||
}
|
||||
session.SetScanData(res.Description, res.Scandate)
|
||||
metrics.UploadSessionsScanned.Inc()
|
||||
if err := session.Persist(ctx); err != nil {
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not persist scan result")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// onPostprocessingFinished completes or discards an upload according to the
|
||||
// outcome postprocessing reported.
|
||||
func (c *coordinator) onPostprocessingFinished(ctx context.Context, ev events.PostprocessingFinished, log *zerolog.Logger) {
|
||||
session, err := c.store.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
// Without the session we cannot reach the staged bytes, so they are leaked
|
||||
// here. Housekeeping cleans them up later.
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("PostprocessingFinished: could not load session")
|
||||
return
|
||||
}
|
||||
ctx = session.Context(ctx)
|
||||
log = appctx.GetLogger(ctx)
|
||||
|
||||
switch ev.Outcome {
|
||||
case events.PPOutcomeContinue:
|
||||
if err := c.finishAsync(ctx, session); err != nil {
|
||||
// Deliberately left as it is: the node stays marked and the session on
|
||||
// disk, so this can be retried with RestartPostprocessing or discarded
|
||||
// with CleanUpload rather than silently losing the bytes.
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not commit upload after postprocessing")
|
||||
c.publishUploadFailed(ctx, session, ev)
|
||||
}
|
||||
return
|
||||
case events.PPOutcomeAbort:
|
||||
metrics.UploadSessionsAborted.Inc()
|
||||
// Keep the staged bytes: an abort is a transient failure and the upload can
|
||||
// be restarted with RestartPostprocessing.
|
||||
c.rollbackNode(ctx, session)
|
||||
case events.PPOutcomeDelete:
|
||||
metrics.UploadSessionsDeleted.Inc()
|
||||
c.rollbackPrepared(ctx, session, session.SizeDiff())
|
||||
default:
|
||||
log.Error().Str("outcome", string(ev.Outcome)).Str("uploadid", ev.UploadID).Msg("unknown postprocessing outcome, aborting")
|
||||
metrics.UploadSessionsAborted.Inc()
|
||||
c.rollbackNode(ctx, session)
|
||||
}
|
||||
|
||||
c.publishUploadFailed(ctx, session, ev)
|
||||
}
|
||||
|
||||
// onRestartPostprocessing re-publishes BytesReceived so a previously aborted
|
||||
// upload gets another postprocessing run.
|
||||
func (c *coordinator) onRestartPostprocessing(ctx context.Context, ev events.RestartPostprocessing, log *zerolog.Logger) {
|
||||
session, err := c.store.Get(ctx, ev.UploadID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("RestartPostprocessing: could not load session")
|
||||
return
|
||||
}
|
||||
metrics.UploadSessionsRestarted.Inc()
|
||||
if err := c.publishBytesReceived(session.Context(ctx), session); err != nil {
|
||||
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not restart postprocessing")
|
||||
}
|
||||
}
|
||||
|
||||
// rollbackNode reverts the node to its pre-upload state but keeps the staged
|
||||
// bytes and the session, so postprocessing can be restarted.
|
||||
func (c *coordinator) rollbackNode(ctx context.Context, session Session) {
|
||||
ref := session.Reference()
|
||||
if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, session.SizeDiff())); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload, keeping session")
|
||||
return
|
||||
}
|
||||
c.unmarkProcessing(ctx, session, &ref)
|
||||
}
|
||||
|
||||
// publishUploadFailed tells consumers the upload will not become available.
|
||||
// Clients wait on UploadReady, so staying silent would leave them hanging.
|
||||
func (c *coordinator) publishUploadFailed(ctx context.Context, session Session, ev events.PostprocessingFinished) {
|
||||
if c.pub == nil {
|
||||
return
|
||||
}
|
||||
if err := events.Publish(ctx, c.pub, events.UploadReady{
|
||||
UploadID: session.ID(),
|
||||
Failed: true,
|
||||
Filename: session.Filename(),
|
||||
SpaceOwner: session.SpaceOwner(),
|
||||
ExecutingUser: ev.ExecutingUser,
|
||||
FileRef: c.uploadRef(session),
|
||||
ResourceID: &provider.ResourceId{
|
||||
StorageId: session.ProviderID(),
|
||||
SpaceId: session.SpaceID(),
|
||||
OpaqueId: session.NodeID(),
|
||||
},
|
||||
Timestamp: utils.TSNow(),
|
||||
IsVersion: session.VersionCreated(),
|
||||
ImpersonatingUser: ev.ImpersonatingUser,
|
||||
}); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("failed to publish UploadReady event")
|
||||
}
|
||||
}
|
||||
+491
@@ -0,0 +1,491 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5" //nolint:gosec
|
||||
"crypto/sha1" //nolint:gosec
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hash"
|
||||
"hash/adler32"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/renameio/v2"
|
||||
"github.com/pkg/errors"
|
||||
tusd "github.com/tus/tusd/v2/pkg/handler"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
const defaultFilePerm = os.FileMode(0664)
|
||||
|
||||
// FileSession is the Session implementation for disk-backed uploads. While an
|
||||
// upload is in progress, incoming bytes are staged in a .bin file and upload
|
||||
// metadata (size, owner, checksums, etc.) is persisted in a .info file. Both
|
||||
// survive process restarts, allowing TUS resumption.
|
||||
//
|
||||
// In scope: read/write the staged .bin file, persist/load upload metadata in the .info file.
|
||||
// Out of scope: TUS protocol, checksums, event publishing, postprocessing — those live in coordinatedUpload and coordinator.
|
||||
type FileSession struct {
|
||||
store *FileStore
|
||||
info tusd.FileInfo
|
||||
}
|
||||
|
||||
// Session is the driver-agnostic view of an upload session the Coordinator
|
||||
// needs. Implementations must be pure state (CRUD): protocol orchestration
|
||||
// belongs to coordinatedUpload or the coordinator itself.
|
||||
type Session interface {
|
||||
storage.UploadSession
|
||||
|
||||
// Data access — delegated to by coordinatedUpload for TUS reads/writes.
|
||||
GetInfo(ctx context.Context) (tusd.FileInfo, error)
|
||||
GetReader(ctx context.Context) (io.ReadCloser, error)
|
||||
WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error)
|
||||
|
||||
// Internal coordinator plumbing.
|
||||
Chunk() string
|
||||
BinPath() string
|
||||
ExecutantUser() *userpb.User
|
||||
ProviderID() string
|
||||
SpaceID() string
|
||||
NodeID() string
|
||||
NodeParentID() string
|
||||
NodeExists() bool
|
||||
Dir() string
|
||||
URL(ctx context.Context) (string, error)
|
||||
SetScanData(result string, date time.Time)
|
||||
Checksums() storage.UploadChecksums
|
||||
SetChecksums(sha1, md5, adler32 []byte)
|
||||
SizeDiff() int64
|
||||
SetSizeDiff(d int64)
|
||||
VersionCreated() bool
|
||||
SetVersionCreated(v bool)
|
||||
Metadata() map[string]string
|
||||
Persist(ctx context.Context) error
|
||||
Cleanup(ctx context.Context, cleanBin, cleanInfo bool)
|
||||
Context(ctx context.Context) context.Context
|
||||
|
||||
// Typed setters used by Coordinator.InitiateUpload to populate a new session
|
||||
// without knowing internal storage key names.
|
||||
SetStorageValue(key, value string)
|
||||
SetMetadata(key, value string)
|
||||
SetSize(size int64)
|
||||
SetSizeIsDeferred(value bool)
|
||||
SetExecutant(u *userpb.User)
|
||||
TouchBin() error
|
||||
}
|
||||
|
||||
func (s *FileSession) GetInfo(_ context.Context) (tusd.FileInfo, error) {
|
||||
return s.info, nil
|
||||
}
|
||||
|
||||
func (s *FileSession) GetReader(_ context.Context) (io.ReadCloser, error) {
|
||||
return os.Open(s.binPath())
|
||||
}
|
||||
|
||||
func (s *FileSession) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) {
|
||||
file, err := os.OpenFile(s.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
n, err := io.Copy(file, src)
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return n, err
|
||||
}
|
||||
s.info.Offset += n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Purge removes all on-disk state for this session.
|
||||
func (s *FileSession) Purge(ctx context.Context) {
|
||||
s.Cleanup(ctx, true, true)
|
||||
}
|
||||
|
||||
// ScanData returns the AV scan result and scan date stored on the session.
|
||||
func (s *FileSession) ScanData() (string, time.Time) {
|
||||
date := s.info.MetaData["scanDate"]
|
||||
if date == "" {
|
||||
return "", time.Time{}
|
||||
}
|
||||
d, _ := time.Parse(time.RFC3339, date)
|
||||
return s.info.MetaData["scanResult"], d
|
||||
}
|
||||
|
||||
// ID returns the upload session ID.
|
||||
func (s *FileSession) ID() string {
|
||||
return s.info.ID
|
||||
}
|
||||
|
||||
// Filename returns the filename stored in the session.
|
||||
func (s *FileSession) Filename() string {
|
||||
return s.info.Storage["NodeName"]
|
||||
}
|
||||
|
||||
// Size returns the declared upload size.
|
||||
func (s *FileSession) Size() int64 {
|
||||
return s.info.Size
|
||||
}
|
||||
|
||||
// Offset returns the current upload offset.
|
||||
func (s *FileSession) Offset() int64 {
|
||||
return s.info.Offset
|
||||
}
|
||||
|
||||
// Chunk returns the chunk basename stored in the session, or "" for non-chunked uploads.
|
||||
func (s *FileSession) Chunk() string {
|
||||
return s.info.Storage["Chunk"]
|
||||
}
|
||||
|
||||
// BinPath returns the path to the staged binary file.
|
||||
func (s *FileSession) BinPath() string {
|
||||
return s.binPath()
|
||||
}
|
||||
|
||||
// SpaceGid returns the numeric GID of the space owner, or "" if not set.
|
||||
func (s *FileSession) SpaceGid() string {
|
||||
return s.info.Storage["SpaceGid"]
|
||||
}
|
||||
|
||||
// ProviderID returns the storage provider ID stored in the session.
|
||||
func (s *FileSession) ProviderID() string {
|
||||
return s.info.MetaData["providerID"]
|
||||
}
|
||||
|
||||
// SpaceID returns the space (root) ID.
|
||||
func (s *FileSession) SpaceID() string {
|
||||
return s.info.Storage["SpaceRoot"]
|
||||
}
|
||||
|
||||
// NodeID returns the node ID for this upload.
|
||||
func (s *FileSession) NodeID() string {
|
||||
return s.info.Storage["NodeId"]
|
||||
}
|
||||
|
||||
// NodeParentID returns the parent node ID for this upload.
|
||||
func (s *FileSession) NodeParentID() string {
|
||||
return s.info.Storage["NodeParentId"]
|
||||
}
|
||||
|
||||
// NodeExists returns whether the target node existed when the upload was initiated.
|
||||
func (s *FileSession) NodeExists() bool {
|
||||
return s.info.Storage["NodeExists"] == "true"
|
||||
}
|
||||
|
||||
// Dir returns the directory portion of the upload path.
|
||||
func (s *FileSession) Dir() string {
|
||||
return s.info.Storage["Dir"]
|
||||
}
|
||||
|
||||
// IsProcessing returns true if all bytes are received but postprocessing has not finished.
|
||||
func (s *FileSession) IsProcessing() bool {
|
||||
return s.info.Size == s.info.Offset && s.info.MetaData["scanResult"] == ""
|
||||
}
|
||||
|
||||
// SpaceOwner returns the space owner user ID.
|
||||
func (s *FileSession) SpaceOwner() *userpb.UserId {
|
||||
return &userpb.UserId{
|
||||
OpaqueId: s.info.Storage["SpaceOwnerOrManager"],
|
||||
Idp: s.info.Storage["SpaceOwnerIdp"],
|
||||
Type: userpb.UserType(userpb.UserType_value[s.info.Storage["SpaceOwnerType"]]),
|
||||
}
|
||||
}
|
||||
|
||||
// Executant returns the user ID of the user who initiated this upload.
|
||||
func (s *FileSession) Executant() userpb.UserId {
|
||||
return userpb.UserId{
|
||||
Type: utils.UserTypeMap(s.info.Storage["UserType"]),
|
||||
Idp: s.info.Storage["Idp"],
|
||||
OpaqueId: s.info.Storage["UserId"],
|
||||
}
|
||||
}
|
||||
|
||||
// Expires returns the upload expiry time.
|
||||
func (s *FileSession) Expires() time.Time {
|
||||
var t time.Time
|
||||
if value, ok := s.info.MetaData["expires"]; ok {
|
||||
t, _ = utils.MTimeToTime(value)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// Reference returns a CS3 reference for the resource being uploaded.
|
||||
func (s *FileSession) Reference() provider.Reference {
|
||||
return provider.Reference{
|
||||
ResourceId: &provider.ResourceId{
|
||||
StorageId: s.info.MetaData["providerID"],
|
||||
SpaceId: s.info.Storage["SpaceRoot"],
|
||||
OpaqueId: s.info.Storage["NodeId"],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Checksums returns the pre-computed checksums stored on the session.
|
||||
func (s *FileSession) Checksums() storage.UploadChecksums {
|
||||
decode := func(key string) []byte {
|
||||
b, _ := hex.DecodeString(s.info.MetaData[key])
|
||||
return b
|
||||
}
|
||||
return storage.UploadChecksums{
|
||||
SHA1: decode("checksumSHA1"),
|
||||
MD5: decode("checksumMD5"),
|
||||
Adler32: decode("checksumAdler32"),
|
||||
}
|
||||
}
|
||||
|
||||
// Metadata returns the upload metadata the coordinator passes to the driver.
|
||||
func (s *FileSession) Metadata() map[string]string {
|
||||
return map[string]string{
|
||||
"providerID": s.info.MetaData["providerID"],
|
||||
"mtime": s.info.MetaData["mtime"],
|
||||
"nodeExists": s.info.Storage["NodeExists"],
|
||||
"sessionID": s.info.ID,
|
||||
"if-match": s.info.MetaData["if-match"],
|
||||
"if-none-match": s.info.MetaData["if-none-match"],
|
||||
"if-unmodified-since": s.info.MetaData["if-unmodified-since"],
|
||||
}
|
||||
}
|
||||
|
||||
// SizeDiff returns the tree size change PrepareUpload propagated optimistically.
|
||||
// Rolling an upload back has to undo exactly that amount.
|
||||
func (s *FileSession) SizeDiff() int64 {
|
||||
d, _ := strconv.ParseInt(s.info.MetaData["sizeDiff"], 10, 64)
|
||||
return d
|
||||
}
|
||||
|
||||
// SetSizeDiff records the size change PrepareUpload reported. It is persisted
|
||||
// because the async path prepares and commits in different processes, so the
|
||||
// value cannot be held in memory between the two.
|
||||
func (s *FileSession) SetSizeDiff(d int64) {
|
||||
s.info.MetaData["sizeDiff"] = strconv.FormatInt(d, 10)
|
||||
}
|
||||
|
||||
// VersionCreated reports whether this upload superseded existing content, which
|
||||
// UploadReady consumers use to tell an overwrite from a new file.
|
||||
func (s *FileSession) VersionCreated() bool {
|
||||
return s.info.MetaData["versionCreated"] == "true"
|
||||
}
|
||||
|
||||
// SetVersionCreated records what PrepareUpload reported. Persisted for the same
|
||||
// reason as the size diff: on the async path the commit runs in another process.
|
||||
func (s *FileSession) SetVersionCreated(v bool) {
|
||||
s.info.MetaData["versionCreated"] = strconv.FormatBool(v)
|
||||
}
|
||||
|
||||
// SetScanData stores AV scan results on the session.
|
||||
func (s *FileSession) SetScanData(result string, date time.Time) {
|
||||
s.info.MetaData["scanResult"] = result
|
||||
s.info.MetaData["scanDate"] = date.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// SetChecksums stores pre-computed checksums so CommitUpload can use them without
|
||||
// re-reading the binary file.
|
||||
func (s *FileSession) SetChecksums(sha1Sum, md5Sum, adler32Sum []byte) {
|
||||
s.info.MetaData["checksumSHA1"] = hex.EncodeToString(sha1Sum)
|
||||
s.info.MetaData["checksumMD5"] = hex.EncodeToString(md5Sum)
|
||||
s.info.MetaData["checksumAdler32"] = hex.EncodeToString(adler32Sum)
|
||||
}
|
||||
|
||||
// SetMetadata sets a user-visible upload metadata field.
|
||||
func (s *FileSession) SetMetadata(key, value string) {
|
||||
s.info.MetaData[key] = value
|
||||
}
|
||||
|
||||
// SetStorageValue sets an internal storage field on the session.
|
||||
func (s *FileSession) SetStorageValue(key, value string) {
|
||||
s.info.Storage[key] = value
|
||||
}
|
||||
|
||||
// SetSize updates the declared upload size.
|
||||
func (s *FileSession) SetSize(size int64) {
|
||||
s.info.Size = size
|
||||
}
|
||||
|
||||
// SetSizeIsDeferred marks the upload size as not yet known.
|
||||
func (s *FileSession) SetSizeIsDeferred(value bool) {
|
||||
s.info.SizeIsDeferred = value
|
||||
}
|
||||
|
||||
// SetExecutant stores the identity of the user who initiated the upload.
|
||||
func (s *FileSession) SetExecutant(u *userpb.User) {
|
||||
s.info.Storage["Idp"] = u.GetId().GetIdp()
|
||||
s.info.Storage["UserId"] = u.GetId().GetOpaqueId()
|
||||
s.info.Storage["UserType"] = utils.UserTypeToString(u.GetId().Type)
|
||||
s.info.Storage["UserName"] = u.GetUsername()
|
||||
s.info.Storage["UserDisplayName"] = u.GetDisplayName()
|
||||
b, _ := json.Marshal(u.GetOpaque())
|
||||
s.info.Storage["UserOpaque"] = string(b)
|
||||
g, _ := json.Marshal(u.GetGroups())
|
||||
s.info.Storage["UserGroups"] = string(g)
|
||||
}
|
||||
|
||||
// TouchBin creates the empty staging file.
|
||||
func (s *FileSession) TouchBin() error {
|
||||
f, err := os.OpenFile(s.binPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// Persist writes the session metadata atomically to disk.
|
||||
func (s *FileSession) Persist(ctx context.Context) error {
|
||||
infoPath := s.infoPath()
|
||||
if err := os.MkdirAll(filepath.Dir(infoPath), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := json.Marshal(s.info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return renameio.WriteFile(infoPath, d, 0600)
|
||||
}
|
||||
|
||||
// Cleanup removes the staged binary and/or info file.
|
||||
// Node deletion and processing flag changes are the coordinator's responsibility.
|
||||
func (s *FileSession) Cleanup(ctx context.Context, cleanBin, cleanInfo bool) {
|
||||
if cleanBin {
|
||||
if err := os.Remove(s.binPath()); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
appctx.GetLogger(ctx).Error().Str("path", s.binPath()).Err(err).Msg("filestore: removing staged binary failed")
|
||||
}
|
||||
}
|
||||
if cleanInfo {
|
||||
if err := os.Remove(s.infoPath()); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
appctx.GetLogger(ctx).Error().Str("path", s.infoPath()).Err(err).Msg("filestore: removing session info failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Context reconstructs a context carrying the user, logger, lock ID, and
|
||||
// initiator ID that were recorded when the upload was initiated.
|
||||
func (s *FileSession) Context(ctx context.Context) context.Context {
|
||||
sub := s.store.log.With().Int("pid", os.Getpid()).Logger()
|
||||
ctx = appctx.WithLogger(ctx, &sub)
|
||||
ctx = ctxpkg.ContextSetLockID(ctx, s.info.MetaData["lockid"])
|
||||
ctx = ctxpkg.ContextSetUser(ctx, s.ExecutantUser())
|
||||
return ctxpkg.ContextSetInitiator(ctx, s.info.MetaData["initiatorid"])
|
||||
}
|
||||
|
||||
// URL returns a signed JWT URL that the postprocessing service can use to
|
||||
// download the staged binary via the data gateway.
|
||||
func (s *FileSession) URL(_ context.Context) (string, error) {
|
||||
type transferClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
target := joinURLParts(s.store.opts.DownloadEndpoint, "tus/", s.info.ID)
|
||||
ttl := time.Duration(s.store.opts.TransferExpires) * time.Second
|
||||
claims := transferClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
|
||||
Audience: jwt.ClaimStrings{"reva"},
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
Target: target,
|
||||
}
|
||||
t := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
|
||||
tkn, err := t.SignedString([]byte(s.store.opts.TransferSharedSecret))
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(err, "filestore: error signing transfer token with claims %+v", claims)
|
||||
}
|
||||
return joinURLParts(s.store.opts.DataGatewayEndpoint, tkn), nil
|
||||
}
|
||||
|
||||
func (s *FileSession) ToFileInfo() tusd.FileInfo {
|
||||
return s.info
|
||||
}
|
||||
|
||||
func (s *FileSession) InitiatorID() string {
|
||||
return s.info.MetaData["initiatorid"]
|
||||
}
|
||||
|
||||
func (s *FileSession) binPath() string {
|
||||
return filepath.Join(s.store.uploadDir, s.info.ID)
|
||||
}
|
||||
|
||||
func (s *FileSession) infoPath() string {
|
||||
return fileSessionPath(s.store.uploadDir, s.info.ID)
|
||||
}
|
||||
|
||||
// ExecutantUser returns the full identity of the user who initiated the upload.
|
||||
// Upload events must carry it rather than the bare id from Executant(): consumers
|
||||
// read the display name straight off the event and do not look it up, so an
|
||||
// id-only user reaches the activity feed with a blank name.
|
||||
func (s *FileSession) ExecutantUser() *userpb.User {
|
||||
var o *typespb.Opaque
|
||||
_ = json.Unmarshal([]byte(s.info.Storage["UserOpaque"]), &o)
|
||||
var groups []string
|
||||
_ = json.Unmarshal([]byte(s.info.Storage["UserGroups"]), &groups)
|
||||
return &userpb.User{
|
||||
Id: &userpb.UserId{
|
||||
Type: utils.UserTypeMap(s.info.Storage["UserType"]),
|
||||
Idp: s.info.Storage["Idp"],
|
||||
OpaqueId: s.info.Storage["UserId"],
|
||||
},
|
||||
Username: s.info.Storage["UserName"],
|
||||
DisplayName: s.info.Storage["UserDisplayName"],
|
||||
Opaque: o,
|
||||
Groups: groups,
|
||||
}
|
||||
}
|
||||
|
||||
// fileSessionPath returns the path to the .info file for the given session ID.
|
||||
func fileSessionPath(uploadDir, id string) string {
|
||||
return filepath.Join(uploadDir, id+".info")
|
||||
}
|
||||
|
||||
// calculateChecksums computes sha1, md5, and adler32 in a single pass over path.
|
||||
func calculateChecksums(_ context.Context, path string) (hash.Hash, hash.Hash, hash.Hash32, error) {
|
||||
sha1h := sha1.New() //nolint:gosec
|
||||
md5h := md5.New() //nolint:gosec
|
||||
adler32h := adler32.New()
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r1 := io.TeeReader(f, sha1h)
|
||||
r2 := io.TeeReader(r1, md5h)
|
||||
if _, err = io.Copy(adler32h, r2); err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
return sha1h, md5h, adler32h, nil
|
||||
}
|
||||
|
||||
func checkHash(expected string, h hash.Hash) error {
|
||||
got := hex.EncodeToString(h.Sum(nil))
|
||||
if expected != got {
|
||||
return errtypes.ChecksumMismatch(fmt.Sprintf("invalid checksum: expected %s got %s", expected, got))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// joinURLParts concatenates URL path segments, inserting "/" between them if needed.
|
||||
func joinURLParts(parts ...string) string {
|
||||
var b strings.Builder
|
||||
for i, p := range parts {
|
||||
b.WriteString(p)
|
||||
if i < len(parts)-1 && !strings.HasSuffix(p, "/") {
|
||||
b.WriteByte('/')
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
tusd "github.com/tus/tusd/v2/pkg/handler"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
)
|
||||
|
||||
var errNotImplemented = tusd.NewError("ERR_NOT_IMPLEMENTED", "use InitiateUpload on the CS3 API to start a new upload", http.StatusNotImplemented)
|
||||
|
||||
// tusAdapter adapts a single upload session to tusd's Upload interfaces.
|
||||
type tusAdapter struct {
|
||||
session Session
|
||||
coord *coordinator
|
||||
}
|
||||
|
||||
func (u *tusAdapter) GetInfo(ctx context.Context) (tusd.FileInfo, error) {
|
||||
return u.session.GetInfo(ctx)
|
||||
}
|
||||
|
||||
func (u *tusAdapter) GetReader(ctx context.Context) (io.ReadCloser, error) {
|
||||
return u.session.GetReader(ctx)
|
||||
}
|
||||
|
||||
func (u *tusAdapter) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) {
|
||||
return u.session.WriteChunk(ctx, offset, src)
|
||||
}
|
||||
|
||||
// FinishUpload runs the coordinator's finish path once all bytes have arrived.
|
||||
func (u *tusAdapter) FinishUpload(ctx context.Context) error {
|
||||
_, err := u.coord.finishUpload(u.session.Context(ctx), u.session)
|
||||
|
||||
// tusd answers an error type it does not recognise with a bare 500.
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
return nil
|
||||
case errtypes.AlreadyExists:
|
||||
return tusd.NewError("ERR_ALREADY_EXISTS", err.Error(), http.StatusConflict)
|
||||
case errtypes.ResourceProcessing, errtypes.TooEarly:
|
||||
return tusd.NewError("ERR_TOO_EARLY", err.Error(), http.StatusTooEarly)
|
||||
case errtypes.Aborted:
|
||||
return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusPreconditionFailed)
|
||||
case errtypes.PreconditionFailed:
|
||||
return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusMethodNotAllowed)
|
||||
case errtypes.Locked:
|
||||
return tusd.NewError("ERR_LOCKED", err.Error(), http.StatusLocked)
|
||||
case errtypes.BadRequest:
|
||||
return tusd.NewError("ERR_BAD_REQUEST", err.Error(), http.StatusBadRequest)
|
||||
case errtypes.ChecksumMismatch:
|
||||
return tusd.NewError("ERR_CHECKSUM_MISMATCH", err.Error(), errtypes.StatusChecksumMismatch)
|
||||
case errtypes.IsPermissionDenied:
|
||||
return tusd.NewError("ERR_PERMISSION_DENIED", err.Error(), http.StatusForbidden)
|
||||
case errtypes.InsufficientStorage:
|
||||
return tusd.NewError("ERR_INSUFFICIENT_STORAGE", err.Error(), http.StatusInsufficientStorage)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Terminate discards an upload, so a cancelled one leaves nothing behind.
|
||||
func (u *tusAdapter) Terminate(ctx context.Context) error {
|
||||
ref := u.session.Reference()
|
||||
|
||||
// Rollback rather than Delete, which is permission-gated. It is a no-op unless
|
||||
// this upload still owns the node.
|
||||
if err := u.coord.fs.RollbackUpload(ctx, &ref, u.session.ID(), rollbackInfo(u.session, u.session.SizeDiff())); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", u.session.ID()).Msg("could not roll back terminated upload, keeping session")
|
||||
return err
|
||||
}
|
||||
// A node that was never created cannot be unmarked, which is the normal case here.
|
||||
if err := u.coord.fs.MarkProcessing(ctx, &ref, false, u.session.ID()); err != nil {
|
||||
appctx.GetLogger(ctx).Debug().Err(err).Str("uploadid", u.session.ID()).Msg("could not unmark terminated upload")
|
||||
}
|
||||
|
||||
u.session.Cleanup(ctx, true, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeclareLength records the total size for uploads initiated without one.
|
||||
func (u *tusAdapter) DeclareLength(ctx context.Context, length int64) error {
|
||||
u.session.SetSize(length)
|
||||
u.session.SetSizeIsDeferred(false)
|
||||
return u.session.Persist(ctx)
|
||||
}
|
||||
|
||||
// ConcatUploads appends the staged bytes of the partial uploads, in the order given.
|
||||
func (u *tusAdapter) ConcatUploads(ctx context.Context, partials []tusd.Upload) error {
|
||||
file, err := os.OpenFile(u.session.BinPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
for _, partial := range partials {
|
||||
p, ok := partial.(*tusAdapter)
|
||||
if !ok {
|
||||
return fmt.Errorf("coordinator: unexpected partial upload type %T", partial)
|
||||
}
|
||||
src, err := p.session.GetReader(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(file, src)
|
||||
src.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UseIn registers the coordinator as tusd's data store, in place of the driver's own.
|
||||
func (c *coordinator) UseIn(composer *tusd.StoreComposer) {
|
||||
composer.UseCore(c)
|
||||
composer.UseTerminater(c)
|
||||
composer.UseConcater(c)
|
||||
composer.UseLengthDeferrer(c)
|
||||
}
|
||||
|
||||
// NewUpload is unsupported: uploads always start through the CS3 InitiateUpload call.
|
||||
func (c *coordinator) NewUpload(_ context.Context, _ tusd.FileInfo) (tusd.Upload, error) {
|
||||
return nil, errNotImplemented
|
||||
}
|
||||
|
||||
// GetUpload wraps the session with the given id for the TUS data path.
|
||||
func (c *coordinator) GetUpload(ctx context.Context, id string) (tusd.Upload, error) {
|
||||
session, err := c.store.Get(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tusAdapter{session: session, coord: c}, nil
|
||||
}
|
||||
|
||||
// The As* methods let tusd reach the extension interfaces on a plain tusd.Upload.
|
||||
|
||||
func (c *coordinator) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload {
|
||||
return up.(*tusAdapter)
|
||||
}
|
||||
|
||||
func (c *coordinator) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload {
|
||||
return up.(*tusAdapter)
|
||||
}
|
||||
|
||||
func (c *coordinator) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload {
|
||||
return up.(*tusAdapter)
|
||||
}
|
||||
Vendored
+2
-1
@@ -1321,7 +1321,7 @@ github.com/orcaman/concurrent-map
|
||||
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
## explicit; go 1.18
|
||||
github.com/owncloud/libre-graph-api-go
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20260917145219-ba14a94a3c7a
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20260916115339-d8ba9085f572
|
||||
## explicit; go 1.26.0
|
||||
github.com/owncloud/reva/v2/cmd/revad/internal/grace
|
||||
github.com/owncloud/reva/v2/cmd/revad/runtime
|
||||
@@ -1684,6 +1684,7 @@ github.com/owncloud/reva/v2/pkg/token/manager/jwt
|
||||
github.com/owncloud/reva/v2/pkg/token/manager/loader
|
||||
github.com/owncloud/reva/v2/pkg/token/manager/registry
|
||||
github.com/owncloud/reva/v2/pkg/trace
|
||||
github.com/owncloud/reva/v2/pkg/upload
|
||||
github.com/owncloud/reva/v2/pkg/user
|
||||
github.com/owncloud/reva/v2/pkg/user/manager/demo
|
||||
github.com/owncloud/reva/v2/pkg/user/manager/json
|
||||
|
||||
Reference in new issue
Block a user