-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathshards.go
213 lines (190 loc) · 4.38 KB
/
shards.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright 2021 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// # lockless sharding
// * shard choice responding to backpressure by running operation
// * read prioritisation over writing
// * free slots allow write
package sharky
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"sync"
"github.com/ethersphere/bee/pkg/swarm"
)
var (
DataSize int64 = swarm.ChunkWithSpanSize
ErrTooLong = errors.New("data too long")
ErrCapacityReached = errors.New("capacity reached")
)
// models the sharded chunkdb
type Shards struct {
writeOps chan *operation // shared write operations channel
pool *sync.Pool // pool to save on allocating for operation
shards []*shard
quit chan struct{}
}
// New constructs a new sharded chunk db
func New(basedir string, shardCnt int, limit int64) (*Shards, error) {
pool := &sync.Pool{New: func() interface{} {
return newOp()
}}
sh := &Shards{
pool: pool,
writeOps: make(chan *operation),
shards: make([]*shard, shardCnt),
quit: make(chan struct{}),
}
for i := range sh.shards {
s, err := sh.create(uint8(i), limit, basedir)
if err != nil {
return nil, err
}
sh.shards[i] = s
}
return sh, nil
}
// Close closes each shard
func (s *Shards) Close() error {
close(s.quit)
errs := []string{}
errc := make(chan error)
for _, sh := range s.shards {
sh := sh
go func() {
errc <- sh.close()
}()
}
for range s.shards {
if err := <-errc; err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) > 0 {
return fmt.Errorf("closing shards: %s", strings.Join(errs, ", "))
}
return nil
}
// create creates a new shard with index, max capacity limit, file within base directory
func (s *Shards) create(index uint8, limit int64, basedir string) (*shard, error) {
fh, err := os.OpenFile(path.Join(basedir, fmt.Sprintf("shard_%03d", index)), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
fi, err := fh.Stat()
if err != nil {
return nil, err
}
size := fi.Size() / DataSize
ffh, err := os.OpenFile(path.Join(basedir, fmt.Sprintf("free_%03d", index)), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
ffi, err := ffh.Stat()
if err != nil {
return nil, err
}
freed := make(chan int64)
wg := &sync.WaitGroup{}
if ffi.Size() > 0 {
frees, err := ioutil.ReadAll(ffh)
if err != nil {
return nil, err
}
var free []int64
err = json.Unmarshal(frees, &free)
if err != nil {
return nil, err
}
for _, offset := range free {
offset := offset
if offset/DataSize >= size {
continue
}
wg.Add(1)
go func() {
freed <- offset
wg.Done()
}()
}
}
sh := &shard{
readOps: make(chan *operation),
writeOps: s.writeOps,
free: make(chan int64),
freed: freed,
index: index,
limit: limit,
fh: fh,
ffh: ffh,
quit: s.quit,
wg: wg,
}
sh.wg.Add(2) // initialisation requires so that s.wg.Wait() does not hold prematurely
go sh.offer(size)
go sh.process()
return sh, nil
}
func (s *Shards) Read(ctx context.Context, loc Location) (data []byte, err error) {
op, f := s.newReadOp(loc)
defer f()
sh := s.shards[loc.Shard]
select {
case sh.readOps <- op:
case <-ctx.Done():
return nil, ctx.Err()
}
select {
case err = <-op.err:
case <-ctx.Done():
return nil, ctx.Err()
}
return op.buffer[:op.location.Length], err
}
func (s *Shards) Write(ctx context.Context, data []byte) (loc Location, err error) {
if len(data) > int(DataSize) {
return loc, ErrTooLong
}
op, f := s.newWriteOp(data)
defer f()
select {
case s.writeOps <- op:
case <-ctx.Done():
return loc, ctx.Err()
}
select {
case err = <-op.err:
case <-ctx.Done():
return loc, ctx.Err()
}
return op.location, err
}
func (s *Shards) Release(ctx context.Context, loc Location) {
sh := s.shards[loc.Shard]
sh.release(loc.Offset)
}
func newOp() *operation {
return &operation{
location: Location{},
err: make(chan error),
buffer: make([]byte, DataSize),
}
}
func (s *Shards) newReadOp(loc Location) (*operation, func()) {
op := s.pool.Get().(*operation)
f := func() { s.pool.Put(op) }
op.location = loc
return op, f
}
func (s *Shards) newWriteOp(data []byte) (*operation, func()) {
op := s.pool.Get().(*operation)
f := func() { s.pool.Put(op) }
op.data = data
return op, f
}