fix(search): redeliver events with a delay and give up after 5 runs when tika is unreachable

Assisted-by: opencode:claude-sonnet-5.5
This commit is contained in:
Alex Ababii committed 2026-12-02 12:02:28 +01:00
1 parent 61ea17c14a
commit 38ccf9869a
12 files changed
+346 -94

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ require (
github.com/open-policy-agent/opa v1.21.1
github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89
github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261127131426-04b14c99507e
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261202100614-a18d5cce6929
github.com/opensearch-project/opensearch-go/v4 v4.7.3
github.com/orcaman/concurrent-map v1.0.0
github.com/pkg/errors v0.9.1
+2
View File
@@ -763,6 +763,8 @@ github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e
github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e/go.mod h1:lTM8JeGblNpoMySTW7Lui2+c5TTLI95mwxtdUIHHrhU=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261127131426-04b14c99507e h1:fl8LqvkTJMl8yGAslaCY2OHeWyPgPaW0q6MihMbUF/A=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261127131426-04b14c99507e/go.mod h1:oqi8rN/Nt2v+Gn/dmY9p2Zct3VHrdvnYtqZWHrjij7M=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261202100614-a18d5cce6929 h1:suFvSU1XhNSoY8d3/pRHi0/mQFRvvUk2uy7Zz8XnToY=
github.com/opencloud-eu/reva/v3 v3.0.2-0.20261202100614-a18d5cce6929/go.mod h1:oqi8rN/Nt2v+Gn/dmY9p2Zct3VHrdvnYtqZWHrjij7M=
github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4 h1:l2oB/RctH+t8r7QBj5p8thfEHCM/jF35aAY3WQ3hADI=
github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
@@ -33,6 +33,9 @@ type workItem struct {
type AckFunc func() error
// NakWithDelayFunc negatively acknowledges an event, it is redelivered after the delay
type NakWithDelayFunc func(time.Duration) error
// NewSpaceDebouncer returns a new SpaceDebouncer instance
func NewSpaceDebouncer(d time.Duration, timeout time.Duration, f func(id *provider.StorageSpaceId, force bool) error, logger log.Logger) *SpaceDebouncer {
return &SpaceDebouncer{
@@ -48,8 +51,9 @@ func NewSpaceDebouncer(d time.Duration, timeout time.Duration, f func(id *provid
// Debounce restarts the debounce timer for the given space. If force is set,
// the scheduled run is a forced one. A pending run stays forced even if it is
// debounced again without force. When the run fails because tika or the files
// are unreachable, nack is called instead of ack so the event is redelivered.
func (d *SpaceDebouncer) Debounce(id *provider.StorageSpaceId, ack AckFunc, nack AckFunc, force bool) {
// are unreachable, nack is called instead of ack, it is up to the caller to have
// the event redelivered.
func (d *SpaceDebouncer) Debounce(id *provider.StorageSpaceId, ack AckFunc, nack NakWithDelayFunc, force bool) {
d.mutex.Lock()
defer d.mutex.Unlock()
@@ -90,7 +94,7 @@ func (d *SpaceDebouncer) Debounce(id *provider.StorageSpaceId, ack AckFunc, nack
go func() {
if nack != nil && errors.Is(err, content.ErrUnreachable) {
d.log.Warn().Err(err).Msg("nacking event because tika or the files are unreachable")
nackErr := nack()
nackErr := nack(retryDelay)
if nackErr != nil {
d.log.Error().Err(nackErr).Msg("error while nacking event")
}
@@ -214,11 +214,13 @@ var _ = Describe("SpaceDebouncer", func() {
var (
ackCalled atomic.Bool
nackCalled atomic.Bool
nackDelay atomic.Int64
ackFunc = func() error {
ackCalled.Store(true)
return nil
}
nackFunc = func() error {
nackFunc = func(delay time.Duration) error {
nackDelay.Store(int64(delay))
nackCalled.Store(true)
return nil
}
@@ -227,6 +229,7 @@ var _ = Describe("SpaceDebouncer", func() {
BeforeEach(func() {
ackCalled = atomic.Bool{}
nackCalled = atomic.Bool{}
nackDelay = atomic.Int64{}
})
DescribeTable("acks or nacks the event depending on the result of the run",
@@ -246,6 +249,9 @@ var _ = Describe("SpaceDebouncer", func() {
}, "200ms").Should(BeTrue())
Expect(nackCalled.Load()).To(Equal(expectNack))
Expect(ackCalled.Load()).To(Equal(!expectNack))
if expectNack {
Expect(time.Duration(nackDelay.Load())).To(BeNumerically(">", 0))
}
},
Entry("acks when the run succeeds", nil, false),
Entry("acks when the run fails with another error", errors.New("boom"), false),
@@ -266,7 +272,7 @@ var _ = Describe("SpaceDebouncer", func() {
secondAckCalled.Store(true)
return nil
},
func() error {
func(time.Duration) error {
secondNackCalled.Store(true)
return nil
},
@@ -0,0 +1,13 @@
package event
import (
"time"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/events/raw"
)
// NakWithDelay exposes nakWithDelay to the tests
func (s Service) NakWithDelay(e *raw.Event, id *provider.StorageSpaceId, delay time.Duration) error {
return s.nakWithDelay(e, id, delay)
}
+25 -1
View File
@@ -19,6 +19,14 @@ import (
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
const (
// maxIndexRuns is how often an event is delivered before the service
// stops retrying a space whose files stay out of reach
maxIndexRuns = 5
// retryDelay is how long a failed index run waits before the event is redelivered
retryDelay = 2 * time.Minute
)
var tracer trace.Tracer
func init() {
@@ -166,6 +174,21 @@ func getSpaceID(ref *provider.Reference) *provider.StorageSpaceId {
}
}
// nakWithDelay redelivers the event after delay, unless it was delivered
// maxIndexRuns times already, then it acknowledges it instead
func (s Service) nakWithDelay(e *raw.Event, id *provider.StorageSpaceId, delay time.Duration) error {
n, err := e.NumDelivered()
if err != nil {
s.log.Error().Err(err).Interface("spaceID", id).Msg("failed to get the delivery count of the event, giving up on it")
return e.Ack()
}
if n >= maxIndexRuns {
s.log.Warn().Interface("spaceID", id).Uint64("deliveries", n).Msg("the space still has files indexed by name only, run `opencloud search index` to retry them once tika is back")
return e.Ack()
}
return e.NakWithDelay(delay)
}
func (s Service) processEvent(e raw.Event) error {
ctx := e.GetTraceContext(s.ctx)
_, span := tracer.Start(ctx, "processEvent")
@@ -181,7 +204,8 @@ func (s Service) processEvent(e raw.Event) error {
debounce := func(id *provider.StorageSpaceId, force bool) {
ack = func() error { return nil }
s.indexSpaceDebouncer.Debounce(id, e.Ack, e.Nak, force)
nack := func(delay time.Duration) error { return s.nakWithDelay(&e, id, delay) }
s.indexSpaceDebouncer.Debounce(id, e.Ack, nack, force)
}
var err error
@@ -2,12 +2,18 @@ package event_test
import (
"context"
"encoding/json"
"reflect"
"slices"
"sync"
"sync/atomic"
"time"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
nserver "github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/pkg/log"
@@ -111,3 +117,92 @@ var _ = It("does not index the space of a failed upload", func() {
Eventually(indexedSpaces, "2s").Should(ContainElement("storageid$succeeded"))
Consistently(indexedSpaces, "200ms").Should(Equal([]string{"storageid$succeeded"}))
})
var _ = Describe("nakWithDelay", func() {
const delay = 50 * time.Millisecond
var (
svc event.Service
ch <-chan raw.Event
spaceid = &provider.StorageSpaceId{OpaqueId: "spaceid"}
)
BeforeEach(func() {
ctx := context.Background()
srv, err := nserver.NewServer(&nserver.Options{
Port: -1,
JetStream: true,
StoreDir: GinkgoT().TempDir(),
NoLog: true,
NoSigs: true,
})
Expect(err).ToNot(HaveOccurred())
go srv.Start()
Expect(srv.ReadyForConnections(5 * time.Second)).To(BeTrue())
DeferCleanup(srv.Shutdown)
nc, err := nats.Connect(srv.ClientURL())
Expect(err).ToNot(HaveOccurred())
DeferCleanup(nc.Close)
js, err := jetstream.New(nc)
Expect(err).ToNot(HaveOccurred())
_, err = js.CreateStream(ctx, jetstream.StreamConfig{Name: events.MainQueueName})
Expect(err).ToNot(HaveOccurred())
// an event that is not acknowledged in time shows up again
stream, err := raw.FromConfig(ctx, "nakwithdelay-test", raw.Config{
Endpoint: srv.ClientURL(),
MaxAckPending: 10,
AckWait: time.Second,
})
Expect(err).ToNot(HaveOccurred())
ch, err = stream.Consume("nakwithdelay-test", events.FileTouched{})
Expect(err).ToNot(HaveOccurred())
svc, err = event.New(ctx, stream, log.NewLogger(), nil, nil, &searchMocks.Searcher{}, search.NewSkippedSpaces(nil), 50, 1, false)
Expect(err).ToNot(HaveOccurred())
data, err := json.Marshal(raw.RawEvent{
Metadata: map[string]string{events.MetadatakeyEventType: reflect.TypeOf(events.FileTouched{}).String()},
Payload: []byte("{}"),
})
Expect(err).ToNot(HaveOccurred())
_, err = js.Publish(ctx, events.MainQueueName, data)
Expect(err).ToNot(HaveOccurred())
})
// delivered waits for the next delivery of the event and checks its delivery count
delivered := func(count uint64) *raw.Event {
var e raw.Event
Eventually(ch, "5s").Should(Receive(&e))
Expect(e.NumDelivered()).To(Equal(count))
return &e
}
It("redelivers the event after the delay until it was delivered often enough", func() {
for count := uint64(1); count < 5; count++ {
e := delivered(count)
Expect(svc.NakWithDelay(e, spaceid, delay)).To(Succeed())
}
delivered(5)
})
It("acknowledges the event once it was delivered often enough", func() {
for count := uint64(1); count < 5; count++ {
e := delivered(count)
Expect(svc.NakWithDelay(e, spaceid, delay)).To(Succeed())
}
e := delivered(5)
Expect(svc.NakWithDelay(e, spaceid, delay)).To(Succeed())
// neither the delay nor the ack wait pass without a redelivery
Consistently(ch, "1500ms").ShouldNot(Receive())
})
It("gives up on an event without a message by acknowledging it", func() {
err := svc.NakWithDelay(&raw.Event{}, spaceid, delay)
Expect(err).To(MatchError("cannot ack event without message"))
})
})
@@ -20,6 +20,7 @@ package ocdav
import (
"context"
stderrors "errors"
"fmt"
"io"
"net/http"
@@ -53,6 +54,12 @@ type copy struct {
successCode int
}
// errResponseWritten is returned by executePathCopy and executeSpacesCopy when they
// have already written the error response, e.g. a 425 for a file that is still being
// processed. It stops the copy of the remaining children of a folder, and tells the
// handler not to write a status of its own.
var errResponseWritten = stderrors.New("copy: error response already written")
func (s *svc) handlePathCopy(w http.ResponseWriter, r *http.Request, ns string) {
ctx, span := appctx.GetTracerProvider(r.Context()).Tracer(tracerName).Start(r.Context(), "copy")
defer span.End()
@@ -134,8 +141,11 @@ func (s *svc) handlePathCopy(w http.ResponseWriter, r *http.Request, ns string)
}
if err := s.executePathCopy(ctx, s.gatewaySelector, w, r, cp); err != nil {
sublog.Error().Err(err).Str("depth", cp.depth.String()).Msg("error executing path copy")
w.WriteHeader(http.StatusInternalServerError)
if !stderrors.Is(err, errResponseWritten) {
sublog.Error().Err(err).Str("depth", cp.depth.String()).Msg("error executing path copy")
w.WriteHeader(http.StatusInternalServerError)
}
return
}
w.WriteHeader(cp.successCode)
}
@@ -166,6 +176,7 @@ func (s *svc) executePathCopy(ctx context.Context, selector pool.Selectable[gate
m := fmt.Sprintf("Permission denied to create %v", createReq.Ref.Path)
b, err := errors.Marshal(http.StatusForbidden, m, "", "")
errors.HandleWebdavError(log, w, b, err)
return errResponseWritten
}
return nil
}
@@ -186,7 +197,7 @@ func (s *svc) executePathCopy(ctx context.Context, selector pool.Selectable[gate
}
if res.Status.Code != rpc.Code_CODE_OK {
w.WriteHeader(http.StatusInternalServerError)
return nil
return errResponseWritten
}
for i := range res.Infos {
@@ -273,10 +284,10 @@ func (s *svc) executePathCopy(ctx context.Context, selector pool.Selectable[gate
m := fmt.Sprintf("Permissions denied to create %v", uReq.Ref.Path)
b, err := errors.Marshal(http.StatusForbidden, m, "", "")
errors.HandleWebdavError(log, w, b, err)
return nil
return errResponseWritten
}
errors.HandleErrorStatus(log, w, uRes.Status)
return nil
return errResponseWritten
}
var uploadEP, uploadToken string
@@ -299,13 +310,20 @@ func (s *svc) executePathCopy(ctx context.Context, selector pool.Selectable[gate
return err
}
defer httpDownloadRes.Body.Close()
if httpDownloadRes.StatusCode == http.StatusForbidden {
switch httpDownloadRes.StatusCode {
case http.StatusForbidden:
w.WriteHeader(http.StatusForbidden)
b, err := errors.Marshal(http.StatusForbidden, http.StatusText(http.StatusForbidden), "", strconv.Itoa(http.StatusForbidden))
errors.HandleWebdavError(log, w, b, err)
return nil
}
if httpDownloadRes.StatusCode != http.StatusOK {
return errResponseWritten
case http.StatusTooEarly:
// the file is still being processed and can't be copied yet; like GET, MOVE
// and DELETE in that case, answer with the status only
w.WriteHeader(http.StatusTooEarly)
return errResponseWritten
case http.StatusOK:
// ok
default:
return fmt.Errorf("status code %d", httpDownloadRes.StatusCode)
}
@@ -362,8 +380,11 @@ func (s *svc) handleSpacesCopy(w http.ResponseWriter, r *http.Request, spaceID s
err = s.executeSpacesCopy(ctx, w, s.gatewaySelector, cp)
if err != nil {
sublog.Error().Err(err).Str("depth", cp.depth.String()).Msg("error descending directory")
w.WriteHeader(http.StatusInternalServerError)
if !stderrors.Is(err, errResponseWritten) {
sublog.Error().Err(err).Str("depth", cp.depth.String()).Msg("error descending directory")
w.WriteHeader(http.StatusInternalServerError)
}
return
}
w.WriteHeader(cp.successCode)
}
@@ -395,6 +416,7 @@ func (s *svc) executeSpacesCopy(ctx context.Context, w http.ResponseWriter, sele
m := fmt.Sprintf("Permission denied to create %v", createReq.Ref.Path)
b, err := errors.Marshal(http.StatusForbidden, m, "", "")
errors.HandleWebdavError(log, w, b, err)
return errResponseWritten
}
return nil
}
@@ -413,7 +435,7 @@ func (s *svc) executeSpacesCopy(ctx context.Context, w http.ResponseWriter, sele
}
if res.Status.Code != rpc.Code_CODE_OK {
w.WriteHeader(http.StatusInternalServerError)
return nil
return errResponseWritten
}
for i := range res.Infos {
@@ -489,10 +511,10 @@ func (s *svc) executeSpacesCopy(ctx context.Context, w http.ResponseWriter, sele
m := fmt.Sprintf("Permissions denied to create %v", uReq.Ref.Path)
b, err := errors.Marshal(http.StatusForbidden, m, "", "")
errors.HandleWebdavError(log, w, b, err)
return nil
return errResponseWritten
}
errors.HandleErrorStatus(log, w, uRes.Status)
return nil
return errResponseWritten
}
var uploadEP, uploadToken string
@@ -517,11 +539,16 @@ func (s *svc) executeSpacesCopy(ctx context.Context, w http.ResponseWriter, sele
}
defer httpDownloadRes.Body.Close()
switch httpDownloadRes.StatusCode {
case http.StatusForbidden, http.StatusTooEarly:
w.WriteHeader(httpDownloadRes.StatusCode)
b, err := errors.Marshal(http.StatusForbidden, http.StatusText(httpDownloadRes.StatusCode), "", strconv.Itoa(httpDownloadRes.StatusCode))
case http.StatusForbidden:
w.WriteHeader(http.StatusForbidden)
b, err := errors.Marshal(http.StatusForbidden, http.StatusText(http.StatusForbidden), "", strconv.Itoa(http.StatusForbidden))
errors.HandleWebdavError(log, w, b, err)
return nil
return errResponseWritten
case http.StatusTooEarly:
// the file is still being processed and can't be copied yet; like GET, MOVE
// and DELETE in that case, answer with the status only
w.WriteHeader(http.StatusTooEarly)
return errResponseWritten
case http.StatusOK:
// ok
default:
+20
View File
@@ -60,6 +60,26 @@ func (re *Event) Nak() error {
return re.msg.Nak()
}
// NakWithDelay negatively acknowledges the event, the server redelivers it after the delay
func (re *Event) NakWithDelay(delay time.Duration) error {
if re.msg == nil {
return errors.New("cannot nack event without message")
}
return re.msg.NakWithDelay(delay)
}
// NumDelivered returns how many times the server has delivered the event, the first delivery counts as 1
func (re *Event) NumDelivered() (uint64, error) {
if re.msg == nil {
return 0, errors.New("cannot get delivery count of event without message")
}
md, err := re.msg.Metadata()
if err != nil {
return 0, err
}
return md.NumDelivered, nil
}
func (re *Event) Term() error {
if re.msg == nil {
return errors.New("cannot terminate event without message")
+71 -41
View File
@@ -27,6 +27,7 @@ import (
"os"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
@@ -47,6 +48,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/events"
"github.com/opencloud-eu/reva/v3/pkg/storage"
"github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/blobstore"
"github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/idcache"
"github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/ignore"
"github.com/opencloud-eu/reva/v3/pkg/storage/fs/posix/lookup"
@@ -383,7 +385,11 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool,
parentPath := n.ParentPath()
nodePath := filepath.Join(parentPath, n.Name)
// lock the meta file
// the lock file is named after the id, and the watcher waits for this lock once the file
// shows up with its id
if n.ID == "" {
n.ID = uuid.New().String()
}
unlock, err := t.lookup.MetadataBackend().Lock(n)
if err != nil {
return err
@@ -392,26 +398,20 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool,
_ = unlock()
}()
if n.ID == "" {
n.ID = uuid.New().String()
}
n.SetType(provider.ResourceType_RESOURCE_TYPE_FILE)
// Set id in cache
if err := t.lookup.CacheID(context.Background(), n.SpaceID, n.ID, nodePath); err != nil {
t.log.Error().Err(err).Str("spaceID", n.SpaceID).Str("id", n.ID).Str("path", nodePath).Msg("could not cache id")
}
if err := os.MkdirAll(filepath.Dir(nodePath), 0700); err != nil {
return errors.Wrap(err, "posixfs: error creating node")
}
f, err := os.Create(nodePath)
fi, err := t.createFileNode(n, nodePath)
if err != nil {
return errors.Wrap(err, "posixfs: error creating node")
return err
}
// cached only now that the name is ours, so a losing touch cannot point it at its id
if err := t.lookup.CacheID(context.Background(), n.SpaceID, n.ID, nodePath); err != nil {
t.log.Error().Err(err).Str("spaceID", n.SpaceID).Str("id", n.ID).Str("path", nodePath).Msg("could not cache id")
}
defer func() {
_ = f.Close()
}()
attributes := n.NodeMetadata(ctx)
attributes[prefixes.IDAttr] = []byte(n.ID)
@@ -428,12 +428,7 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool,
return err
}
} else {
fi, err := f.Stat()
if err != nil {
return err
}
mtime := fi.ModTime()
attributes[prefixes.MTimeAttr] = []byte(mtime.UTC().Format(time.RFC3339Nano))
attributes[prefixes.MTimeAttr] = []byte(fi.ModTime().UTC().Format(time.RFC3339Nano))
}
err = n.SetXattrsWithContext(ctx, attributes)
@@ -908,18 +903,11 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
return nil, err
}
// we also need to touch the actual node file here it stores the mtime of the resource
h, err := os.OpenFile(nodePath, os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
if _, err := t.createFileNode(n, nodePath); err != nil {
// the file is not ours: leave it, and its cache entry, alone
releaseNewNodeLock(ctx, n, unlock)
if os.IsExist(err) {
// the name only: the message reaches the client, the path is the server's
return nil, errtypes.AlreadyExists(n.Name)
}
return nil, err
}
defer func() { _ = 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.
@@ -939,19 +927,6 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
return fail(err)
}
// Set known mtime from filesystem to metadata to preven re-assimilation
fi, err := h.Stat()
if err != nil {
return fail(err)
}
mtime := fi.ModTime()
err = n.SetXattrsWithContext(ctx, map[string][]byte{
prefixes.MTimeAttr: []byte(mtime.UTC().Format(time.RFC3339Nano)),
})
if err != nil {
t.log.Error().Err(err).Str("path", nodePath).Msg("could not set mtime attribute on new node")
}
if _, err := node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize); err != nil {
return fail(err)
}
@@ -959,6 +934,61 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
return unlock, nil
}
// createFileNode creates the file of the new node n at nodePath. The file must not show up
// under its name without an id: the watcher would assimilate it as a new item under a lock of
// its own, give it an id, blob id and size of its own and cache its id for the path, racing
// the attributes the caller writes. So we create it under a temp name the watcher ignores,
// give it its identity there and only then hardlink it to its name. Whatever scans it from
// then on finds the id and waits for the node lock the caller holds.
// Like O_EXCL, link() fails if the name is taken, and unlike renameat2(RENAME_NOREPLACE) it
// works on every POSIX filesystem, NFS included. On an error nothing at nodePath is ours.
// It returns the stat of the new file, the mtime attribute already matches it.
func (t *Tree) createFileNode(n *node.Node, nodePath string) (os.FileInfo, error) {
tmpDir := filepath.Join(n.SpaceRoot.InternalPath(), blobstore.TMPDir)
if err := os.MkdirAll(tmpDir, 0700); err != nil {
return nil, err
}
tmpPath := filepath.Join(tmpDir, ".new-"+n.ID)
h, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return nil, err
}
defer func() { _ = h.Close() }()
// after the link only the temp name goes, the inode stays under its real name
defer func() {
if err := os.Remove(tmpPath); err != nil && !os.IsNotExist(err) {
t.log.Error().Err(err).Str("path", tmpPath).Msg("could not remove temp file of new node")
}
}()
// the mtime is set here as well, so the watcher's mtime check skips the file
fi, err := h.Stat()
if err != nil {
return nil, err
}
identity := map[string]string{
prefixes.IDAttr: n.ID,
prefixes.ParentidAttr: n.ParentID,
prefixes.NameAttr: n.Name,
prefixes.TypeAttr: strconv.FormatInt(int64(provider.ResourceType_RESOURCE_TYPE_FILE), 10),
prefixes.MTimeAttr: fi.ModTime().UTC().Format(time.RFC3339Nano),
}
for k, v := range identity {
if err := xattr.FSet(h, k, []byte(v)); err != nil {
return nil, err
}
}
if err := os.Link(tmpPath, nodePath); err != nil {
if os.IsExist(err) {
// the name only: the message reaches the client, the path is the server's
return nil, errtypes.AlreadyExists(n.Name)
}
return nil, err
}
return fi, 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 {
@@ -6,8 +6,10 @@ import (
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/google/renameio/v2"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/mtimesyncedcache"
"github.com/pkg/errors"
"github.com/rogpeppe/go-internal/lockedfile"
@@ -21,10 +23,42 @@ type Index struct {
cache mtimesyncedcache.Cache[string, map[string]string]
}
type readWriteCloseSeekTruncater interface {
io.ReadWriteCloser
io.Seeker
Truncate(int64) error
// writeLock is the in-process lock of one index file. refs counts the writers that hold it or wait for it.
type writeLock struct {
mu sync.Mutex
refs int
}
var (
writeLocksMu sync.Mutex
writeLocks = map[string]*writeLock{} // index path -> lock, only while a writer holds it or waits for it
)
// lockIndex serializes the writers of an index file within this process, so that at most one of them at a time
// waits for the file lock: several flock requests of one client waiting for the same file can be very slow on some
// shared filesystems (ceph-fuse). It returns the unlock function, which removes the entry again when no other
// writer of this process holds it or waits for it.
func lockIndex(indexPath string) (unlock func()) {
writeLocksMu.Lock()
l, ok := writeLocks[indexPath]
if !ok {
l = &writeLock{}
writeLocks[indexPath] = l
}
l.refs++
writeLocksMu.Unlock()
l.mu.Lock()
return func() {
l.mu.Unlock()
writeLocksMu.Lock()
l.refs--
if l.refs == 0 {
delete(writeLocks, indexPath)
}
writeLocksMu.Unlock()
}
}
// New returns a new index instance
@@ -83,18 +117,22 @@ func (i *Index) Remove(index, key string) error {
return i.updateIndex(index, map[string]string{}, []string{key})
}
func (i *Index) updateIndex(index string, addLinks map[string]string, removeLinks []string) error {
func (i *Index) updateIndex(index string, addLinks map[string]string, removeLinks []string) (err error) {
indexPath := filepath.Join(i.root, i.name, index+".mpk")
var err error
// acquire writelock
var f readWriteCloseSeekTruncater
f, err = lockedfile.OpenFile(indexPath, os.O_RDWR|os.O_CREATE, 0600)
unlock := lockIndex(indexPath)
defer unlock()
// acquire writelock on a separate lock file, like the node metadata does. The index itself is replaced
// atomically and never truncated and rewritten in place: on a shared filesystem (e.g. the CephFS kernel client)
// a writer on another node could otherwise read up to a stale size and drop entries, and a process that dies
// between truncating and writing would leave an empty or partial index behind.
l, err := lockedfile.OpenFile(indexPath+".mlock", os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return errors.Wrap(err, "unable to lock index to write")
}
defer func() {
rerr := f.Close()
rerr := l.Close()
// if err is non nil we do not overwrite that
if err == nil {
@@ -103,15 +141,17 @@ func (i *Index) updateIndex(index string, addLinks map[string]string, removeLink
}()
// Read current state
msgBytes, err := io.ReadAll(f)
if err != nil {
return err
}
links := map[string]string{}
if len(msgBytes) > 0 {
msgBytes, err := os.ReadFile(indexPath)
switch {
case errors.Is(err, os.ErrNotExist):
// no index yet
case err != nil:
return errors.Wrap(err, "unable to read index")
case len(msgBytes) > 0:
err = msgpack.Unmarshal(msgBytes, &links)
if err != nil {
return err
return errors.Wrap(err, "unable to parse index")
}
}
@@ -122,22 +162,13 @@ func (i *Index) updateIndex(index string, addLinks map[string]string, removeLink
for _, key := range removeLinks {
delete(links, key)
}
// Truncate file
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return err
}
err = f.Truncate(0)
if err != nil {
return err
}
// Write new metadata to file
// Write new metadata to a temporary file next to the index, fsync it and rename it over the index
d, err := msgpack.Marshal(links)
if err != nil {
return errors.Wrap(err, "unable to marshal index")
}
_, err = f.Write(d)
err = renameio.WriteFile(indexPath, d, 0600, renameio.WithTempDir(filepath.Dir(indexPath)))
if err != nil {
return errors.Wrap(err, "unable to write index")
}
+1 -1
View File
@@ -1360,7 +1360,7 @@ github.com/opencloud-eu/icap-client
# github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261119152805-1a7a500a264e
## explicit; go 1.23
github.com/opencloud-eu/libre-graph-api-go
# github.com/opencloud-eu/reva/v3 v3.0.2-0.20261127131426-04b14c99507e
# github.com/opencloud-eu/reva/v3 v3.0.2-0.20261202100614-a18d5cce6929
## explicit; go 1.26.0
github.com/opencloud-eu/reva/v3/cmd/revad/internal/grace
github.com/opencloud-eu/reva/v3/cmd/revad/runtime