-
Notifications
You must be signed in to change notification settings - Fork 0
/
mass_crc32c.go
258 lines (214 loc) · 7.03 KB
/
mass_crc32c.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
package main
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"errors"
"flag"
"fmt"
"hash/crc32"
"io"
"log"
"math"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"golang.org/x/text/language"
"golang.org/x/text/message"
) //import
type job struct {
path string
fileSize int64
} //job struct
type jobStat struct {
bytesProcessed int64
filesProcessed int64
}
var (
g_jobQueueChan chan job
g_crc32cTable *crc32.Table
)
func printErr(path string, err error) {
os.Stderr.WriteString("File Open error: '" + path + "' : " + err.Error() + "\n")
} //printErr()
func CRCReader(j job, buffer []byte, bufferSize int) (string, error) {
file, err := os.Open(j.path)
if err != nil {
return "", err
}
defer file.Close()
checksum := uint32(0)
processedSize := int64(0)
for {
switch n, err := file.Read(buffer); err {
case nil: // runs many times
if n == bufferSize {
processedSize += int64(bufferSize)
checksum = crc32.Update(checksum, g_crc32cTable, buffer)
} else {
processedSize += int64(n)
checksum = crc32.Update(checksum, g_crc32cTable, buffer[:n])
}
case io.EOF: // runs once
if j.fileSize != processedSize {
return "", errors.New("fileInfoSize != processedSize")
}
const checksumByteSize = crc32.Size
const checksumBase64Size = (checksumByteSize + 2) / 3 * 4
checksumBufferSlice := buffer[0:checksumByteSize]
encodedBufferSlice := buffer[checksumByteSize : checksumByteSize+checksumBase64Size]
binary.BigEndian.PutUint32(checksumBufferSlice, checksum)
base64.StdEncoding.Encode(encodedBufferSlice, checksumBufferSlice)
return string(encodedBufferSlice), nil
default: // should never run
return "ERROR!", err
} //switch
} //for
} //CRCReader()
func fileHandler(jobId int, bufferSizeKB int, jobStats []jobStat) error {
fileReadBufferSize := 1024 * bufferSizeKB
fileReadBuffer := make([]byte, fileReadBufferSize)
stdoutBuffer := bytes.Buffer{}
batchCounter := uint8(0) // batches of 256
localJobStat := jobStat{}
for j := range g_jobQueueChan { // consume the messages in the queue
crc, err := CRCReader(j, fileReadBuffer, fileReadBufferSize)
if err != nil {
printErr(j.path, err)
continue
}
batchCounter++
localJobStat.bytesProcessed += j.fileSize
stdoutBuffer.WriteString(crc + fmt.Sprintf(" %016x ", j.fileSize) + j.path + "\n")
if batchCounter == 0 { // byte wrap-around
os.Stdout.Write(stdoutBuffer.Bytes())
stdoutBuffer.Reset()
localJobStat.filesProcessed += (math.MaxUint8 + 1)
}
} //for
if batchCounter > 0 {
os.Stdout.Write(stdoutBuffer.Bytes())
localJobStat.filesProcessed += int64(batchCounter)
}
jobStats[jobId] = localJobStat
return nil
} //fileHandler()
// os.FileInfo is an interface
var enqueueJob filepath.WalkFunc = func(path string, info os.FileInfo, err error) error {
if err != nil {
nodeType := ""
if info != nil && info.IsDir() {
nodeType = "dir: "
} else {
nodeType = "file: "
}
os.Stderr.WriteString(nodeType + "error: '" + path + "': " + err.Error() + "\n")
return nil
}
if info.IsDir() {
//str := "entering dir: " + path + "\n"
//os.Stderr.Write(unsafe.Slice(unsafe.StringData(str), len(str)))
return nil
}
if !info.Mode().IsRegular() {
os.Stderr.WriteString("ignoring: " + path + "\n")
return nil
}
g_jobQueueChan <- job{path: path, fileSize: info.Size()} // add new file job to the queue (blocking when queue is full)
return nil
} //enqueueJob()
func init() {
g_crc32cTable = crc32.MakeTable(crc32.Castagnoli)
sanityCheck()
}
func sanityCheck() {
slice4 := make([]byte, 4)
func() {
const data = "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8" // sha512("Hello World!")
const expectedCorrectChecksum = "C7DdPQ=="
calculatedChecksum := crc32.Update(uint32(0), g_crc32cTable, []byte(data))
binary.BigEndian.PutUint32(slice4, calculatedChecksum)
calculatedChecksumBase64 := base64.StdEncoding.EncodeToString(slice4)
if expectedCorrectChecksum != calculatedChecksumBase64 {
fmt.Fprintf(os.Stderr, "Sanity Check #1 failed! [expected: %s, calculated: %s]. Terminating.\n",
expectedCorrectChecksum, calculatedChecksumBase64)
os.Exit(2)
}
}() // sanity check 1
func() {
const constantCRC32C = "0x48674bc7"
randomBytes := make([]byte, 64)
rand.Reader.Read(randomBytes)
calculatedChecksum := crc32.Update(uint32(0), g_crc32cTable, randomBytes)
binary.LittleEndian.PutUint32(slice4, calculatedChecksum)
calculatedChecksum = crc32.Update(calculatedChecksum, g_crc32cTable, slice4)
calculatedChecksumHex := fmt.Sprintf("%#x", calculatedChecksum)
if calculatedChecksumHex != constantCRC32C {
fmt.Fprintf(os.Stderr, "Sanity Check #2 failed! [expected: %s, calculated %s]. Terminating.\n",
constantCRC32C, calculatedChecksumHex)
os.Exit(2)
}
}() // sanity check 2
} //sanityCheck()
func printUsage() {
fmt.Fprintf(os.Stderr, "Usage of %s: [options] path [path ...]\n\nOptions:\n", os.Args[0])
flag.PrintDefaults()
} //printUsage()
func main() {
var cpuCount int
var workerCount int
var bufferSizeKB int
var listAheadSize int
const DEFAULT_BUFFER_SIZE_KB = 1024
numCPU := runtime.NumCPU()
flag.IntVar(&cpuCount, "p", numCPU, "# of cpu used")
flag.IntVar(&workerCount, "j", numCPU*4, "# of parallel reads")
flag.IntVar(&listAheadSize, "l", workerCount, "size of list ahead queue")
flag.IntVar(&bufferSizeKB, "s", DEFAULT_BUFFER_SIZE_KB, "size of reads in kbytes")
flag.Usage = printUsage
flag.Parse()
if flag.NArg() == 0 {
fmt.Fprintln(os.Stderr, "error: missing paths")
printUsage()
os.Exit(1)
}
printFlags := func() {
fmt.Fprintf(os.Stderr, "Flags: [p=%d j=%d l=%d s=%d]\n", cpuCount, workerCount, listAheadSize, bufferSizeKB)
}
runtime.GOMAXPROCS(cpuCount) // limit number of kernel threads (CPUs used)
g_jobQueueChan = make(chan job, listAheadSize) // use a channel with a size to limit the number of list ahead path
jobStats := make([]jobStat, workerCount)
waitGroup := sync.WaitGroup{}
start := time.Now()
// create the fileHandler worker goroutines
waitGroup.Add(workerCount)
for jobId := 0; jobId < workerCount; jobId++ {
go func(jobId int) {
defer waitGroup.Done()
fileHandler(jobId, bufferSizeKB, jobStats)
}(jobId)
}
// enqueue jobs
for _, arg := range flag.Args() {
err := filepath.Walk(arg, enqueueJob)
if err != nil {
log.Fatal(err)
}
} //for
close(g_jobQueueChan) // safe to close, since all jobs have already been channel-received by now
waitGroup.Wait()
duration := time.Since(start)
var totalFilesProcessed, totalBytesProcessed int64
for _, item := range jobStats {
totalFilesProcessed += item.filesProcessed
totalBytesProcessed += item.bytesProcessed
}
var mbPerSecond float64 = (float64(totalBytesProcessed) / (1024 * 1024)) / duration.Seconds()
printer := message.NewPrinter(language.English)
printFlags()
printer.Fprintf(os.Stderr, "[Duration: %v] [Files processed: %v] [Bytes processed: %v] [%.2f MiB/second]\n",
duration, totalFilesProcessed, totalBytesProcessed, mbPerSecond)
} //main()