chore: [stable-8.0] bump reva

This commit is contained in:
Michal Klos committed 2026-10-08 22:37:31 +02:00
1 parent da4ab34396
commit acdfa71270
14 files changed
+465 -194

No files matched your search

@@ -31,13 +31,13 @@ import (
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/mitchellh/mapstructure"
"github.com/owncloud/reva/v2/pkg/password"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/sharedconf"
"github.com/owncloud/reva/v2/pkg/storage/utils/grants"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"google.golang.org/grpc"
@@ -99,10 +99,18 @@ func getShareManager(c *config) (publicshare.Manager, error) {
return nil, errtypes.NotFound("driver not found: " + c.Driver)
}
// TODO(labkode): add ctx to Close.
func (s *service) Close() error {
return nil
cm, ok := s.sm.(publicshare.ClosableManager)
if !ok {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return cm.Close(ctx)
}
func (s *service) UnprotectedEndpoints() []string {
return []string{"/cs3.sharing.link.v1beta1.LinkAPI/GetPublicShareByToken"}
}
+204 -120
View File
@@ -22,12 +22,9 @@ import (
"context"
"encoding/json"
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/rs/zerolog/log"
@@ -39,6 +36,7 @@ import (
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/mitchellh/mapstructure"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/publicshare"
@@ -50,16 +48,35 @@ import (
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storage/utils/metadata"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
// shareField and passwordField are the keys used to store a share's encoded
// proto and its bcrypt-hashed password in a db entry.
const (
shareField = "share"
passwordField = "password"
)
func init() {
registry.Register("json", NewFile)
registry.Register("jsoncs3", NewCS3)
registry.Register("jsonmemory", NewMemory)
}
// dbEntryString safely reads the string value stored under key in a db entry.
// Entries are read back from persistence as interface{} (map[string]interface{}
// with string values), so a corrupted or legacy record can hold an unexpected
// type; this reports that via ok instead of panicking.
func dbEntryString(v interface{}, key string) (string, bool) {
m, ok := v.(map[string]interface{})
if !ok {
return "", false
}
s, ok := m[key].(string)
return s, ok
}
// NewFile returns a new filesystem public shares manager.
func NewFile(c map[string]interface{}) (publicshare.Manager, error) {
conf := &fileConfig{}
@@ -109,13 +126,17 @@ func NewCS3(c map[string]interface{}) (publicshare.Manager, error) {
// New returns a new public share manager instance
func New(gwAddr string, pwHashCost, janitorRunInterval int, enableCleanup bool, p persistence.Persistence) (publicshare.Manager, error) {
janitorCtx, janitorCancel := context.WithCancel(context.Background())
m := &manager{
gatewayAddr: gwAddr,
mutex: &sync.Mutex{},
mutex: &sync.RWMutex{},
passwordHashCost: pwHashCost,
janitorRunInterval: janitorRunInterval,
enableExpiredSharesCleanup: enableCleanup,
persistence: p,
janitorCtx: janitorCtx,
janitorCancel: janitorCancel,
janitorDone: make(chan struct{}),
}
go m.startJanitorRun()
@@ -149,54 +170,88 @@ func (c *commonConfig) init() {
c.SharePasswordHashCost = 11
}
if c.JanitorRunInterval == 0 {
c.JanitorRunInterval = 60
c.JanitorRunInterval = 3600 // 1 hour
}
}
type manager struct {
gatewayAddr string
mutex *sync.Mutex
mutex *sync.RWMutex
persistence persistence.Persistence
passwordHashCost int
janitorRunInterval int
enableExpiredSharesCleanup bool
// janitorCtx/janitorCancel let Close ask startJanitorRun's goroutine to
// stop - including cancelling a cleanupExpiredShares run it may be in
// the middle of - and janitorDone lets Close wait until that goroutine
// has actually returned, instead of racing it on shutdown.
janitorCtx context.Context
janitorCancel context.CancelFunc
janitorDone chan struct{}
}
func (m *manager) init() error {
return m.persistence.Init(context.Background())
var _ publicshare.ClosableManager = (*manager)(nil)
// init is called at the top of every public method to lazily initialize the
// persistence layer. It must not take m.mutex: persistence.Init is already
// idempotent and self-synchronized (it returns immediately once the
// persistence layer reports itself initialized), so wrapping it in the
// manager's write lock added nothing but contention - and because a pending
// sync.RWMutex writer blocks new readers, that contention serialized every
// concurrent call through this single point regardless of whether it needed
// a read or a write lock.
func (m *manager) init(ctx context.Context) error {
return m.persistence.Init(ctx)
}
func (m *manager) startJanitorRun() {
defer close(m.janitorDone)
if !m.enableExpiredSharesCleanup {
return
}
ticker := time.NewTicker(time.Duration(m.janitorRunInterval) * time.Second)
work := make(chan os.Signal, 1)
signal.Notify(work, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT)
defer ticker.Stop()
for {
select {
case <-work:
case <-m.janitorCtx.Done():
return
case <-ticker.C:
m.cleanupExpiredShares()
if err := m.cleanupExpiredShares(); err != nil {
log.Err(err).Msg("publicShareJSONManager: error cleaning up expired shares")
}
}
}
}
// Close stops the janitor and waits for any in-flight cleanupExpiredShares
// run to finish, bounded by ctx. It satisfies publicshare.ClosableManager.
func (m *manager) Close(ctx context.Context) error {
m.janitorCancel()
select {
case <-m.janitorDone:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Dump exports public shares to channels (e.g. during migration)
func (m *manager) Dump(ctx context.Context, shareChan chan<- *publicshare.WithPassword) error {
log := appctx.GetLogger(ctx)
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return err
}
m.mutex.RLock()
defer m.mutex.RUnlock()
db, err := m.persistence.Read(ctx)
if err != nil {
return err
@@ -204,10 +259,16 @@ func (m *manager) Dump(ctx context.Context, shareChan chan<- *publicshare.WithPa
for _, v := range db {
var local publicshare.WithPassword
if err := utils.UnmarshalJSONToProtoV1([]byte(v.(map[string]interface{})["share"].(string)), &local.PublicShare); err != nil {
log.Error().Err(err).Msg("error unmarshalling share")
if share, ok := dbEntryString(v, shareField); ok {
if err := utils.UnmarshalJSONToProtoV1([]byte(share), &local.PublicShare); err != nil {
log.Error().Err(err).Msg("error unmarshalling share")
}
} else {
log.Error().Msg("error reading share entry: missing or invalid \"share\" field")
}
local.Password = v.(map[string]interface{})["password"].(string)
// password is optional: shares without password protection have no
// password field, so a missing/invalid entry just means "no password".
local.Password, _ = dbEntryString(v, passwordField)
shareChan <- &local
}
@@ -216,17 +277,18 @@ func (m *manager) Dump(ctx context.Context, shareChan chan<- *publicshare.WithPa
// Load imports public shares and received shares from channels (e.g. during migration)
func (m *manager) Load(ctx context.Context, shareChan <-chan *publicshare.WithPassword) error {
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return err
}
m.mutex.Lock()
defer m.mutex.Unlock()
db, err := m.persistence.Read(ctx)
if err != nil {
return err
}
dbCopy := persistence.Copy(db)
for ps := range shareChan {
encShare, err := utils.MarshalProtoV1ToJSON(&ps.PublicShare)
@@ -234,12 +296,12 @@ func (m *manager) Load(ctx context.Context, shareChan <-chan *publicshare.WithPa
return err
}
db[ps.PublicShare.Id.GetOpaqueId()] = map[string]interface{}{
"share": string(encShare),
"password": ps.Password,
dbCopy[ps.PublicShare.Id.GetOpaqueId()] = map[string]interface{}{
shareField: string(encShare),
passwordField: ps.Password,
}
}
return m.persistence.Write(ctx, db)
return m.persistence.Write(ctx, dbCopy)
}
// CreatePublicShare adds a new entry to manager.shares
@@ -294,33 +356,34 @@ func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *pr
}
proto.Merge(&ps.PublicShare, s)
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
return nil, err
}
encShare, err := utils.MarshalProtoV1ToJSON(&ps.PublicShare)
if err != nil {
return nil, err
}
if err := m.init(ctx); err != nil {
return nil, err
}
m.mutex.Lock()
defer m.mutex.Unlock()
db, err := m.persistence.Read(ctx)
if err != nil {
return nil, err
}
dbCopy := persistence.Copy(db)
if _, ok := db[s.Id.GetOpaqueId()]; !ok {
db[s.Id.GetOpaqueId()] = map[string]interface{}{
"share": string(encShare),
"password": ps.Password,
if _, ok := dbCopy[s.Id.GetOpaqueId()]; !ok {
dbCopy[s.Id.GetOpaqueId()] = map[string]interface{}{
shareField: string(encShare),
passwordField: ps.Password,
}
} else {
return nil, errors.New("key already exists")
}
err = m.persistence.Write(ctx, db)
err = m.persistence.Write(ctx, dbCopy)
if err != nil {
return nil, err
}
@@ -387,36 +450,37 @@ func (m *manager) UpdatePublicShare(ctx context.Context, u *user.User, req *link
Nanos: uint32(now % int64(time.Second)),
}
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return nil, err
}
m.mutex.Lock()
defer m.mutex.Unlock()
db, err := m.persistence.Read(ctx)
if err != nil {
return nil, err
}
dbCopy := persistence.Copy(db)
encShare, err := utils.MarshalProtoV1ToJSON(share)
if err != nil {
return nil, err
}
data, ok := db[share.Id.OpaqueId].(map[string]interface{})
data, ok := dbCopy[share.Id.OpaqueId].(map[string]interface{})
if !ok {
data = map[string]interface{}{}
}
if ok && passwordChanged {
data["password"] = newPasswordEncoded
data[passwordField] = newPasswordEncoded
}
data["share"] = string(encShare)
data[shareField] = string(encShare)
db[share.Id.OpaqueId] = data
dbCopy[share.Id.OpaqueId] = data
err = m.persistence.Write(ctx, db)
err = m.persistence.Write(ctx, dbCopy)
if err != nil {
return nil, err
}
@@ -426,13 +490,13 @@ func (m *manager) UpdatePublicShare(ctx context.Context, u *user.User, req *link
// GetPublicShare gets a public share either by ID or Token.
func (m *manager) GetPublicShare(ctx context.Context, u *user.User, ref *link.PublicShareReference, sign bool) (*link.PublicShare, error) {
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return nil, err
}
m.mutex.RLock()
defer m.mutex.RUnlock()
if ref.GetToken() != "" {
ps, pw, err := m.getByToken(ctx, ref.GetToken())
if err != nil {
@@ -453,19 +517,20 @@ func (m *manager) GetPublicShare(ctx context.Context, u *user.User, ref *link.Pu
}
for _, v := range db {
d := v.(map[string]interface{})["share"]
passDB := v.(map[string]interface{})["password"].(string)
share, ok := dbEntryString(v, shareField)
if !ok {
continue
}
passDB, _ := dbEntryString(v, passwordField)
var ps link.PublicShare
if err := utils.UnmarshalJSONToProtoV1([]byte(d.(string)), &ps); err != nil {
if err := utils.UnmarshalJSONToProtoV1([]byte(share), &ps); err != nil {
return nil, err
}
if ref.GetId().GetOpaqueId() == ps.Id.OpaqueId {
if publicshare.IsExpired(&ps) {
if err := m.revokeExpiredPublicShare(ctx, &ps); err != nil {
return nil, err
}
// actual deletion is left to the janitor (cleanupExpiredShares)
return nil, errtypes.NotFound("no shares found by id:" + ref.GetId().String())
}
if ps.PasswordProtected && sign {
@@ -483,20 +548,25 @@ func (m *manager) GetPublicShare(ctx context.Context, u *user.User, ref *link.Pu
// ListPublicShares retrieves all the shares on the manager that are valid.
func (m *manager) ListPublicShares(ctx context.Context, u *user.User, filters []*link.ListPublicSharesRequest_Filter, sign bool) ([]*link.PublicShare, error) {
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return nil, err
}
log := appctx.GetLogger(ctx)
m.mutex.RLock()
// Ranging over db below happens after the lock is released, which is safe
// because we never mutate it: writers copy before they mutate, and the
// persistence layer publishes a new map instead of changing this one.
db, err := m.persistence.Read(ctx)
if err != nil {
m.mutex.RUnlock()
return nil, err
}
m.mutex.RUnlock()
log := appctx.GetLogger(ctx)
client, err := pool.GetGatewayServiceClient(m.gatewayAddr)
if err != nil {
return nil, errors.Wrap(err, "failed to list shares")
@@ -506,16 +576,17 @@ func (m *manager) ListPublicShares(ctx context.Context, u *user.User, filters []
shares := []*link.PublicShare{}
for _, v := range db {
var local publicShare
if err := utils.UnmarshalJSONToProtoV1([]byte(v.(map[string]interface{})["share"].(string)), &local.PublicShare); err != nil {
share, ok := dbEntryString(v, shareField)
if !ok {
log.Warn().Interface("entry", v).Msg("ListPublicShares: skipping entry with missing or invalid \"share\" field")
continue
}
if err := utils.UnmarshalJSONToProtoV1([]byte(share), &local.PublicShare); err != nil {
return nil, err
}
if publicshare.IsExpired(&local.PublicShare) {
if err := m.revokeExpiredPublicShare(ctx, &local.PublicShare); err != nil {
log.Error().Err(err).
Str("share_token", local.Token).
Msg("failed to revoke expired public share")
}
// actual deletion is left to the janitor (cleanupExpiredShares)
continue
}
@@ -576,67 +647,72 @@ func (m *manager) ListPublicShares(ctx context.Context, u *user.User, filters []
return shares, nil
}
func (m *manager) cleanupExpiredShares() {
func (m *manager) cleanupExpiredShares() error {
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
return
// Another goroutine may hold the lock for a while; once we get it, skip the work if Close already asked us to stop.
if err := m.janitorCtx.Err(); err != nil {
return err
}
// Deriving from m.janitorCtx (not context.Background()) means Close
// cancels an in-flight run immediately instead of leaving it to run out its full timeout.
ctx, cancel := context.WithTimeout(m.janitorCtx, 60*time.Second)
defer cancel()
db, _ := m.persistence.Read(context.Background())
for _, v := range db {
d := v.(map[string]interface{})["share"]
var ps link.PublicShare
_ = utils.UnmarshalJSONToProtoV1([]byte(d.(string)), &ps)
if publicshare.IsExpired(&ps) {
_ = m.revokeExpiredPublicShare(context.Background(), &ps)
}
}
}
// revokeExpiredPublicShare doesn't have a lock inside, ensure a lock before call
func (m *manager) revokeExpiredPublicShare(ctx context.Context, s *link.PublicShare) error {
if !m.enableExpiredSharesCleanup {
return nil
}
err := m.revokePublicShare(ctx, &link.PublicShareReference{
Spec: &link.PublicShareReference_Id{
Id: &link.PublicShareId{
OpaqueId: s.Id.OpaqueId,
},
},
})
if err != nil {
log.Err(err).Msg(fmt.Sprintf("publicShareJSONManager: error deleting public share with opaqueId: %s", s.Id.OpaqueId))
if err := m.init(ctx); err != nil {
return err
}
return nil
read, err := m.persistence.Read(ctx)
if err != nil {
return err
}
db := persistence.Copy(read)
var changed bool
for id, v := range db {
share, ok := dbEntryString(v, shareField)
if !ok {
continue
}
var ps link.PublicShare
if err := utils.UnmarshalJSONToProtoV1([]byte(share), &ps); err != nil {
continue
}
if publicshare.IsExpired(&ps) {
delete(db, id)
changed = true
}
}
if !changed {
return nil
}
return m.persistence.Write(ctx, db)
}
// RevokePublicShare undocumented.
func (m *manager) RevokePublicShare(ctx context.Context, _ *user.User, ref *link.PublicShareReference) error {
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return err
}
m.mutex.Lock()
defer m.mutex.Unlock()
return m.revokePublicShare(ctx, ref)
}
// revokePublicShare doesn't have a lock inside, ensure a lock before call
func (m *manager) revokePublicShare(ctx context.Context, ref *link.PublicShareReference) error {
db, err := m.persistence.Read(ctx)
read, err := m.persistence.Read(ctx)
if err != nil {
return err
}
db := persistence.Copy(read)
switch {
case ref.GetId() != nil && ref.GetId().OpaqueId != "":
@@ -666,13 +742,18 @@ func (m *manager) getByToken(ctx context.Context, token string) (*link.PublicSha
}
for _, v := range db {
share, ok := dbEntryString(v, shareField)
if !ok {
continue
}
var local link.PublicShare
if err := utils.UnmarshalJSONToProtoV1([]byte(v.(map[string]interface{})["share"].(string)), &local); err != nil {
if err := utils.UnmarshalJSONToProtoV1([]byte(share), &local); err != nil {
return nil, "", err
}
if local.Token == token {
passDB := v.(map[string]interface{})["password"].(string)
passDB, _ := dbEntryString(v, passwordField)
return &local, passDB, nil
}
}
@@ -682,30 +763,33 @@ func (m *manager) getByToken(ctx context.Context, token string) (*link.PublicSha
// GetPublicShareByToken gets a public share by its opaque token.
func (m *manager) GetPublicShareByToken(ctx context.Context, token string, auth *link.PublicShareAuthentication, sign bool) (*link.PublicShare, error) {
m.mutex.Lock()
defer m.mutex.Unlock()
if err := m.init(); err != nil {
if err := m.init(ctx); err != nil {
return nil, err
}
m.mutex.RLock()
defer m.mutex.RUnlock()
db, err := m.persistence.Read(ctx)
if err != nil {
return nil, err
}
for _, v := range db {
passDB := v.(map[string]interface{})["password"].(string)
share, ok := dbEntryString(v, shareField)
if !ok {
continue
}
passDB, _ := dbEntryString(v, passwordField)
var local link.PublicShare
if err := utils.UnmarshalJSONToProtoV1([]byte(v.(map[string]interface{})["share"].(string)), &local); err != nil {
if err := utils.UnmarshalJSONToProtoV1([]byte(share), &local); err != nil {
return nil, err
}
if local.Token == token {
if publicshare.IsExpired(&local) {
if err := m.revokeExpiredPublicShare(ctx, &local); err != nil {
return nil, err
}
// actual deletion is left to the janitor (cleanupExpiredShares)
break
}
@@ -22,6 +22,8 @@ import (
"context"
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/owncloud/reva/v2/pkg/errtypes"
@@ -36,9 +38,23 @@ type db struct {
}
type cs3 struct {
initialized bool
// initialized is read on every call (Init is called unconditionally by
// the manager ahead of every Read/Write) and must stay lock-free once
// true, or every already-initialized caller would queue behind mu for a
// single bool check - and worse, behind whatever Read is doing with mu
// at the time, since they'd be contending for the same lock.
initialized atomic.Bool
s metadata.Storage
// initMu serializes the one-time (and retried-on-failure) call into
// s.Init. It is deliberately not mu: that state is independent of the
// mtime cache below, and sharing a lock would reintroduce the same
// contention initialized/atomic.Bool exists to avoid.
initMu sync.Mutex
// cs3 caches the remote publicshares.json in p.db and only refetches it when
// its mtime advances. That cache refill mutates p.db as a side effect of
// Read, so Read cannot be treated as a pure/reentrant read by callers - mu
// serializes access to p.db regardless of how the caller itself locks.
mu sync.Mutex
db db
}
@@ -53,7 +69,14 @@ func New(s metadata.Storage) persistence.Persistence {
}
func (p *cs3) Init(ctx context.Context) error {
if p.initialized {
if p.initialized.Load() {
return nil
}
p.initMu.Lock()
defer p.initMu.Unlock()
if p.initialized.Load() {
return nil
}
@@ -61,20 +84,24 @@ func (p *cs3) Init(ctx context.Context) error {
if err != nil {
return err
}
p.initialized = true
p.initialized.Store(true)
return nil
}
func (p *cs3) Read(ctx context.Context) (persistence.PublicShares, error) {
if !p.initialized {
if !p.initialized.Load() {
return nil, fmt.Errorf("not initialized")
}
// We use the Lock because the read function updates the cache. So most time operations should be fast.
p.mu.Lock()
defer p.mu.Unlock()
info, err := p.s.Stat(ctx, "publicshares.json")
if err != nil {
if _, ok := err.(errtypes.NotFound); ok {
return p.db.publicShares, nil // Nothing to sync against
return p.db.publicShares, nil
}
return nil, err
}
@@ -94,9 +121,13 @@ func (p *cs3) Read(ctx context.Context) (persistence.PublicShares, error) {
}
func (p *cs3) Write(ctx context.Context, db persistence.PublicShares) error {
if !p.initialized {
if !p.initialized.Load() {
return fmt.Errorf("not initialized")
}
p.mu.Lock()
defer p.mu.Unlock()
dbAsJSON, err := json.Marshal(db)
if err != nil {
return err
@@ -107,5 +138,13 @@ func (p *cs3) Write(ctx context.Context, db persistence.PublicShares) error {
Path: "publicshares.json",
IfUnmodifiedSince: p.db.mtime,
})
return err
if err != nil {
return err
}
// Invalidate the cache to minimize the risk of inconsistency.
p.db.mtime = time.Time{}
p.db.publicShares = persistence.PublicShares{}
return nil
}
@@ -50,6 +50,6 @@ func (p *memory) Write(_ context.Context, db persistence.PublicShares) error {
if p.db == nil {
return fmt.Errorf("not initialized")
}
p.db = db
p.db = persistence.Copy(db)
return nil
}
@@ -26,6 +26,32 @@ type PublicShares map[string]interface{}
// Persistence defines the interface for the json publicshare manager persistence layers
type Persistence interface {
Init(context.Context) error
// Read returns the share database for reading only. The result may alias
// the implementation's own cache and be shared with concurrent readers, so
// a caller that intends to mutate it - or to hand it to Write - must take
// its own Copy first. Implementations must publish a new map rather than
// mutate one they have already returned.
Read(context.Context) (PublicShares, error)
Write(context.Context, PublicShares) error
}
// Copy returns a copy of db that shares no mutable state with it: a fresh
// top-level map plus a fresh copy of each share's own map. Callers that mutate
// what Read returned need it, so that a reader still ranging over the same
// result after releasing its lock cannot race the mutation (see
// manager.UpdatePublicShare, which rewrites an existing share's fields).
func Copy(db PublicShares) PublicShares {
out := make(PublicShares, len(db))
for k, v := range db {
if entry, ok := v.(map[string]interface{}); ok {
entryCopy := make(map[string]interface{}, len(entry))
for ek, ev := range entry {
entryCopy[ek] = ev
}
out[k] = entryCopy
continue
}
out[k] = v
}
return out
}
+6
View File
@@ -66,6 +66,12 @@ type LoadableManager interface {
Load(ctx context.Context, shareChan <-chan *WithPassword) error
}
// ClosableManager defines a share manager that owns background work (e.g. a
// janitor) which must be stopped and awaited on shutdown
type ClosableManager interface {
Close(ctx context.Context) error
}
// CreateSignature calculates a signature for a public share.
func CreateSignature(token, pw string, expiration time.Time) (string, error) {
h := sha256.New()
-24
View File
@@ -1,24 +0,0 @@
package rgrpc
import (
"math"
"os"
"time"
)
const (
_serverMaxConnectionAgeEnv = "GRPC_MAX_CONNECTION_AGE"
// same default as grpc
infinity = time.Duration(math.MaxInt64)
_defaultMaxConnectionAge = infinity
)
// GetMaxConnectionAge returns the maximum grpc connection age.
func GetMaxConnectionAge() time.Duration {
d, err := time.ParseDuration(os.Getenv(_serverMaxConnectionAgeEnv))
if err != nil {
return _defaultMaxConnectionAge
}
return d
}
+13 -2
View File
@@ -24,6 +24,7 @@ import (
"io"
"net"
"sort"
"time"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/mitchellh/mapstructure"
@@ -50,6 +51,12 @@ import (
const (
// Prefix used to auto-propagate GRPC metadata across reva services
AutoPropPrefix = "autoprop-"
// _minKeepalivePingInterval is the shortest keepalive ping interval we
// accept from a client. Clients cannot ping more often than every ten
// seconds, so this leaves headroom below that; grpc's own default would
// GOAWAY anything more frequent than every five minutes.
_minKeepalivePingInterval = 5 * time.Second
)
// UnaryInterceptors is a map of registered unary grpc interceptors.
@@ -252,8 +259,12 @@ func (s *Server) registerServices() error {
if s.conf.TLSSettings.tlsConfig != nil {
opts = append(opts, grpc.Creds(credentials.NewTLS(s.conf.TLSSettings.tlsConfig)))
}
opts = append(opts, grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionAge: GetMaxConnectionAge(), // this forces clients to reconnect after 30 seconds, triggering a new DNS lookup to pick up new IPs
// accept the keepalive pings our clients send while an rpc is in flight, so
// that they can tell a peer that stopped answering from one that is merely
// slow
opts = append(opts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: _minKeepalivePingInterval,
PermitWithoutStream: true,
}))
grpcServer := grpc.NewServer(opts...)
+44 -31
View File
@@ -29,6 +29,7 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
)
var (
@@ -84,42 +85,54 @@ func NewConn(target string, opts ...Option) (*grpc.ClientConn, error) {
maxRcvMsgSize = s
}
opt := []grpc.DialOption{}
// only dial with keepalive params once they are actually configured, so that an unconfigured
// deployment keeps grpc's own behavior. Where they are set, a black-holed peer fails the rpcs
// on its connection instead of hanging for the caller's full timeout, see
// GetClientKeepaliveParams in pkg/rgrpc/todo/pool/keepalive.go.
if kp := GetClientKeepaliveParams(); kp != (keepalive.ClientParameters{}) {
opt = append(opt, grpc.WithKeepaliveParams(kp))
}
conn, err := grpc.NewClient(
target,
grpc.WithTransportCredentials(cred),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(maxRcvMsgSize),
),
grpc.WithDefaultServiceConfig(`{
append(opt,
grpc.WithTransportCredentials(cred),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(maxRcvMsgSize),
),
grpc.WithDefaultServiceConfig(`{
"loadBalancingPolicy":"round_robin"
}`),
/* we may want to retry more often than the default transparent retry, see https://grpc.io/docs/guides/retry/#retry-configuration
grpc.WithDefaultServiceConfig(`{
"loadBalancingPolicy":"round_robin"
"methodConfig": [
{
"name": [
{ "service": "grpc.examples.echo.Echo" }
],
"retryPolicy": {
"maxAttempts": 3,
"initialBackoff": "0.1s",
"maxBackoff": "1s",
"backoffMultiplier": 2,
"retryableStatusCodes": ["UNAVAILABLE", "CANCELLED", "RESOURCE_EXHAUSTED", "DEADLINE_EXCEEDED"]
/* we may want to retry more often than the default transparent retry, see https://grpc.io/docs/guides/retry/#retry-configuration
grpc.WithDefaultServiceConfig(`{
"loadBalancingPolicy":"round_robin"
"methodConfig": [
{
"name": [
{ "service": "grpc.examples.echo.Echo" }
],
"retryPolicy": {
"maxAttempts": 3,
"initialBackoff": "0.1s",
"maxBackoff": "1s",
"backoffMultiplier": 2,
"retryableStatusCodes": ["UNAVAILABLE", "CANCELLED", "RESOURCE_EXHAUSTED", "DEADLINE_EXCEEDED"]
}
}
}
]
}`),
*/
grpc.WithStatsHandler(otelgrpc.NewClientHandler(
otelgrpc.WithTracerProvider(
options.tracerProvider,
),
otelgrpc.WithPropagators(
rtrace.Propagator,
),
)),
]
}`),
*/
grpc.WithStatsHandler(otelgrpc.NewClientHandler(
otelgrpc.WithTracerProvider(
options.tracerProvider,
),
otelgrpc.WithPropagators(
rtrace.Propagator,
),
)),
)...,
)
if err != nil {
return nil, err
+81
View File
@@ -0,0 +1,81 @@
package pool
import (
"os"
"time"
"google.golang.org/grpc/keepalive"
)
const (
_clientKeepaliveTimeEnv = "GRPC_CLIENT_KEEPALIVE_TIME"
_clientKeepaliveTimeoutEnv = "GRPC_CLIENT_KEEPALIVE_TIMEOUT"
// Used when a keepalive time is configured but the timeout is not usable, so
// that a half configured setup still gives up on a dead peer rather than
// sitting out grpc's longer stock timeout of 20s.
_defaultKeepaliveTimeout = 10 * time.Second
)
// GetClientKeepaliveParams returns the keepalive parameters for every grpc
// client connection of the pool, read from GRPC_CLIENT_KEEPALIVE_TIME and
// GRPC_CLIENT_KEEPALIVE_TIMEOUT.
//
// Once they are set, a peer that stops answering on an established connection -
// a black-holed node, a wedged process - can be told apart from one that is
// merely slow: grpc pings it while an rpc is in flight and fails the requests on
// that connection when no answer arrives within the timeout, instead of waiting
// for as long as the caller allows. The pings are only sent while an rpc is in
// flight, so a healthy server never sees them often enough to complain.
//
// Keepalive is strictly opt-in and driven by the keepalive time alone. Without a
// usable time this returns the zero ClientParameters, which NewConn reads as
// "add no keepalive dial option at all", so grpc's own behavior applies and no
// pings are sent - a deployment that configured nothing behaves exactly as it
// did before this package started setting keepalive params. A time with no
// usable timeout gets a working default instead, so detection cannot be left
// half configured.
//
// Nothing is salvaged or second-guessed: a value that is empty, negative or not
// a valid duration - "20" without a unit suffix - reads the same as unset. ocis
// configures its go-micro based clients from the same two env vars and applies
// the same rules, so both sets of clients behave identically for every input.
// grpc also raises any time below 10s to 10s on its own.
func GetClientKeepaliveParams() keepalive.ClientParameters {
keepaliveTime := duration(_clientKeepaliveTimeEnv)
if keepaliveTime == 0 {
// not configured: the zero value tells NewConn to skip the keepalive
// dial option, so grpc's own behavior applies and no pings are sent
return keepalive.ClientParameters{}
}
keepaliveTimeout := duration(_clientKeepaliveTimeoutEnv)
if keepaliveTimeout <= 0 {
// a time without a usable timeout: fall back to a working default
keepaliveTimeout = _defaultKeepaliveTimeout
}
return keepalive.ClientParameters{
// If set below 10s, the grpc library will set a minimum value of 10s.
Time: keepaliveTime,
Timeout: keepaliveTimeout,
// no pings on connections that have no rpc in flight: an idle
// connection has nothing to rescue, and staying quiet keeps us clear of
// any server side ping enforcement
PermitWithoutStream: false,
}
}
// duration reads a duration from the environment. Anything that is not a usable
// positive duration - unset, empty, negative or missing its unit suffix - reads
// as zero, which every caller treats as "not configured".
func duration(env string) time.Duration {
v, ok := os.LookupEnv(env)
if !ok {
return 0
}
d, err := time.ParseDuration(v)
if err != nil || d < 0 {
return 0
}
return d
}
+28 -1
View File
@@ -39,6 +39,7 @@ import (
"google.golang.org/grpc/metadata"
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
"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/rgrpc/todo/pool"
@@ -51,6 +52,12 @@ func init() {
tracer = otel.Tracer("github.com/owncloud/reva/pkg/storage/utils/metadata")
}
// defaultAuthRPCTimeout bounds the machine auth Authenticate call made for
// every metadata operation. It only has to cover a token mint, so it is
// generous - its purpose is to turn a stalled gateway into an error instead of
// a goroutine that waits for the lifetime of the process.
const defaultAuthRPCTimeout = 10 * time.Second
// CS3 represents a metadata storage with a cs3 storage backend
type CS3 struct {
SpaceRoot *provider.ResourceId
@@ -60,6 +67,7 @@ type CS3 struct {
useSystemUser bool
serviceUser *user.User
machineAuthAPIKey string
authRPCTimeout time.Duration
dataGatewayClient *http.Client
}
@@ -69,6 +77,7 @@ func NewCS3(gwAddr, providerAddr string) (s *CS3) {
return &CS3{
providerAddr: providerAddr,
gatewayAddr: gwAddr,
authRPCTimeout: defaultAuthRPCTimeout,
dataGatewayClient: http.DefaultClient,
}
}
@@ -600,12 +609,30 @@ func (cs3 *CS3) getAuthContext(ctx context.Context) (context.Context, error) {
}
authCtx = ctxpkg.ContextSetUser(authCtx, cs3.serviceUser)
authRes, err := client.Authenticate(authCtx, &gateway.AuthenticateRequest{
// The Authenticate call gets a context of its own: a gateway that is stuck
// on a downstream storage provider accepts the connection and then never
// answers, and there is nothing else that would ever end the wait. The
// deadline cannot live on authCtx, because the caller runs its own RPC on
// the context we return here.
timeout := cs3.authRPCTimeout
if timeout <= 0 {
timeout = defaultAuthRPCTimeout
}
rpcCtx, cancel := context.WithTimeout(authCtx, timeout)
defer cancel()
start := time.Now()
authRes, err := client.Authenticate(rpcCtx, &gateway.AuthenticateRequest{
Type: "machine",
ClientId: "userid:" + cs3.serviceUser.Id.OpaqueId,
ClientSecret: cs3.machineAuthAPIKey,
})
if err != nil {
// this used to fail silently by never returning at all, so make sure
// an exhausted deadline is visible at production log level
appctx.GetLogger(ctx).Warn().Err(err).Str("gateway_addr", cs3.gatewayAddr).
Dur("elapsed", time.Since(start)).Dur("timeout", timeout).Msg("cs3: machine authentication failed")
return nil, err
}
if authRes.GetStatus().GetCode() != rpc.Code_CODE_OK {