Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
acdfa71270 | ||
|
|
da4ab34396 | ||
|
|
feb5741eb6 |
No files matched your search
@@ -2,48 +2,106 @@ name: k6 Load Test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
schedule:
|
||||
- cron: '0 4 * * *'
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ocis_ref:
|
||||
description: 'oCIS commit or branch to build on the target (must exist in owncloud/ocis)'
|
||||
default: master
|
||||
quick:
|
||||
description: 'Short smoke run instead of the full ramping suite'
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: k6-load-test-server
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
k6-load-test:
|
||||
name: k6-load-test
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: owncloudci/alpine:latest
|
||||
# The runner lives on the k6 driver itself, so there is no checkout, no
|
||||
# container and no ssh into the driver — only the target is remote.
|
||||
runs-on: [self-hosted, loadtest]
|
||||
timeout-minutes: 360
|
||||
if: >-
|
||||
github.event_name == 'schedule' ||
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
contains(github.event.pull_request.title || '', 'k6-test'))
|
||||
env:
|
||||
SSH_OCIS_REMOTE: ${{ secrets.SSH_OCIS_REMOTE }}
|
||||
SSH_OCIS_USERNAME: ${{ secrets.SSH_OCIS_USERNAME }}
|
||||
SSH_OCIS_PASSWORD: ${{ secrets.SSH_OCIS_PASSWORD }}
|
||||
TEST_SERVER_URL: ${{ secrets.TEST_SERVER_URL }}
|
||||
SSH_K6_REMOTE: ${{ secrets.SSH_K6_REMOTE }}
|
||||
SSH_K6_USERNAME: ${{ secrets.SSH_K6_USERNAME }}
|
||||
SSH_K6_PASSWORD: ${{ secrets.SSH_K6_PASSWORD }}
|
||||
OCIS_COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
OCIS_HOST: ${{ vars.LOADTEST_OCIS_HOST || 'loadtest-ocis.svc.owncloud.host' }}
|
||||
OCIS_COMMIT_ID: ${{ inputs.ocis_ref || github.event.pull_request.head.sha || github.sha }}
|
||||
# inputs.* is empty on pull_request, so the workflow_dispatch default does
|
||||
# not apply here — the shell below falls back to a quick run.
|
||||
QUICK: ${{ inputs.quick }}
|
||||
SSH_OPTS: -o BatchMode=yes -o ServerAliveInterval=60 -o ServerAliveCountMax=10
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- name: Show what will run
|
||||
run: |
|
||||
echo "driver : $(hostname -f)"
|
||||
echo "target : $OCIS_HOST"
|
||||
echo "oCIS : $OCIS_COMMIT_ID"
|
||||
/usr/local/bin/k6 version
|
||||
|
||||
- name: Install SSH dependencies
|
||||
run: apk add --no-cache openssh-client sshpass
|
||||
- name: Build and start oCIS on the target
|
||||
id: start
|
||||
run: |
|
||||
ssh $SSH_OPTS "loadtest@$OCIS_HOST" \
|
||||
"OCIS_COMMIT_ID='$OCIS_COMMIT_ID' /usr/local/bin/ocis.sh start"
|
||||
|
||||
- name: Run k6 load tests
|
||||
run: sh tests/config/drone/run_k6_tests.sh
|
||||
- name: Show the oCIS build log
|
||||
if: failure() && steps.start.outcome == 'failure'
|
||||
run: ssh $SSH_OPTS "loadtest@$OCIS_HOST" 'tail -n 200 /srv/loadtest/ocis-build.log' || true
|
||||
|
||||
- name: Retrieve OCIS logs
|
||||
# ocis.sh proves readiness from the target's own shell. This proves it from
|
||||
# the driver, which is a different question: firewalld, and whether the
|
||||
# server outlived the ssh session that started it.
|
||||
- name: Check that the target answers from the driver
|
||||
run: |
|
||||
if curl -sk -o /dev/null --max-time 10 \
|
||||
"https://$OCIS_HOST:9200/.well-known/openid-configuration"; then
|
||||
echo "oCIS answers at https://$OCIS_HOST:9200"
|
||||
exit 0
|
||||
fi
|
||||
echo "::error::oCIS is not answering on $OCIS_HOST:9200 from the driver"
|
||||
ssh $SSH_OPTS "loadtest@$OCIS_HOST" \
|
||||
'pgrep -af "bin/ocis server" || echo "no oCIS process on the target"'
|
||||
exit 1
|
||||
|
||||
# No !cancelled() here on purpose: k6 against a target that failed to start
|
||||
# just buries the real error under a TypeScript stack trace.
|
||||
- name: Run the k6 tests
|
||||
run: |
|
||||
if [ "${QUICK:-true}" = "true" ]; then
|
||||
# Seed at least one user per VU: each VU logs in as the pool user
|
||||
# matching its own VU number, so seeding fewer users than the 16 VUs
|
||||
# started below leaves those extra VUs with accounts that were never
|
||||
# created, and every request they make fails to authenticate.
|
||||
export SEED_USERS_TOTAL=20
|
||||
for id in 020 040 050 070 080 090 100 110; do
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_VUS=2
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_UP_DURATION=10s
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_PEAK_DURATION=30s
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_STAGES_DOWN_DURATION=10s
|
||||
export TEST_KOKO_PLATFORM_${id}_RAMPING_SLEEP_AFTER_ITERATION=1s
|
||||
done
|
||||
fi
|
||||
/usr/local/bin/k6-tests.sh
|
||||
|
||||
- name: Retrieve the oCIS log
|
||||
if: ${{ !cancelled() }}
|
||||
run: ssh $SSH_OPTS "loadtest@$OCIS_HOST" '/usr/local/bin/ocis.sh log' || true
|
||||
|
||||
# always(), not the old fire-and-forget tail call: a failing k6 run used to
|
||||
# leave oCIS holding port 9200, and the next run then failed to start.
|
||||
- name: Stop oCIS on the target
|
||||
if: always()
|
||||
run: sh tests/config/drone/run_k6_tests.sh --ocis-log
|
||||
run: ssh $SSH_OPTS "loadtest@$OCIS_HOST" '/usr/local/bin/ocis.sh stop'
|
||||
|
||||
- name: Show Grafana dashboard link
|
||||
if: always()
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
echo "Grafana Dashboard: https://grafana.k6.infra.owncloud.works"
|
||||
echo "Grafana: http://$(hostname -f):3000 (office/VPN only)"
|
||||
@@ -65,7 +65,7 @@ require (
|
||||
github.com/open-policy-agent/opa v1.19.0
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261001150122-9557cab91f00
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261008202759-e28d93df3fc9
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
|
||||
@@ -735,8 +735,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-20261001150122-9557cab91f00 h1:VbWKQwx5KV4Dls6FIfSzsdaWcXwTf6zr5l3Jy8ApQlw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261001150122-9557cab91f00/go.mod h1:LSXqMWTC7Ya6uxmqp1ksrWYZXBuZ6PhcmVimxyG8U5o=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261008202759-e28d93df3fc9 h1:VyijEeEuw2d2mzraD9YAwg/R2WoAk/wHLDXDDzwCyZ0=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261008202759-e28d93df3fc9/go.mod h1:LSXqMWTC7Ya6uxmqp1ksrWYZXBuZ6PhcmVimxyG8U5o=
|
||||
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=
|
||||
|
||||
Generated
Vendored
+6
@@ -440,6 +440,12 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
|
||||
st = status.NewFailedPrecondition(ctx, err, "failed precondition")
|
||||
case errtypes.Locked:
|
||||
st = status.NewLocked(ctx, "locked")
|
||||
case errtypes.TooEarly:
|
||||
st = status.NewTooEarly(ctx, "response from InitiateUpload: "+err.Error())
|
||||
case errtypes.Aborted:
|
||||
st = status.NewAborted(ctx, err, "response from InitiateUpload")
|
||||
case errtypes.AlreadyExists:
|
||||
st = status.NewAlreadyExists(ctx, err, "response from InitiateUpload")
|
||||
default:
|
||||
st = status.NewInternal(ctx, "error getting upload id: "+err.Error())
|
||||
}
|
||||
|
||||
+2
-1
@@ -24,6 +24,7 @@ package errtypes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
@@ -384,7 +385,7 @@ func NewErrtypeFromHTTPStatusCode(code int, message string) error {
|
||||
case StatusChecksumMismatch:
|
||||
return ChecksumMismatch(message)
|
||||
default:
|
||||
return InternalError(message)
|
||||
return InternalError("http " + strconv.Itoa(code) + ": " + message)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
@@ -170,6 +170,15 @@ func NewTooManyRequests(ctx context.Context, msg string) *rpc.Status {
|
||||
}
|
||||
}
|
||||
|
||||
// NewTooEarly returns a status Code_CODE_TOO_EARLY
|
||||
func NewTooEarly(ctx context.Context, msg string) *rpc.Status {
|
||||
return &rpc.Status{
|
||||
Code: rpc.Code_CODE_TOO_EARLY,
|
||||
Message: msg,
|
||||
Trace: getTrace(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
// NewStatusFromErrType returns a status that corresponds to the given errtype
|
||||
func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Status {
|
||||
switch e := err.(type) {
|
||||
@@ -202,6 +211,8 @@ func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Statu
|
||||
return NewInvalid(ctx, msg+":"+err.Error())
|
||||
case errtypes.TooManyRequests:
|
||||
return NewTooManyRequests(ctx, msg+": "+err.Error())
|
||||
case errtypes.TooEarly:
|
||||
return NewTooEarly(ctx, msg+": "+err.Error())
|
||||
}
|
||||
|
||||
// map GRPC status codes coming from the auth middleware
|
||||
|
||||
+3
@@ -275,6 +275,9 @@ func handleError(w http.ResponseWriter, log *zerolog.Logger, err error, action s
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Err(err).Str("action", action).Msg("etags do not match")
|
||||
w.WriteHeader(http.StatusPreconditionFailed)
|
||||
case errtypes.IsTooEarly:
|
||||
log.Debug().Err(err).Str("action", action).Msg("resource is processing")
|
||||
w.WriteHeader(http.StatusTooEarly)
|
||||
default:
|
||||
log.Error().Err(err).Str("action", action).Msg("unexpected error")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
// Package cas classifies CAS-conflict errors shared by providercache, sharecache, and receivedsharecache.
|
||||
package cas
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
"github.com/rs/zerolog"
|
||||
grpccodes "google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// NewBackoff returns the backoff policy shared by every CAS-retry loop.
|
||||
func NewBackoff() *backoff.ExponentialBackOff {
|
||||
bo := backoff.NewExponentialBackOff()
|
||||
bo.InitialInterval = 500 * time.Microsecond
|
||||
bo.Multiplier = 2.0
|
||||
bo.RandomizationFactor = 1.0
|
||||
bo.MaxInterval = 50 * time.Millisecond
|
||||
return bo
|
||||
}
|
||||
|
||||
// IsConflict reports whether err is a CAS conflict the caller should resync and retry on.
|
||||
func IsConflict(err error) bool {
|
||||
switch err.(type) {
|
||||
case errtypes.Aborted:
|
||||
// If-Match etag check failed
|
||||
return true
|
||||
case errtypes.PreconditionFailed:
|
||||
// same as Aborted; some server paths return this instead
|
||||
return true
|
||||
case errtypes.AlreadyExists:
|
||||
// If-None-Match=* conflict: cache thought there was no file yet
|
||||
return true
|
||||
case errtypes.TooEarly:
|
||||
// an upload is already in progress for this path
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsSyncTransient reports whether a sync's Download error is worth retrying.
|
||||
func IsSyncTransient(err error) bool {
|
||||
_, isTooEarly := err.(errtypes.IsTooEarly)
|
||||
return isTooEarly || IsTransientGRPCStatus(err)
|
||||
}
|
||||
|
||||
// IsTransientGRPCStatus catches raw gRPC transport errors that metadata.CS3 never wraps in errtypes.
|
||||
func IsTransientGRPCStatus(err error) bool {
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch st.Code() {
|
||||
case grpccodes.Unavailable, grpccodes.DeadlineExceeded, grpccodes.Canceled, grpccodes.ResourceExhausted:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RetryPersist retries persistFunc on a CAS conflict, calling resyncFunc between attempts to
|
||||
// refresh in-memory state before the next persist, up to maxRetries times with this package's
|
||||
// shared backoff. onConflict/onPersistFailed/onResyncFailed let the caller record its own
|
||||
// span/log side effects for each outcome without this package depending on otel/zerolog.
|
||||
func RetryPersist(ctx context.Context, maxRetries int, persistFunc, resyncFunc func() error,
|
||||
onConflict, onPersistFailed, onResyncFailed func(err error)) error {
|
||||
bo := NewBackoff()
|
||||
var err error
|
||||
for retries := maxRetries; retries > 0; retries-- {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
err = persistFunc()
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case IsConflict(err):
|
||||
onConflict(err)
|
||||
default:
|
||||
onPersistFailed(err)
|
||||
return err
|
||||
}
|
||||
if rerr := resyncFunc(); rerr != nil {
|
||||
onResyncFailed(rerr)
|
||||
return rerr
|
||||
}
|
||||
timer := time.NewTimer(bo.NextBackOff())
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// DecideNotFoundReset reports whether a NotFound download result should be treated as a
|
||||
// legitimately empty resource (reset) rather than a lost update (error). A resync with a
|
||||
// prior etag never resets silently; otherwise the backend's trash state decides, failing
|
||||
// open (reset=true) when the backend can't tell (e.g. Disk). trashed is only meaningful
|
||||
// when reset is false, to pick the right log reason.
|
||||
func DecideNotFoundReset(ctx context.Context, storage metadata.Storage, path string, resetOnNotFound, hadPriorEtag bool, log zerolog.Logger) (reset, trashed bool) {
|
||||
if !resetOnNotFound && hadPriorEtag {
|
||||
return false, false
|
||||
}
|
||||
trashed, terr := storage.WasRecentlyDeleted(ctx, path)
|
||||
if terr != nil {
|
||||
log.Warn().Err(terr).Msg("could not check trash state, assuming not deleted")
|
||||
return true, false
|
||||
}
|
||||
return !trashed, trashed
|
||||
}
|
||||
Generated
Vendored
+68
-53
@@ -29,10 +29,12 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
"go.opentelemetry.io/otel"
|
||||
@@ -166,7 +168,7 @@ func (c *Cache) Add(ctx context.Context, storageID, spaceID, shareID string, sha
|
||||
|
||||
var err error
|
||||
if !c.isSpaceCached(storageID, spaceID) {
|
||||
err = c.syncWithLock(ctx, storageID, spaceID)
|
||||
err = c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,38 +191,22 @@ func (c *Cache) Add(ctx context.Context, storageID, spaceID, shareID string, sha
|
||||
return c.Persist(ctx, storageID, spaceID)
|
||||
}
|
||||
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added provider share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added provider share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added provider share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
err = cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, storageID, spaceID) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting added provider share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added provider share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added provider share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, storageID, spaceID); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added provider share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -235,7 +221,7 @@ func (c *Cache) Remove(ctx context.Context, storageID, spaceID, shareID string)
|
||||
span.AddEvent("got lock")
|
||||
|
||||
if !c.isSpaceCached(storageID, spaceID) {
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -261,32 +247,21 @@ func (c *Cache) Remove(ctx context.Context, storageID, spaceID, shareID string)
|
||||
Str("spaceID", spaceID).
|
||||
Str("shareID", shareID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting removed provider share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting removed provider share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
default:
|
||||
err := cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, storageID, spaceID) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting removed provider share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting removed provider share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting removed provider share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, storageID, spaceID); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting removed provider share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -303,7 +278,7 @@ func (c *Cache) Get(ctx context.Context, storageID, spaceID, shareID string, ski
|
||||
|
||||
if !skipSync {
|
||||
// sync cache, maybe our data is outdated
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -340,7 +315,8 @@ func (c *Cache) All(ctx context.Context) (*mtimesyncedcache.Map[string, *Spaces]
|
||||
|
||||
unlock := c.LockSpace(spaceID)
|
||||
span.AddEvent("got lock for space " + spaceID)
|
||||
if err := c.syncWithLock(ctx, storageID, spaceID); err != nil {
|
||||
if err := c.syncWithRetry(ctx, storageID, spaceID); err != nil {
|
||||
unlock()
|
||||
return nil, err
|
||||
}
|
||||
unlock()
|
||||
@@ -361,7 +337,7 @@ func (c *Cache) ListSpace(ctx context.Context, storageID, spaceID string) (*Shar
|
||||
span.AddEvent("got lock")
|
||||
|
||||
// sync cache, maybe our data is outdated
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -459,7 +435,7 @@ func (c *Cache) PurgeSpace(ctx context.Context, storageID, spaceID string) error
|
||||
span.AddEvent("got lock")
|
||||
|
||||
if !c.isSpaceCached(storageID, spaceID) {
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
err := c.syncWithRetry(ctx, storageID, spaceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -478,7 +454,18 @@ func (c *Cache) PurgeSpace(ctx context.Context, storageID, spaceID string) error
|
||||
return c.Persist(ctx, storageID, spaceID)
|
||||
}
|
||||
|
||||
// syncWithLock treats NotFound as a legitimately empty space (cold-start only).
|
||||
func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) error {
|
||||
return c.doSync(ctx, storageID, spaceID, true)
|
||||
}
|
||||
|
||||
// Unlike syncWithLock, a NotFound here must not reset the cache -- a pending
|
||||
// mutation is about to overwrite it, dropping a sibling writer's data.
|
||||
func (c *Cache) resyncAfterConflict(ctx context.Context, storageID, spaceID string) error {
|
||||
return c.doSync(ctx, storageID, spaceID, false)
|
||||
}
|
||||
|
||||
func (c *Cache) doSync(ctx context.Context, storageID, spaceID string, resetOnNotFound bool) error {
|
||||
ctx, span := tracer.Start(ctx, "syncWithLock")
|
||||
defer span.End()
|
||||
|
||||
@@ -498,10 +485,22 @@ func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) err
|
||||
}
|
||||
|
||||
dlres, err := c.storage.Download(ctx, dlreq)
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
if reset, trashed := cas.DecideNotFoundReset(ctx, c.storage, dlreq.Path, resetOnNotFound, space.Etag != "", log); !reset {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if trashed {
|
||||
log.Error().Err(err).Msg("lost update: backing file was recently trashed")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: backing file disappeared mid-retry")
|
||||
}
|
||||
return err
|
||||
}
|
||||
spaces.Spaces.Store(spaceID, &Shares{Shares: map[string]*collaboration.Share{}})
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
@@ -529,6 +528,22 @@ func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) err
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncWithRetry retries syncWithLock's cold-start read on transient errors, since callers have no other retry wrapper.
|
||||
func (c *Cache) syncWithRetry(ctx context.Context, storageID, spaceID string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := backoff.Retry(ctx, func() (struct{}, error) {
|
||||
err := c.syncWithLock(ctx, storageID, spaceID)
|
||||
if err != nil && !cas.IsSyncTransient(err) {
|
||||
return struct{}{}, backoff.Permanent(err)
|
||||
}
|
||||
return struct{}{}, err
|
||||
}, backoff.WithBackOff(cas.NewBackoff()), backoff.WithMaxTries(20))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Cache) initializeIfNeeded(storageID, spaceID string) {
|
||||
spaces, _ := c.Providers.LoadOrStore(storageID, &Spaces{
|
||||
Spaces: mtimesyncedcache.Map[string, *Shares]{},
|
||||
|
||||
Generated
Vendored
+151
-94
@@ -28,10 +28,12 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
@@ -94,12 +96,12 @@ func (c *Cache) lockUser(userID string) func() {
|
||||
func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaboration.ReceivedShare) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
span.End()
|
||||
defer unlock()
|
||||
|
||||
if _, ok := c.ReceivedSpaces.Load(userID); !ok {
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
err := c.syncWithRetry(ctx, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -109,7 +111,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
|
||||
|
||||
persistFunc := func() error {
|
||||
err := c.retryPersist(ctx, userID, spaceID, func() error {
|
||||
c.initializeIfNeeded(userID, spaceID)
|
||||
|
||||
rss, _ := c.ReceivedSpaces.Load(userID)
|
||||
@@ -124,44 +126,12 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
}
|
||||
|
||||
return c.persist(ctx, userID)
|
||||
}
|
||||
|
||||
log := appctx.GetLogger(ctx).With().
|
||||
Str("hostname", os.Getenv("HOSTNAME")).
|
||||
Str("userID", userID).
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added received share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added received share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userID); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -170,11 +140,11 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*State, error) {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
span.End()
|
||||
defer unlock()
|
||||
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
err := c.syncWithRetry(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -189,15 +159,15 @@ func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*Stat
|
||||
func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
span.End()
|
||||
defer unlock()
|
||||
|
||||
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Add")
|
||||
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Remove")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
|
||||
|
||||
persistFunc := func() error {
|
||||
err := c.retryPersist(ctx, userID, spaceID, func() error {
|
||||
c.initializeIfNeeded(userID, spaceID)
|
||||
|
||||
rss, _ := c.ReceivedSpaces.Load(userID)
|
||||
@@ -211,44 +181,12 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
|
||||
}
|
||||
|
||||
return c.persist(ctx, userID)
|
||||
}
|
||||
|
||||
log := appctx.GetLogger(ctx).With().
|
||||
Str("hostname", os.Getenv("HOSTNAME")).
|
||||
Str("userID", userID).
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added received share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added received share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userID); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -256,13 +194,14 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
|
||||
// List returns a list of received shares for a given user
|
||||
// The return list is guaranteed to be thread-safe
|
||||
func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, error) {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
|
||||
unlock := c.lockUser(userID)
|
||||
span.End()
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "List")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
|
||||
unlock := c.lockUser(userID)
|
||||
defer unlock()
|
||||
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
err := c.syncWithRetry(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -285,7 +224,110 @@ func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, err
|
||||
return spaces, nil
|
||||
}
|
||||
|
||||
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
func (c *Cache) retryPersist(ctx context.Context, userID, spaceID string, persistFunc func() error) error {
|
||||
log := appctx.GetLogger(ctx).With().
|
||||
Str("hostname", os.Getenv("HOSTNAME")).
|
||||
Str("userID", userID).
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
bo := cas.NewBackoff()
|
||||
|
||||
const maxPersistAttempts = 20
|
||||
// independent budget, not derived from maxPersistAttempts: a flaky resync must not starve the persist budget.
|
||||
const maxResyncAttemptsPerFailure = 20
|
||||
|
||||
var err error
|
||||
needsResync := false
|
||||
persistAttempts := 0
|
||||
resyncAttempts := 0
|
||||
for persistAttempts < maxPersistAttempts {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
if needsResync {
|
||||
// a previous persist attempt failed and the re-read to pick up fresh state
|
||||
// was itself transient; keep retrying the re-read instead of hammering
|
||||
// persistFunc again with the same stale in-memory rss/etag
|
||||
serr := c.resyncAfterConflict(ctx, userID)
|
||||
if serr == nil {
|
||||
needsResync = false
|
||||
resyncAttempts = 0
|
||||
continue // fresh state is in memory; retry persistFunc next attempt, no need to wait
|
||||
}
|
||||
// keep err at its last real (persist or resync) failure; never let a
|
||||
// budget-exhausting resync success clobber it into a false nil return
|
||||
err = serr
|
||||
if !cas.IsSyncTransient(serr) {
|
||||
log.Error().Err(serr).Msg("lost update: re-read failed, aborting")
|
||||
return serr
|
||||
}
|
||||
resyncAttempts++
|
||||
if resyncAttempts >= maxResyncAttemptsPerFailure {
|
||||
log.Error().Err(serr).Msg("lost update: resync would not stabilize, giving up")
|
||||
return serr
|
||||
}
|
||||
log.Warn().Err(serr).Msg("lost update: re-read before retry")
|
||||
} else {
|
||||
persistAttempts++
|
||||
err = persistFunc()
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case cas.IsTransientGRPCStatus(err):
|
||||
log.Debug().Err(err).Msg("persist failed: transient gRPC error, retrying")
|
||||
case cas.IsConflict(err):
|
||||
log.Debug().Err(err).Msg("CAS conflict persisting received share, retrying")
|
||||
default:
|
||||
log.Error().Err(err).Msg("persisting received share failed, giving up")
|
||||
return err
|
||||
}
|
||||
needsResync = true
|
||||
}
|
||||
|
||||
timer := time.NewTimer(bo.NextBackOff())
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// syncWithRetry retries sync's cold-start read on transient errors, since
|
||||
// Add/Get/List call it directly with no other retry wrapper around it.
|
||||
func (c *Cache) syncWithRetry(ctx context.Context, userID string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := backoff.Retry(ctx, func() (struct{}, error) {
|
||||
err := c.sync(ctx, userID)
|
||||
if err != nil && !cas.IsSyncTransient(err) {
|
||||
return struct{}{}, backoff.Permanent(err)
|
||||
}
|
||||
return struct{}{}, err
|
||||
}, backoff.WithBackOff(cas.NewBackoff()), backoff.WithMaxTries(20))
|
||||
return err
|
||||
}
|
||||
|
||||
// sync pulls the authoritative state from storage; caller must hold the user
|
||||
// lock. Treats NotFound as a legitimately empty user (cold-start only).
|
||||
func (c *Cache) sync(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, true)
|
||||
}
|
||||
|
||||
// Unlike sync, a NotFound here must not reset the cache -- a pending mutation
|
||||
// is about to overwrite it, dropping a sibling writer's data.
|
||||
func (c *Cache) resyncAfterConflict(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, false)
|
||||
}
|
||||
|
||||
func (c *Cache) doSync(ctx context.Context, userID string, resetOnNotFound bool) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
@@ -298,22 +340,38 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
span.AddEvent("updating cache")
|
||||
// - update cached list of created shares for the user in memory if changed
|
||||
rss, _ := c.ReceivedSpaces.Load(userID)
|
||||
dlres, err := c.storage.Download(ctx, metadata.DownloadRequest{
|
||||
dlreq := metadata.DownloadRequest{
|
||||
Path: jsonPath,
|
||||
IfNoneMatch: []string{rss.etag},
|
||||
})
|
||||
}
|
||||
dlres, err := c.storage.Download(ctx, dlreq)
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
if reset, trashed := cas.DecideNotFoundReset(ctx, c.storage, jsonPath, resetOnNotFound, rss.etag != "", log); !reset {
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if trashed {
|
||||
log.Error().Err(err).Msg("lost update: backing file was recently trashed")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: backing file disappeared mid-retry")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.ReceivedSpaces.Store(userID, &Spaces{Spaces: map[string]*Space{}})
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
default:
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("Failed to download the received share: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("Failed to download the received share")
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if cas.IsSyncTransient(err) {
|
||||
log.Warn().Err(err).Msg("lost update: re-read transient error")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: re-read failed")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -374,7 +432,6 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
|
||||
return err
|
||||
}
|
||||
rss.etag = res.Etag
|
||||
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
Generated
Vendored
+66
-57
@@ -28,12 +28,14 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
backoff "github.com/cenkalti/backoff/v5"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"golang.org/x/exp/maps"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/shareid"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
|
||||
@@ -97,7 +99,7 @@ func (c *Cache) Add(ctx context.Context, userid, shareID string) error {
|
||||
defer unlock()
|
||||
|
||||
if _, ok := c.UserShares.Load(userid); !ok {
|
||||
err := c.syncWithLock(ctx, userid)
|
||||
err := c.syncWithRetry(ctx, userid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -124,37 +126,21 @@ func (c *Cache) Add(ctx context.Context, userid, shareID string) error {
|
||||
Str("userID", userid).
|
||||
Str("shareID", shareID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting added share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting added share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("already exists when persisting added share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
err := cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, userid) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting added share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting added share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting added share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userid); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
log.Error().Err(err).Msg("persisting added share failed. giving up.")
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -167,8 +153,8 @@ func (c *Cache) Remove(ctx context.Context, userid, shareID string) error {
|
||||
span.SetAttributes(attribute.String("cs3.userid", userid))
|
||||
defer unlock()
|
||||
|
||||
if _, ok := c.UserShares.Load(userid); ok {
|
||||
err := c.syncWithLock(ctx, userid)
|
||||
if _, ok := c.UserShares.Load(userid); !ok {
|
||||
err := c.syncWithRetry(ctx, userid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -199,38 +185,21 @@ func (c *Cache) Remove(ctx context.Context, userid, shareID string) error {
|
||||
Str("userID", userid).
|
||||
Str("shareID", shareID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.Aborted:
|
||||
log.Debug().Msg("aborted when persisting removed share: etag changed. retrying...")
|
||||
// this is the expected status code from the server when the if-match etag check fails
|
||||
// continue with sync below
|
||||
case errtypes.PreconditionFailed:
|
||||
log.Debug().Msg("precondition failed when persisting removed share: etag changed. retrying...")
|
||||
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
|
||||
// continue with sync below
|
||||
case errtypes.AlreadyExists:
|
||||
log.Debug().Msg("file already existed when persisting removed share. retrying...")
|
||||
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
|
||||
// Thas happens when the cache thinks there is no file.
|
||||
// continue with sync below
|
||||
default:
|
||||
err := cas.RetryPersist(ctx, 100, persistFunc,
|
||||
func() error { return c.resyncAfterConflict(ctx, userid) },
|
||||
func(err error) { log.Debug().Err(err).Msg("CAS conflict persisting removed share, retrying...") },
|
||||
func(err error) {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("persisting removed share failed. giving up: %s", err.Error()))
|
||||
log.Error().Err(err).Msg("persisting removed share failed")
|
||||
return err
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userid); err != nil {
|
||||
},
|
||||
func(err error) {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
return err
|
||||
}
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -241,7 +210,7 @@ func (c *Cache) List(ctx context.Context, userid string) (map[string]SpaceShareI
|
||||
span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userid))
|
||||
defer unlock()
|
||||
if err := c.syncWithLock(ctx, userid); err != nil {
|
||||
if err := c.syncWithRetry(ctx, userid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -259,7 +228,18 @@ func (c *Cache) List(ctx context.Context, userid string) (map[string]SpaceShareI
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// syncWithLock treats NotFound as a legitimately empty cache (cold-start only).
|
||||
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, true)
|
||||
}
|
||||
|
||||
// Unlike syncWithLock, a NotFound here must not reset the cache -- a pending
|
||||
// mutation is about to overwrite it, dropping a sibling writer's data.
|
||||
func (c *Cache) resyncAfterConflict(ctx context.Context, userID string) error {
|
||||
return c.doSync(ctx, userID, false)
|
||||
}
|
||||
|
||||
func (c *Cache) doSync(ctx context.Context, userID string, resetOnNotFound bool) error {
|
||||
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.String("cs3.userid", userID))
|
||||
@@ -274,15 +254,28 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
dlreq := metadata.DownloadRequest{
|
||||
Path: userCreatedPath,
|
||||
}
|
||||
var hadEtag bool
|
||||
if us, ok := c.UserShares.Load(userID); ok && us.Etag != "" {
|
||||
hadEtag = true
|
||||
dlreq.IfNoneMatch = []string{us.Etag}
|
||||
}
|
||||
|
||||
dlres, err := c.storage.Download(ctx, dlreq)
|
||||
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
if reset, trashed := cas.DecideNotFoundReset(ctx, c.storage, userCreatedPath, resetOnNotFound, hadEtag, log); !reset {
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
if trashed {
|
||||
log.Error().Err(err).Msg("lost update: backing file was recently trashed")
|
||||
} else {
|
||||
log.Error().Err(err).Msg("lost update: backing file disappeared mid-retry")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.UserShares.Store(userID, &UserShareCache{UserShares: map[string]*SpaceShareIDs{}})
|
||||
span.SetStatus(codes.Ok, "")
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
@@ -355,6 +348,22 @@ func (c *Cache) Persist(ctx context.Context, userid string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncWithRetry retries syncWithLock's cold-start read on transient errors, since callers have no other retry wrapper.
|
||||
func (c *Cache) syncWithRetry(ctx context.Context, userID string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := backoff.Retry(ctx, func() (struct{}, error) {
|
||||
err := c.syncWithLock(ctx, userID)
|
||||
if err != nil && !cas.IsSyncTransient(err) {
|
||||
return struct{}{}, backoff.Permanent(err)
|
||||
}
|
||||
return struct{}{}, err
|
||||
}, backoff.WithBackOff(cas.NewBackoff()), backoff.WithMaxTries(20))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Cache) userCreatedPath(userid string) string {
|
||||
return filepath.Join("/", c.namespace, userid, c.filename)
|
||||
}
|
||||
|
||||
+4
@@ -26,6 +26,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/lookup"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
@@ -112,6 +113,9 @@ func (bs *Blobstore) Download(node *node.Node) (io.ReadCloser, error) {
|
||||
dest := bs.Path(node)
|
||||
file, err := os.Open(dest)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, errtypes.NotFound(dest)
|
||||
}
|
||||
return nil, errors.Wrapf(err, "could not read blob '%s'", dest)
|
||||
}
|
||||
return file, nil
|
||||
|
||||
Generated
Vendored
+6
@@ -1128,8 +1128,14 @@ func (fs *Decomposedfs) Download(ctx context.Context, ref *provider.Reference, o
|
||||
}
|
||||
var reader io.ReadCloser
|
||||
if openReaderFunc(ri) {
|
||||
if n.IsProcessing(ctx) {
|
||||
return nil, nil, errtypes.TooEarly(n.ID)
|
||||
}
|
||||
reader, err = fs.tp.ReadBlob(n)
|
||||
if err != nil {
|
||||
if _, ok := err.(errtypes.IsNotFound); ok {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, nil, errors.Wrap(err, "Decomposedfs: error download blob '"+n.ID+"'")
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -182,6 +182,9 @@ func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Refe
|
||||
if openReaderFunc(ri) {
|
||||
reader, err = fs.tp.ReadBlob(&revisionNode)
|
||||
if err != nil {
|
||||
if _, ok := err.(errtypes.IsNotFound); ok {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, nil, errors.Wrapf(err, "Decomposedfs: could not download blob of revision '%s' for node '%s'", n.ID, revisionKey)
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -704,10 +704,19 @@ 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 {
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
return unlock, errtypes.AlreadyExists(n.Name)
|
||||
}
|
||||
return unlock, err
|
||||
}
|
||||
h.Close()
|
||||
|
||||
// Mark processing immediately so a reader never sees "not processing";
|
||||
// overwritten later with the full status. acquireLock=false: lock already held.
|
||||
if err := n.SetXattrsWithContext(ctx, map[string][]byte{prefixes.StatusPrefix: []byte(node.ProcessingStatus)}, false); err != nil {
|
||||
return unlock, err
|
||||
}
|
||||
|
||||
_, subspan = tracer.Start(ctx, "node.CheckQuota")
|
||||
_, err = node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize)
|
||||
subspan.End()
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package metadata
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// barrierTimeout bounds how long an arrived Upload call waits for the
|
||||
// remaining callers before giving up, so a caller that never arrives (e.g.
|
||||
// because its own cold-start sync errored before reaching Upload) can't
|
||||
// hang the others for the full test-binary timeout.
|
||||
const barrierTimeout = 2 * time.Second
|
||||
|
||||
// BarrierStorage wraps a Storage and holds Upload calls until n goroutines have
|
||||
// arrived, then releases them all at once, to deterministically reproduce
|
||||
// concurrent-write races in tests.
|
||||
type BarrierStorage struct {
|
||||
Storage
|
||||
arrived int32
|
||||
n int32
|
||||
ready chan struct{}
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// NewBarrierStorage returns a BarrierStorage wrapping s that releases once n Upload calls have arrived.
|
||||
func NewBarrierStorage(s Storage, n int) *BarrierStorage {
|
||||
return &BarrierStorage{Storage: s, n: int32(n), ready: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Upload blocks until n calls have arrived, then delegates to the wrapped Storage.
|
||||
func (b *BarrierStorage) Upload(ctx context.Context, req UploadRequest) (*UploadResponse, error) {
|
||||
if atomic.AddInt32(&b.arrived, 1) >= b.n {
|
||||
b.closeOnce.Do(func() { close(b.ready) })
|
||||
}
|
||||
select {
|
||||
case <-b.ready:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(barrierTimeout):
|
||||
return nil, fmt.Errorf("barrier: timed out after %s waiting for %d/%d callers to arrive", barrierTimeout, atomic.LoadInt32(&b.arrived), b.n)
|
||||
}
|
||||
return b.Storage.Upload(ctx, req)
|
||||
}
|
||||
|
||||
// SimpleUpload routes through Upload so it also counts toward and waits on
|
||||
// the barrier, instead of promoting straight to the embedded Storage.
|
||||
func (b *BarrierStorage) SimpleUpload(ctx context.Context, uploadpath string, content []byte) error {
|
||||
_, err := b.Upload(ctx, UploadRequest{
|
||||
Path: uploadpath,
|
||||
Content: content,
|
||||
})
|
||||
return err
|
||||
}
|
||||
+38
@@ -430,6 +430,44 @@ func (cs3 *CS3) Delete(ctx context.Context, path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// WasRecentlyDeleted checks the recycle bin within a short window so a
|
||||
// long-settled deletion doesn't block a legitimate empty read.
|
||||
func (cs3 *CS3) WasRecentlyDeleted(ctx context.Context, path string) (bool, error) {
|
||||
ctx, span := tracer.Start(ctx, "WasRecentlyDeleted")
|
||||
defer span.End()
|
||||
|
||||
client, err := cs3.providerClient()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx, err = cs3.getAuthContext(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
target := utils.MakeRelativePath(path)
|
||||
now := time.Now()
|
||||
res, err := client.ListRecycle(ctx, &provider.ListRecycleRequest{
|
||||
Ref: &provider.Reference{ResourceId: cs3.SpaceRoot},
|
||||
FromTs: utils.TimeToTS(now.Add(-5 * time.Minute)),
|
||||
ToTs: utils.TimeToTS(now),
|
||||
PageSize: 1000,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if res.Status.Code != rpc.Code_CODE_OK {
|
||||
return false, errtypes.NewErrtypeFromStatus(res.Status)
|
||||
}
|
||||
|
||||
for _, item := range res.RecycleItems {
|
||||
if item.GetRef().GetPath() == target {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// ReadDir returns the entries in a given directory
|
||||
func (cs3 *CS3) ReadDir(ctx context.Context, path string) ([]string, error) {
|
||||
ctx, span := tracer.Start(ctx, "ReadDir")
|
||||
|
||||
+6
@@ -178,6 +178,12 @@ func (disk *Disk) Delete(_ context.Context, path string) error {
|
||||
return os.Remove(disk.targetPath(path))
|
||||
}
|
||||
|
||||
// WasRecentlyDeleted always reports false: Disk has no trash/recycle bin, so
|
||||
// a NotFound here stays ambiguous between "removed" and "never existed".
|
||||
func (disk *Disk) WasRecentlyDeleted(_ context.Context, _ string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// ReadDir returns the resource infos in a given directory
|
||||
func (disk *Disk) ReadDir(_ context.Context, p string) ([]string, error) {
|
||||
infos, err := os.ReadDir(disk.targetPath(p))
|
||||
|
||||
+3
@@ -70,6 +70,9 @@ type Storage interface {
|
||||
SimpleDownload(ctx context.Context, path string) ([]byte, error)
|
||||
Delete(ctx context.Context, path string) error
|
||||
Stat(ctx context.Context, path string) (*provider.ResourceInfo, error)
|
||||
// WasRecentlyDeleted reports whether path was removed vs. never existed.
|
||||
// Backends without trash support always report false (see OCISDEV-855).
|
||||
WasRecentlyDeleted(ctx context.Context, path string) (bool, error)
|
||||
|
||||
ReadDir(ctx context.Context, path string) ([]string, error)
|
||||
ListDir(ctx context.Context, path string) ([]*provider.ResourceInfo, error)
|
||||
|
||||
Vendored
+2
-1
@@ -1325,7 +1325,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-20261001150122-9557cab91f00
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20261008202759-e28d93df3fc9
|
||||
## explicit; go 1.24.0
|
||||
github.com/owncloud/reva/v2/cmd/revad/internal/grace
|
||||
github.com/owncloud/reva/v2/cmd/revad/runtime
|
||||
@@ -1576,6 +1576,7 @@ github.com/owncloud/reva/v2/pkg/share/cache/warmup/registry
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/cs3
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/json
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/cas
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/providercache
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache
|
||||
github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3/sharecache
|
||||
|
||||
Reference in new issue
Block a user