Skip to content

Commit

Permalink
fix: expand lock to include check logi
Browse files Browse the repository at this point in the history
  • Loading branch information
LinZexiao committed Jul 5, 2022
1 parent 0b654bc commit 5af8fba
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions piecestorage/storagemgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ func NewPieceStorageManager(cfg *config.PieceStorage) (*PieceStorageManager, err
func (p *PieceStorageManager) FindStorageForRead(ctx context.Context, s string) (IPieceStorage, error) {
var storages []IPieceStorage
p.RLock()
defer p.RUnlock()

for _, st := range p.storages {
has, err := st.Has(ctx, s)
if err != nil {
Expand All @@ -69,7 +71,6 @@ func (p *PieceStorageManager) FindStorageForRead(ctx context.Context, s string)
storages = append(storages, st)
}
}
p.RUnlock()

if len(storages) == 0 {
return nil, fmt.Errorf("unable to find piece in storage %s", s)
Expand All @@ -81,13 +82,14 @@ func (p *PieceStorageManager) FindStorageForRead(ctx context.Context, s string)
func (p *PieceStorageManager) FindStorageForWrite(size int64) (IPieceStorage, error) {
var storages []IPieceStorage
p.RLock()
defer p.RUnlock()

for _, st := range p.storages {
//todo readuce too much check on storage
if !st.ReadOnly() && st.CanAllocate(size) {
storages = append(storages, st)
}
}
p.RUnlock()

if len(storages) == 0 {
return nil, fmt.Errorf("unable to find enough space for size %d", size)
Expand All @@ -98,21 +100,21 @@ func (p *PieceStorageManager) FindStorageForWrite(size int64) (IPieceStorage, er

func (p *PieceStorageManager) AddMemPieceStorage(s IPieceStorage) {
p.Lock()
defer p.Unlock()

p.storages[s.GetName()] = s
p.Unlock()
}

func (p *PieceStorageManager) AddPieceStorage(s IPieceStorage) error {
// check if storage already exist in manager and it's name is not empty
p.RLock()
p.Lock()
defer p.Unlock()

_, ok := p.storages[s.GetName()]
p.RUnlock()
if ok {
return fmt.Errorf("duplicate storage name: %s", s.GetName())
}
p.Lock()
p.storages[s.GetName()] = s
p.Unlock()
return nil
}

Expand All @@ -128,15 +130,14 @@ func randStorageSelector(storages []IPieceStorage) (IPieceStorage, error) {
}

func (p *PieceStorageManager) RemovePieceStorage(name string) error {
p.RLock()
p.Lock()
defer p.Unlock()

_, exist := p.storages[name]
p.RUnlock()
if !exist {
return fmt.Errorf("storage %s not exist", name)
}
p.Lock()
delete(p.storages, name)
p.Unlock()
return nil
}

Expand Down

0 comments on commit 5af8fba

Please sign in to comment.