/
dirworker.go
360 lines (308 loc) · 9.21 KB
/
dirworker.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package sdk
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"path"
"strings"
"sync"
"time"
"github.com/0chain/errors"
"github.com/0chain/gosdk/core/common"
"github.com/0chain/gosdk/core/util"
"github.com/0chain/gosdk/zboxcore/allocationchange"
"github.com/0chain/gosdk/zboxcore/blockchain"
"github.com/0chain/gosdk/zboxcore/client"
"github.com/0chain/gosdk/zboxcore/fileref"
"github.com/0chain/gosdk/zboxcore/logger"
l "github.com/0chain/gosdk/zboxcore/logger"
"github.com/0chain/gosdk/zboxcore/zboxutil"
"github.com/google/uuid"
)
const (
DirectoryExists = "directory_exists"
)
type DirRequest struct {
allocationObj *Allocation
allocationID string
allocationTx string
remotePath string
blobbers []*blockchain.StorageNode
ctx context.Context
ctxCncl context.CancelFunc
wg *sync.WaitGroup
dirMask zboxutil.Uint128
mu *sync.Mutex
connectionID string
timestamp int64
alreadyExists map[uint64]bool
Consensus
}
func (req *DirRequest) ProcessWithBlobbers(a *Allocation) int {
var pos uint64
var existingDirCount int
countMu := &sync.Mutex{}
for i := req.dirMask; !i.Equals64(0); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) {
pos = uint64(i.TrailingZeros())
req.wg.Add(1)
go func(pos uint64) {
defer req.wg.Done()
err, alreadyExists := req.createDirInBlobber(a.Blobbers[pos], pos)
if err != nil {
l.Logger.Error(err.Error())
return
}
if alreadyExists {
countMu.Lock()
req.alreadyExists[pos] = true
existingDirCount++
countMu.Unlock()
}
}(pos)
}
req.wg.Wait()
return existingDirCount
}
func (req *DirRequest) ProcessDir(a *Allocation) error {
l.Logger.Info("Start creating dir for blobbers")
defer req.ctxCncl()
existingDirCount := req.ProcessWithBlobbers(a)
if !req.isConsensusOk() {
return errors.New("consensus_not_met", "directory creation failed due to consensus not met")
}
writeMarkerMU, err := CreateWriteMarkerMutex(client.GetClient(), a)
if err != nil {
return fmt.Errorf("directory creation failed. Err: %s", err.Error())
}
err = writeMarkerMU.Lock(
req.ctx, &req.dirMask, req.mu,
req.blobbers, &req.Consensus, existingDirCount, time.Minute, req.connectionID)
if err != nil {
return fmt.Errorf("directory creation failed. Err: %s", err.Error())
}
defer writeMarkerMU.Unlock(req.ctx, req.dirMask,
a.Blobbers, time.Minute, req.connectionID) //nolint: errcheck
return req.commitRequest(existingDirCount)
}
func (req *DirRequest) commitRequest(existingDirCount int) error {
req.Consensus.Reset()
req.timestamp = int64(common.Now())
req.consensus = existingDirCount
wg := &sync.WaitGroup{}
activeBlobbersNum := req.dirMask.CountOnes()
wg.Add(activeBlobbersNum)
commitReqs := make([]*CommitRequest, activeBlobbersNum)
var pos uint64
var c int
uid := util.GetNewUUID()
for i := req.dirMask; !i.Equals(zboxutil.NewUint128(0)); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) {
pos = uint64(i.TrailingZeros())
commitReq := &CommitRequest{}
commitReq.allocationID = req.allocationID
commitReq.allocationTx = req.allocationTx
commitReq.blobber = req.blobbers[pos]
newChange := &allocationchange.DirCreateChange{
RemotePath: req.remotePath,
Uuid: uid,
Timestamp: common.Timestamp(req.timestamp),
}
commitReq.changes = append(commitReq.changes, newChange)
commitReq.connectionID = req.connectionID
commitReq.wg = wg
commitReq.timestamp = req.timestamp
commitReqs[c] = commitReq
c++
go AddCommitRequest(commitReq)
}
wg.Wait()
for _, commitReq := range commitReqs {
if commitReq.result != nil {
if commitReq.result.Success {
l.Logger.Info("Commit success", commitReq.blobber.Baseurl)
req.Consensus.Done()
} else {
l.Logger.Info("Commit failed", commitReq.blobber.Baseurl, commitReq.result.ErrorMessage)
}
} else {
l.Logger.Info("Commit result not set", commitReq.blobber.Baseurl)
}
}
if !req.isConsensusOk() {
return errors.New("consensus_not_met", "directory creation failed due consensus not met")
}
return nil
}
func (req *DirRequest) createDirInBlobber(blobber *blockchain.StorageNode, pos uint64) (err error, alreadyExists bool) {
defer func() {
if err != nil {
req.mu.Lock()
req.dirMask = req.dirMask.And(zboxutil.NewUint128(1).Lsh(pos).Not())
req.mu.Unlock()
}
}()
body := new(bytes.Buffer)
formWriter := multipart.NewWriter(body)
err = formWriter.WriteField("connection_id", req.connectionID)
if err != nil {
return err, false
}
err = formWriter.WriteField("dir_path", req.remotePath)
if err != nil {
return err, false
}
formWriter.Close()
httpreq, err := zboxutil.NewCreateDirRequest(blobber.Baseurl, req.allocationID, req.allocationTx, body)
if err != nil {
l.Logger.Error(blobber.Baseurl, "Error creating dir request", err)
return err, false
}
httpreq.Header.Add("Content-Type", formWriter.FormDataContentType())
var (
resp *http.Response
shouldContinue bool
latestRespMsg string
latestStatusCode int
)
for i := 0; i < 3; i++ {
err, shouldContinue = func() (err error, shouldContinue bool) {
ctx, cncl := context.WithTimeout(req.ctx, (time.Second * 10))
resp, err = zboxutil.Client.Do(httpreq.WithContext(ctx))
cncl()
if err != nil {
return err, false
}
if resp.Body != nil {
defer resp.Body.Close()
}
var (
respBody []byte
msg string
)
if resp.StatusCode == http.StatusOK {
l.Logger.Info("Successfully created directory ", req.remotePath)
req.Consensus.Done()
return
}
if resp.StatusCode == http.StatusTooManyRequests {
var r int
r, err = zboxutil.GetRateLimitValue(resp)
if err != nil {
return
}
l.Logger.Debug(fmt.Sprintf("Got too many request error. Retrying after %d seconds", r))
time.Sleep(time.Duration(r) * time.Second)
shouldContinue = true
return
}
respBody, err = ioutil.ReadAll(resp.Body)
if err != nil {
l.Logger.Error(err)
return
}
latestRespMsg = string(respBody)
latestStatusCode = resp.StatusCode
msg = string(respBody)
l.Logger.Error(blobber.Baseurl, " Response: ", msg)
if strings.Contains(msg, DirectoryExists) {
req.Consensus.Done()
alreadyExists = true
return
}
err = errors.New("response_error", msg)
return
}()
if err != nil {
logger.Logger.Error(err)
return
}
if shouldContinue {
continue
}
return
}
return errors.New("dir_creation_failed",
fmt.Sprintf("Directory creation failed with latest status: %d and "+
"latest message: %s", latestStatusCode, latestRespMsg)), false
}
type DirOperation struct {
remotePath string
ctx context.Context
ctxCncl context.CancelFunc
dirMask zboxutil.Uint128
maskMU *sync.Mutex
alreadyExists map[uint64]bool
Consensus
}
func (dirOp *DirOperation) Process(allocObj *Allocation, connectionID string) ([]fileref.RefEntity, zboxutil.Uint128, error) {
refs := make([]fileref.RefEntity, len(allocObj.Blobbers))
dR := &DirRequest{
allocationID: allocObj.ID,
allocationTx: allocObj.Tx,
connectionID: connectionID,
blobbers: allocObj.Blobbers,
remotePath: dirOp.remotePath,
ctx: dirOp.ctx,
ctxCncl: dirOp.ctxCncl,
dirMask: dirOp.dirMask,
mu: dirOp.maskMU,
wg: &sync.WaitGroup{},
alreadyExists: make(map[uint64]bool),
}
dR.Consensus = Consensus{
RWMutex: &sync.RWMutex{},
consensusThresh: dR.consensusThresh,
fullconsensus: dR.fullconsensus,
}
_ = dR.ProcessWithBlobbers(allocObj)
dirOp.alreadyExists = dR.alreadyExists
if !dR.isConsensusOk() {
return nil, dR.dirMask, errors.New("consensus_not_met", "directory creation failed due to consensus not met")
}
return refs, dR.dirMask, nil
}
func (dirOp *DirOperation) buildChange(refs []fileref.RefEntity, uid uuid.UUID) []allocationchange.AllocationChange {
var pos uint64
changes := make([]allocationchange.AllocationChange, len(refs))
for i := dirOp.dirMask; !i.Equals(zboxutil.NewUint128(0)); i = i.And(zboxutil.NewUint128(1).Lsh(pos).Not()) {
pos = uint64(i.TrailingZeros())
if dirOp.alreadyExists[pos] {
newChange := &allocationchange.EmptyFileChange{}
changes[pos] = newChange
} else {
newChange := &allocationchange.DirCreateChange{
RemotePath: dirOp.remotePath,
Uuid: uid,
Timestamp: common.Now(),
}
changes[pos] = newChange
}
}
return changes
}
func (dirOp *DirOperation) Verify(a *Allocation) error {
if dirOp.remotePath == "" {
return errors.New("invalid_name", "Invalid name for dir")
}
if !path.IsAbs(dirOp.remotePath) {
return errors.New("invalid_path", "Path is not absolute")
}
return nil
}
func (dirOp *DirOperation) Completed(allocObj *Allocation) {
}
func (dirOp *DirOperation) Error(allocObj *Allocation, consensus int, err error) {
}
func NewDirOperation(remotePath string, dirMask zboxutil.Uint128, maskMU *sync.Mutex, consensusTh int, fullConsensus int, ctx context.Context) *DirOperation {
dirOp := &DirOperation{}
dirOp.remotePath = zboxutil.RemoteClean(remotePath)
dirOp.dirMask = dirMask
dirOp.maskMU = maskMU
dirOp.consensusThresh = consensusTh
dirOp.fullconsensus = fullConsensus
dirOp.ctx, dirOp.ctxCncl = context.WithCancel(ctx)
dirOp.alreadyExists = make(map[uint64]bool)
return dirOp
}