-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker_gen_file.go
132 lines (105 loc) · 2.26 KB
/
worker_gen_file.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
package main
import (
"fmt"
"os"
"path"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
)
const (
DeviceURandom = "/dev/urandom"
)
const (
ErrCreateFile = ErrCategoryFile + 1
ErrReadFile = ErrCategoryFile + 2
ErrWriteFile = ErrCategoryFile + 3
)
func genFiles(input GenFileParams) error {
chFids := make(chan int, 10000)
go func() {
for i := input.From; i < input.To; i++ {
chFids <- i
}
close(chFids)
}()
var countResultsWg sync.WaitGroup
countResultsWg.Add(1)
go countResults(&countResultsWg)
var wg sync.WaitGroup
wg.Add(p.Goroutines)
for i := 0; i < p.Goroutines; i++ {
go func() {
defer wg.Done()
rf, e := os.Open(DeviceURandom)
if e != nil {
logger.Error("open file err", zap.String("file", DeviceURandom), zap.String("err", e.Error()))
return
}
defer rf.Close()
buffer := make([]byte, 1024*1024)
for {
fid, ok := <-chFids
if !ok {
return
}
r := Result{
Fid: fid,
}
fp := path.Join(PathFiles, fmt.Sprintf("%d", fid))
fd, e := os.Create(fp)
if e != nil {
logger.Error("create file err", zap.String("file", fp), zap.String("err", e.Error()))
r.Ret = ErrCreateFile
r.Err = e
chResults <- r
continue
}
var currentSize, rn, wn int
if p.SyncConcurrency {
atomic.AddInt32(&concurrency, 1)
r.Concurrency = concurrency
} else {
r.Concurrency = int32(p.Goroutines)
}
r.S = time.Now()
for currentSize < input.Size {
rn, e = rf.Read(buffer[:])
if e != nil {
logger.Error("read file err", zap.String("err", e.Error()))
r.Ret = ErrReadFile
r.Err = e
chResults <- r
fd.Close()
break
}
wn, e = fd.Write(buffer[:rn])
if e != nil {
logger.Error("write file err", zap.String("err", e.Error()))
r.Ret = ErrWriteFile
r.Err = e
chResults <- r
fd.Close()
break
}
currentSize += wn
}
fd.Close()
r.E = time.Now()
if p.SyncConcurrency {
atomic.AddInt32(&concurrency, -1)
}
r.Latency = r.E.Sub(r.S).Microseconds()
chResults <- r
if p.Verbose {
logger.Debug("file generated", zap.String("file", fp))
}
}
}()
}
wg.Wait()
close(chResults)
countResultsWg.Wait()
return nil
}