-
Notifications
You must be signed in to change notification settings - Fork 1
/
V5.go
291 lines (249 loc) · 6 KB
/
V5.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
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"runtime/pprof"
"strconv"
"strings"
"sync"
"time"
)
var (
VERSION = 5
INPUT_FOLDER = "./data"
OUTPUT_FILE = "./output.txt"
DO_PROF = false
PROF_FILE = "./prof.dat"
PARSE_CUR = 1
BATCH_SIZE = 1
)
func main() {
// Parse arguments
flag.BoolVar(&DO_PROF, "prof", DO_PROF, "Enables profiling")
flag.IntVar(&PARSE_CUR, "c", PARSE_CUR, "Concurrency of data parsing")
flag.IntVar(&BATCH_SIZE, "b", BATCH_SIZE, "Channel batch size")
flag.Parse()
if len(os.Args) > 1 {
INPUT_FOLDER = os.Args[len(os.Args)-1]
}
fmt.Printf("Starting program V%d!\n", VERSION)
fmt.Printf("\t[Batch Size: %d, Parse Concurrency: %d]\n", BATCH_SIZE, PARSE_CUR)
// Set up profiling
if DO_PROF {
fmt.Println("\tProfiling enabled")
f, err := os.Create(PROF_FILE)
fail(err)
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
// Main body of work
processDataFolder(INPUT_FOLDER)
}
/*
Structure:
list() -filePaths-> read() -rawData-> parse() -parsedData-> aggregate() -processedData-> write()
*/
func processDataFolder(folder string) {
timer := time.Now()
var filePaths = make(chan string, 8) // Carries paths of input files
var rawData = make(chan []string, 64) // Carries raw input lines
var parsedData = make(chan []*Visit, 64) // Carries parsed Visit structs
var processedData = make(chan *Visit, 8) // Carries aggregated Visit structs
go list(folder, filePaths)
go read(filePaths, rawData)
var parseWG sync.WaitGroup
parseWG.Add(PARSE_CUR)
for i := 0; i < PARSE_CUR; i++ {
go func() {
defer parseWG.Done()
parse(rawData, parsedData)
}()
}
go func() {
parseWG.Wait()
close(parsedData)
}()
go aggregate(parsedData, processedData)
write(processedData)
fmt.Printf("Processing folder %s took %dms (%v)\n", folder, MillisecondsSince(timer), time.Since(timer))
}
/*
========== READ STEP ===========
*/
func list(folder string, filePaths chan string) {
defer close(filePaths)
var fileList []os.FileInfo
fileList, err := ioutil.ReadDir(folder)
fail(err)
for _, fileInfo := range fileList {
if !fileInfo.IsDir() {
filePaths <- folder + "/" + fileInfo.Name()
}
}
}
func read(filePaths chan string, out chan []string) {
defer close(out)
counter, timer := 0, time.Now()
var batch = make([]string, BATCH_SIZE)
var index int = 0
for filePath := range filePaths {
file, err := os.Open(filePath)
fail(err)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
batch[index] = scanner.Text() // Add data to the batch
index++
if index == BATCH_SIZE {
out <- batch // Send full batch on the channel
batch = make([]string, BATCH_SIZE)
index = 0
}
}
fail(scanner.Err())
file.Close()
counter++
}
if index > 0 {
out <- batch[:index] // Send final partial batch
}
fmt.Printf("\tRead %d files in %dms\n", counter, MillisecondsSince(timer))
}
/*
========== PARSE STEP ==========
Expected input format (tsv):
Date UserID IP OS Browser
*/
const INPUT_SEP = "\t"
const INPUT_FIELDS = 5
func parse(in chan []string, out chan []*Visit) {
counter, timer := 0, time.Now()
var inputBatch []string
var batch = make([]*Visit, BATCH_SIZE)
var index int = 0
for inputBatch = range in {
for _, line := range inputBatch {
parts := strings.Split(line, INPUT_SEP)
if len(parts) != INPUT_FIELDS {
fail(fmt.Errorf("Wrong number of fields in line: %s", line))
}
userID, err := strconv.ParseUint(parts[1], 10, 32)
fail(err)
doBusyWork() // Real parsing would take more computing than this
visit := NewVisit(uint32(userID), parts[2], parts[3], parts[4])
visit.MakeKey()
batch[index] = visit // Add data to the batch
index++
if index == BATCH_SIZE {
out <- batch // Send full batch on the channel
batch = make([]*Visit, BATCH_SIZE)
index = 0
}
counter++
}
}
if index > 0 {
out <- batch[:index] // Send final partial batch
}
fmt.Printf("\tParsed %d lines in %dms\n", counter, MillisecondsSince(timer))
}
/*
======== AGGREGATE STEP ========
*/
func aggregate(in chan []*Visit, out chan *Visit) {
defer close(out)
var inputBatch []*Visit
var hash = make(map[string]*Visit)
for inputBatch = range in {
for _, visit := range inputBatch {
var key string = visit.GetKey()
cachedVisit, exists := hash[key]
if exists {
cachedVisit.Count += visit.Count
} else {
hash[key] = visit
}
}
}
counter, timer := 0, time.Now()
for _, visit := range hash {
out <- visit
counter++
}
fmt.Printf("\tWrote %d lines in %dms\n", counter, MillisecondsSince(timer))
}
/*
========== WRITE STEP ==========
*/
func write(in chan *Visit) {
file, err := os.OpenFile(OUTPUT_FILE, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
fail(err)
for visit := range in {
fmt.Fprintf(file, "%s\n", visit)
}
}
/*
================================
======== DATA STRUCTURE ========
================================
*/
type Visit struct {
UserID uint32
IP string
OS string
Browser string
Count uint32
Key string
}
func NewVisit(userID uint32, IP, OS, Browser string) *Visit {
if userID > 0 {
IP, OS, Browser = "", "", ""
}
return &Visit{
UserID: userID,
IP: IP,
OS: OS,
Browser: Browser,
Count: 1,
}
}
func (v *Visit) String() string {
return fmt.Sprintf("%d\t%d\t%s\t%s\t%s", v.Count, v.UserID, v.IP, v.OS, v.Browser)
}
func (v *Visit) MakeKey() {
v.Key = fmt.Sprintf("%d\t%s\t%s\t%s", v.UserID, v.IP, v.OS, v.Browser)
}
func (v *Visit) GetKey() string {
if len(v.Key) == 0 {
v.MakeKey()
}
return v.Key
}
/*
================================
====== UTILITY FUNCTIONS =======
================================
*/
// Utility function for measuring time
func MillisecondsSince(t time.Time) int64 {
return int64(time.Since(t) / time.Millisecond)
}
// Utility function for error checking
func fail(err error) {
if err != nil {
panic(err.Error())
}
}
func doBusyWork() {
for i := 2; i < 50; i++ {
isPrime := true
for j := 2; j < i; j++ {
if i%j == 0 {
isPrime = false
}
}
_ = isPrime
}
}