Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2e9f73afc | ||
|
|
e505ae98f1 |
No files matched your search
@@ -67,7 +67,7 @@ require (
|
||||
github.com/open-policy-agent/opa v1.21.1
|
||||
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-20261006170644-bac0e1ee144a
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261007080847-2cb387523ac7
|
||||
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-20261006170644-bac0e1ee144a h1:gUe35SzqPHF+xkEUlyqnN9ZVwTVBBQQ0fmzV/1dLHjQ=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261006170644-bac0e1ee144a/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261007080847-2cb387523ac7 h1:wIL6E2Lu4hVcU44qa1rjo+dp90++/aQeUe4tAjifRAg=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261007080847-2cb387523ac7/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
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"],
|
||||
|
||||
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},
|
||||
|
||||
+7
@@ -190,6 +190,13 @@ func (fs *posixFS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool
|
||||
return fs.FS.(storage.OrphanChecker).IsOrphaned(ctx, ref)
|
||||
}
|
||||
|
||||
// PrepareCreatesNode reports whether the wrapped driver's PrepareUpload creates a
|
||||
// new file's node.
|
||||
func (fs *posixFS) PrepareCreatesNode() bool {
|
||||
nc, ok := fs.FS.(storage.NodeCreator)
|
||||
return ok && nc.PrepareCreatesNode()
|
||||
}
|
||||
|
||||
// UseIn tells the tus upload middleware which extensions it supports.
|
||||
func (fs *posixFS) UseIn(composer *tusd.StoreComposer) {
|
||||
fs.FS.(storage.ComposableFS).UseIn(composer)
|
||||
|
||||
+37
-6
@@ -717,34 +717,65 @@ func (t *Tree) ResolveSpaceIDIndexEntry(spaceid, entry string) (string, string,
|
||||
func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (metadata.UnlockFunc, error) {
|
||||
_, span := tracer.Start(ctx, "InitNewNode")
|
||||
defer span.End()
|
||||
// The node is not cached yet, so its path comes from the parent and the name.
|
||||
nodePath := filepath.Join(n.ParentPath(), n.Name)
|
||||
|
||||
// create folder structure (if needed)
|
||||
if err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700); err != nil {
|
||||
if err := os.MkdirAll(filepath.Dir(nodePath), 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create and write lock new node metadata
|
||||
unlock, err := t.lookup.MetadataBackend().Lock(n.InternalPath())
|
||||
unlock, err := t.lookup.MetadataBackend().Lock(nodePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// we also need to touch the actual node file here it stores the mtime of the resource
|
||||
h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600)
|
||||
h, err := os.OpenFile(nodePath, os.O_CREATE|os.O_EXCL, 0600)
|
||||
if err != nil {
|
||||
// The file is not ours: leave it, and its cache entry, alone.
|
||||
releaseNewNodeLock(ctx, n, unlock)
|
||||
if os.IsExist(err) {
|
||||
return unlock, errtypes.AlreadyExists(n.InternalPath())
|
||||
// The name only: the message reaches the client, the path is the server's.
|
||||
return nil, errtypes.AlreadyExists(n.Name)
|
||||
}
|
||||
return unlock, err
|
||||
return nil, err
|
||||
}
|
||||
h.Close()
|
||||
|
||||
// From here the file is ours. A failure removes it and our cache entry
|
||||
// before unlocking, so nothing can open the node in between.
|
||||
fail := func(err error) (metadata.UnlockFunc, error) {
|
||||
if rErr := os.Remove(nodePath); rErr != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(rErr).Str("nodeid", n.ID).Msg("could not remove new node file")
|
||||
}
|
||||
if dErr := t.lookup.(*lookup.Lookup).IDCache.Delete(ctx, n.SpaceID, n.ID); dErr != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(dErr).Str("nodeid", n.ID).Msg("could not remove new node from the id cache")
|
||||
}
|
||||
releaseNewNodeLock(ctx, n, unlock)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Cached only now that the name is ours, so a losing upload cannot point it at its id.
|
||||
if err := t.lookup.(*lookup.Lookup).CacheID(ctx, n.SpaceID, n.ID, nodePath); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
if _, err := node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize); err != nil {
|
||||
return unlock, err
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
return unlock, nil
|
||||
}
|
||||
|
||||
// releaseNewNodeLock releases the lock of a node InitNewNode failed to create.
|
||||
func releaseNewNodeLock(ctx context.Context, n *node.Node, unlock metadata.UnlockFunc) {
|
||||
if err := unlock(); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not release new node lock")
|
||||
}
|
||||
}
|
||||
|
||||
// TODO check if node exists?
|
||||
func (t *Tree) createDirNode(ctx context.Context, n *node.Node) (err error) {
|
||||
ctx, span := tracer.Start(ctx, "createDirNode")
|
||||
|
||||
+8
-2
@@ -83,11 +83,16 @@ type UploadInfo struct {
|
||||
IfMatch string
|
||||
IfNoneMatch string
|
||||
IfUnmodifiedSince time.Time
|
||||
// Where a new file goes, for a driver whose PrepareUpload creates it. Empty
|
||||
// leaves a missing node NotFound.
|
||||
ParentID string
|
||||
Name string
|
||||
}
|
||||
|
||||
type PrepareUploadResult struct {
|
||||
VersionCreated bool
|
||||
SizeDiff int64
|
||||
SpaceOwner *userpb.UserId // the space owner or a manager, for a new node; nil keeps the one already known
|
||||
}
|
||||
|
||||
// RollbackInfo carries what a driver needs to undo PrepareUpload. NodeID and
|
||||
@@ -135,7 +140,7 @@ type FS interface {
|
||||
// CreateDir creates a resource of type container
|
||||
CreateDir(ctx context.Context, ref *provider.Reference) (*CreateDirResult, error)
|
||||
// TouchFile sets the mtime of a resource, creating an empty file if it does not exist
|
||||
// FIXME(OCISDEV-900) remove markprocessing bool: coordinator calls MarkProcessing(true) explicitly after TouchFile
|
||||
// FIXME(OCISDEV-900) remove markprocessing bool: PrepareUpload marks the node the coordinator touched
|
||||
// FIXME the mtime should either be a time.Time or a CS3 Timestamp, not a string
|
||||
TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*TouchFileResult, error)
|
||||
// Delete deletes a resource.
|
||||
@@ -155,7 +160,8 @@ type FS interface {
|
||||
CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source UploadSource) error
|
||||
// PrepareUpload is called after all bytes are received and before postprocessing begins.
|
||||
// Implementations may lock the target node, snapshot the previous version, write new metadata,
|
||||
// and propagate size changes. Drivers that do not require any of these steps may return immediately.
|
||||
// mark the node as processing for sessionID, and propagate size changes. Drivers that do not
|
||||
// require any of these steps may return immediately.
|
||||
PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info UploadInfo) (*PrepareUploadResult, error)
|
||||
// RollbackUpload reverts node state after a failed or aborted postprocessing run.
|
||||
// It is the inverse of PrepareUpload: restores previous metadata and reverts the optimistic
|
||||
|
||||
+8
@@ -70,6 +70,14 @@ type OrphanChecker interface {
|
||||
IsOrphaned(ctx context.Context, ref *provider.Reference) bool
|
||||
}
|
||||
|
||||
// NodeCreator defines the interface for FS implementations whose PrepareUpload
|
||||
// creates a new file's node from UploadInfo.ParentID and Name, so an upload need
|
||||
// not TouchFile it first.
|
||||
type NodeCreator interface {
|
||||
// PrepareCreatesNode reports whether PrepareUpload creates a missing node.
|
||||
PrepareCreatesNode() bool
|
||||
}
|
||||
|
||||
// UploadSession is the interface that storage drivers need to return whan listing upload sessions.
|
||||
type UploadSession interface {
|
||||
// ID returns the upload id
|
||||
|
||||
Generated
Vendored
+13
-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")
|
||||
}
|
||||
@@ -672,6 +328,11 @@ func (fs *Decomposedfs) Capabilities(_ context.Context) storage.Capabilities {
|
||||
return storage.FullCapabilities()
|
||||
}
|
||||
|
||||
// PrepareCreatesNode reports that PrepareUpload creates a new file's node.
|
||||
func (fs *Decomposedfs) PrepareCreatesNode() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// GetQuota returns the quota available
|
||||
// TODO Document in the cs3 should we return quota or free space?
|
||||
func (fs *Decomposedfs) GetQuota(ctx context.Context, ref *provider.Reference) (total uint64, inUse uint64, remaining uint64, err error) {
|
||||
|
||||
+34
-17
@@ -168,20 +168,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")
|
||||
}
|
||||
|
||||
if storage.SkipTouchPropagation(ctx) {
|
||||
@@ -708,18 +705,31 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
|
||||
h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600)
|
||||
subspan.End()
|
||||
if err != nil {
|
||||
// The node file is not ours, so there is nothing of ours to remove.
|
||||
releaseNewNodeLock(ctx, n, unlock)
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
return unlock, errtypes.AlreadyExists(n.Name)
|
||||
return nil, errtypes.AlreadyExists(n.Name)
|
||||
}
|
||||
return unlock, err
|
||||
return nil, err
|
||||
}
|
||||
h.Close()
|
||||
|
||||
// From here the node file is ours, but the name may not be: a failure removes
|
||||
// the node file and leaves the name to whichever upload linked it. Removed
|
||||
// before unlocking, so nothing can open the node in between.
|
||||
fail := func(err error) (metadata.UnlockFunc, error) {
|
||||
if rErr := os.Remove(n.InternalPath()); rErr != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(rErr).Str("nodeid", n.ID).Msg("could not remove new node file")
|
||||
}
|
||||
releaseNewNodeLock(ctx, n, unlock)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, subspan = tracer.Start(ctx, "node.CheckQuota")
|
||||
_, err = node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize)
|
||||
subspan.End()
|
||||
if err != nil {
|
||||
return unlock, err
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
// link child name to parent if it is new
|
||||
@@ -735,15 +745,22 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
|
||||
log.Info().Err(err).Msg("initNewNode: symlink failed")
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
log.Info().Err(err).Msg("initNewNode: symlink already exists")
|
||||
return unlock, errtypes.AlreadyExists(n.Name)
|
||||
return fail(errtypes.AlreadyExists(n.Name))
|
||||
}
|
||||
return unlock, errors.Wrap(err, "Decomposedfs: could not symlink child entry")
|
||||
return fail(errors.Wrap(err, "Decomposedfs: could not symlink child entry"))
|
||||
}
|
||||
log.Info().Msg("initNewNode: symlink created")
|
||||
|
||||
return unlock, nil
|
||||
}
|
||||
|
||||
// releaseNewNodeLock releases the lock of a node InitNewNode failed to create.
|
||||
func releaseNewNodeLock(ctx context.Context, n *node.Node, unlock metadata.UnlockFunc) {
|
||||
if err := unlock(); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not release new node lock")
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Tree) removeNode(ctx context.Context, path, timeSuffix string, n *node.Node) error {
|
||||
logger := appctx.GetLogger(ctx)
|
||||
|
||||
|
||||
+111
-15
@@ -434,8 +434,9 @@ func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Referenc
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrepareUpload finalizes node metadata after bytes are received, before postprocessing.
|
||||
// CommitUpload is called after postprocessing completes.
|
||||
// PrepareUpload finalizes node metadata after bytes are received, before postprocessing,
|
||||
// and marks the node as processing for sessionID. CommitUpload is called after
|
||||
// postprocessing completes.
|
||||
func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
|
||||
ctx, span := tracer.Start(ctx, "PrepareUpload")
|
||||
defer span.End()
|
||||
@@ -445,15 +446,50 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
appctx.GetLogger(ctx).Error().Err(err).Msg("PrepareUpload: unexpected NodeFromResource failure")
|
||||
return nil, errtypes.InternalError("PrepareUpload: node lookup failed unexpectedly")
|
||||
}
|
||||
if !n.Exists {
|
||||
// A new file nobody has created yet: PrepareUpload creates it, under the id the
|
||||
// ref already carries.
|
||||
create := !n.Exists && !info.NodeExisted && info.ParentID != "" && info.Name != ""
|
||||
if !n.Exists && !create {
|
||||
return nil, errtypes.NotFound(ref.String())
|
||||
}
|
||||
if create {
|
||||
if err := fs.checkNewFileParent(ctx, n.SpaceID, info); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.ParentID = info.ParentID
|
||||
n.Name = info.Name
|
||||
}
|
||||
|
||||
committed := false
|
||||
// Only a node this upload created is purged, and one it is creating only once the
|
||||
// name is its own: Purge removes the name link by name.
|
||||
purge := !info.NodeExisted && !create
|
||||
// This upload created the node, so a failure must not leave it behind as an
|
||||
// empty file. Purge, not trash: it never had content, and Purge needs no
|
||||
// Delete permission. Registered before the lock is taken, so it runs once the
|
||||
// lock is released. Purge leaves the lock file alone: InitNewNode's unlock
|
||||
// removes it, a plain lockedfile's does not.
|
||||
defer func() {
|
||||
if committed || !purge {
|
||||
return
|
||||
}
|
||||
if err := n.Purge(ctx); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not purge new node after failed prepare")
|
||||
}
|
||||
}()
|
||||
|
||||
n.SpaceRoot, err = node.ReadNode(ctx, fs.lu, n.SpaceID, n.SpaceID, false, nil, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := n.CheckLock(ctx); err != nil {
|
||||
if create {
|
||||
// A node still to be created holds no lock, so any lock id is a mismatch, the
|
||||
// answer CheckLock would give, here without creating the node first.
|
||||
if lockID, _ := ctxpkg.ContextGetLockID(ctx); lockID != "" {
|
||||
return nil, errtypes.Aborted("not locked")
|
||||
}
|
||||
} else if err := n.CheckLock(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -468,12 +504,27 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
}
|
||||
}
|
||||
|
||||
targetPath := n.InternalPath()
|
||||
f, err := lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(targetPath), os.O_RDWR|os.O_CREATE, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
var (
|
||||
f *lockedfile.File
|
||||
unlock func() error
|
||||
)
|
||||
if create {
|
||||
// InitNewNode refuses a name already taken, checks the quota, and on failure
|
||||
// removes what it made and releases its lock. Its lock is the one PrepareUpload
|
||||
// would take, so it is kept rather than taken again.
|
||||
unlock, err = fs.tp.InitNewNode(ctx, n, uint64(info.Size))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
purge = true
|
||||
} else {
|
||||
f, err = lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_RDWR|os.O_CREATE, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
unlock = func() error { return f.Close() }
|
||||
}
|
||||
unlock := func() error { return f.Close() }
|
||||
targetPath := n.InternalPath()
|
||||
defer func() {
|
||||
if err := unlock(); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not close lock")
|
||||
@@ -486,7 +537,6 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
versionPath string
|
||||
oldAttrs node.Attributes
|
||||
oldMtime time.Time
|
||||
committed bool
|
||||
)
|
||||
|
||||
defer func() {
|
||||
@@ -507,6 +557,13 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
if err := n.SetXattrsWithContext(ctx, oldAttrs, false); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not restore node xattrs during rollback")
|
||||
}
|
||||
// Restoring only rewrites the old keys, so the mark this upload added would
|
||||
// stay, and with the session discarded nothing else would ever remove it.
|
||||
if _, ok := oldAttrs[prefixes.StatusPrefix]; !ok {
|
||||
if err := n.RemoveXattr(ctx, prefixes.StatusPrefix, false); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not remove processing mark during rollback")
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -525,9 +582,12 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
}
|
||||
|
||||
// also for new files: the coordinator's check fails open without GetQuota
|
||||
// permission, and CheckQuota guards disk space too
|
||||
if _, err := node.CheckQuota(ctx, n.SpaceRoot, overwrite, uint64(oldBlobsize), uint64(info.Size)); err != nil {
|
||||
return nil, err
|
||||
// permission, and CheckQuota guards disk space too. InitNewNode has checked a
|
||||
// node it created.
|
||||
if !create {
|
||||
if _, err := node.CheckQuota(ctx, n.SpaceRoot, overwrite, uint64(oldBlobsize), uint64(info.Size)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if info.NodeExisted {
|
||||
@@ -607,7 +667,8 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
|
||||
sizeDiff = info.Size - old.Blobsize
|
||||
} else {
|
||||
if c, ok := fs.lu.(node.IDCacher); ok {
|
||||
// InitNewNode has cached a node it created
|
||||
if c, ok := fs.lu.(node.IDCacher); ok && !create {
|
||||
if err := c.CacheID(ctx, n.SpaceID, n.ID, filepath.Join(n.ParentPath(), n.Name)); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Msg("failed to cache id")
|
||||
}
|
||||
@@ -625,6 +686,8 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
attrs[prefixes.ChecksumPrefix+"sha1"] = info.Checksums.SHA1
|
||||
attrs[prefixes.ChecksumPrefix+"md5"] = info.Checksums.MD5
|
||||
attrs[prefixes.ChecksumPrefix+"adler32"] = info.Checksums.Adler32
|
||||
// in the same batch, so marking the node costs no write of its own
|
||||
attrs.SetString(prefixes.StatusPrefix, node.ProcessingStatus+sessionID)
|
||||
|
||||
mtime := time.Now()
|
||||
if !info.MTime.IsZero() {
|
||||
@@ -643,7 +706,40 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
|
||||
}
|
||||
committed = true
|
||||
|
||||
return &storage.PrepareUploadResult{VersionCreated: versionCreated, SizeDiff: sizeDiff}, nil
|
||||
result := &storage.PrepareUploadResult{VersionCreated: versionCreated, SizeDiff: sizeDiff}
|
||||
if !info.NodeExisted {
|
||||
// Read off the disk, not through ListGrants: an uploader who cannot see the
|
||||
// space root still needs the manager of a project space reported.
|
||||
result.SpaceOwner = n.SpaceOwnerOrManager(ctx)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// checkNewFileParent re-checks, for a file PrepareUpload is about to create, what
|
||||
// TouchFile checked: the parent still exists, and the user may still upload into it.
|
||||
// Either may have changed while the bytes were in flight.
|
||||
func (fs *Decomposedfs) checkNewFileParent(ctx context.Context, spaceID string, info storage.UploadInfo) error {
|
||||
parentID := &provider.ResourceId{SpaceId: spaceID, OpaqueId: info.ParentID}
|
||||
parent, err := fs.lu.NodeFromID(ctx, parentID)
|
||||
if err != nil {
|
||||
return errtypes.InternalError(err.Error())
|
||||
}
|
||||
f, _ := storagespace.FormatReference(&provider.Reference{ResourceId: parentID, Path: info.Name})
|
||||
if !parent.Exists {
|
||||
return errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, parent)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case !rp.InitiateFileUpload:
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RollbackUpload reverts the node state written by PrepareUpload after a failed or aborted
|
||||
|
||||
+7
@@ -60,6 +60,13 @@ func (f *FS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool {
|
||||
return f.next.(storage.OrphanChecker).IsOrphaned(ctx, ref)
|
||||
}
|
||||
|
||||
// PrepareCreatesNode reports whether the wrapped driver's PrepareUpload creates a
|
||||
// new file's node.
|
||||
func (f *FS) PrepareCreatesNode() bool {
|
||||
nc, ok := f.next.(storage.NodeCreator)
|
||||
return ok && nc.PrepareCreatesNode()
|
||||
}
|
||||
|
||||
// UseIn tells the tus upload middleware which extensions it supports.
|
||||
func (f *FS) UseIn(composer *tusd.StoreComposer) {
|
||||
f.next.(storage.ComposableFS).UseIn(composer)
|
||||
|
||||
+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,
|
||||
}
|
||||
}
|
||||
+942
@@ -0,0 +1,942 @@
|
||||
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
|
||||
}
|
||||
// Its bytes already arrived, and an async finish keeps the session for
|
||||
// postprocessing: a repeated PUT would append to them and finish it again.
|
||||
if session.Offset() > 0 {
|
||||
return nil, errtypes.Aborted("coordinator: upload " + session.ID() + " was already received")
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Only the staged bytes are read, so a mismatch has no node to undo.
|
||||
if err := verifyAndStoreChecksums(ctx, session); err != nil {
|
||||
session.Cleanup(ctx, true, true)
|
||||
return nil, err
|
||||
}
|
||||
// Read before the node exists, so bad request metadata has no node to undo either.
|
||||
info, err := uploadInfo(session)
|
||||
if err != nil {
|
||||
session.Cleanup(ctx, true, true)
|
||||
return nil, err
|
||||
}
|
||||
// A driver whose PrepareUpload creates a new file's node is told where it goes,
|
||||
// under the id minted at initiate. Any other is handed one TouchFile created.
|
||||
if !session.NodeExists() && c.prepareCreatesNode() {
|
||||
info.ParentID, info.Name = session.NodeParentID(), session.Filename()
|
||||
} else if err := c.touchNode(ctx, session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
metrics.UploadSessionsBytesReceived.Inc()
|
||||
|
||||
if err := c.prepare(ctx, session, info); 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),
|
||||
})
|
||||
}
|
||||
|
||||
// prepareCreatesNode reports whether the driver's PrepareUpload creates a new
|
||||
// file's node, sparing the extra metadata write a TouchFile costs.
|
||||
func (c *coordinator) prepareCreatesNode() bool {
|
||||
nc, ok := c.fs.(storage.NodeCreator)
|
||||
return ok && nc.PrepareCreatesNode()
|
||||
}
|
||||
|
||||
// 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(),
|
||||
}
|
||||
// PrepareUpload marks and propagates the node, so TouchFile need not.
|
||||
result, err := c.fs.TouchFile(storage.ContextSkipTouchPropagation(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
|
||||
}
|
||||
|
||||
// prepare has the driver write the node metadata, mark it as processing so clients
|
||||
// do not read it before its bytes are committed, and snapshot the previous version,
|
||||
// ahead of the commit that writes the bytes.
|
||||
func (c *coordinator) prepare(ctx context.Context, session Session, info storage.UploadInfo) error {
|
||||
ref := session.Reference()
|
||||
|
||||
// A failed PrepareUpload has already undone its own writes, a new file's node
|
||||
// included, and marks the node only on success: there is nothing to unmark.
|
||||
prepared, err := c.fs.PrepareUpload(ctx, &ref, session.ID(), info)
|
||||
if err != nil {
|
||||
session.Cleanup(ctx, true, true)
|
||||
if _, ok := err.(errtypes.IsNotFound); ok && info.ParentID != "" {
|
||||
// The parent went away, or the share was revoked, while bytes were in flight.
|
||||
return errtypes.PreconditionFailed(err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
metrics.UploadProcessing.Inc()
|
||||
|
||||
// Persisted, not just held: the commit may run in another process, which can
|
||||
// only learn these, and the real node id from touchNode, by reading them back.
|
||||
// Saved once, here: a failure now finds the node marked, so the rollback can
|
||||
// purge it.
|
||||
if prepared.SpaceOwner != nil {
|
||||
session.SetStorageValue("SpaceOwnerOrManager", prepared.SpaceOwner.GetOpaqueId())
|
||||
session.SetStorageValue("SpaceOwnerIdp", prepared.SpaceOwner.GetIdp())
|
||||
session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(prepared.SpaceOwner.GetType()))
|
||||
}
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
// 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(),
|
||||
NodeExisted: session.NodeExists(),
|
||||
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-20261006170644-bac0e1ee144a
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20261007080847-2cb387523ac7
|
||||
## 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