-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorter.go
302 lines (258 loc) · 6.95 KB
/
sorter.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
package datachan
import (
"bufio"
"container/heap"
"encoding/gob"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"reflect"
"sort"
"sync"
)
// Sort sorts the output of the previous stage in ascending order,
// using keyer to extract the sorting Key.
//
// Keyer must be a function like func(T)Comparable, where the output
// is a comparable type (int, uint, float, string).
//
// If the number of records is less than MaxBeforeSpill this stage
// works from memory. Otherwise it spills its contents to disk, and
// later uses merge sort to sort the whole data.
func (s *Stage) Sort(MaxBeforeSpill int, keyer T) *Stage {
keyFun := reflect.ValueOf(keyer)
if keyFun.Kind() != reflect.Func {
panic("Reduce Keyer argument must be a function")
}
if keyFun.Type().NumIn() != 1 {
panic("Reduce function output must support method Key(T)Comparable")
}
if !keyFun.Type().Out(0).Comparable() {
panic("Reduce function output must support method Key(T)Comparable")
}
if keyFun.Type().NumOut() != 1 {
panic("Reduce function output must support method Key(T)Comparable")
}
output := reflect.MakeChan(s.output.Type(), MaxBeforeSpill)
readersChan := make(chan interface{}, 16)
filesWG := sync.WaitGroup{}
var executor func()
executor = func() {
// Process and accumulate all the inputs in batches
accArr := make([]*keyValuePair, 0, MaxBeforeSpill)
for e, ok := s.output.Recv(); ok; e, ok = s.output.Recv() {
eKey := keyFun.Call([]reflect.Value{e})[0]
pv := keyValuePairPool.Get().(*keyValuePair)
pv.Key = eKey.Interface()
pv.Value = e.Interface()
accArr = append(accArr, pv)
// Spill if too much records are on memory
if len(accArr) >= MaxBeforeSpill {
sort.Sort(sortByKey(accArr))
readersChan <- spillKeyValuePairToDisk(accArr)
filesWG.Add(1)
go executor()
filesWG.Done()
return
}
}
sort.Sort(sortByKey(accArr))
readersChan <- readKeyValuePairFromMemory(accArr)
filesWG.Done()
}
var sortMerger func()
sortMerger = func() {
kvProviders := make([]<-chan *keyValuePair, 0)
kvProvidersFiles := make([]string, 0)
for kvProvider := range readersChan {
switch kvProvider.(type) {
case string:
kvProvidersFiles = append(kvProvidersFiles, kvProvider.(string))
case <-chan *keyValuePair:
kvProviders = append(kvProviders, kvProvider.(<-chan *keyValuePair))
}
}
for _, kvProvider := range kvProvidersFiles {
kvProviders = append(kvProviders, readKeyValuePairFromDisk(kvProvider))
}
// Generate the priority queue and fill it
pq := make(kvPairPriorityQueue, 0, len(readersChan))
for _, ch := range kvProviders {
chValue, ok := <-ch
if ok {
pq = append(pq, &kvMerge{
value: chValue,
src: ch,
})
}
}
heap.Init(&pq)
for pq.Len() > 0 {
item := pq.PopAndRefill()
output.Send(reflect.ValueOf(item.Value))
}
output.Close()
}
filesWG.Add(1)
go executor()
go func() {
filesWG.Wait()
close(readersChan)
}()
go sortMerger()
return &Stage{output}
}
func (p *keyValuePair) keyEquals(q *keyValuePair) bool {
a := p.Key
b := q.Key
switch a.(type) {
case string:
return a.(string) == b.(string)
case int:
return a.(int) == b.(int)
case uint:
return a.(uint) == b.(uint)
case float64:
return a.(float64) == b.(float64)
case float32:
return a.(float32) == b.(float32)
default:
panic(fmt.Sprint("Type is not sortable: only String, Int, Uint and Float are allowed, given: ",
a, " and ", b,
" (", reflect.TypeOf(a), ")"))
}
}
func (p *keyValuePair) less(q *keyValuePair) bool {
a := p.Key
b := q.Key
switch a.(type) {
case string:
return a.(string) < b.(string)
case int:
return a.(int) < b.(int)
case uint:
return a.(uint) < b.(uint)
case float64:
return a.(float64) < b.(float64)
case float32:
return a.(float32) < b.(float32)
default:
panic(fmt.Sprint("Type is not sortable: only String, Int, Uint and Float are allowed, given: ",
a, " and ", b,
" (", reflect.TypeOf(a), ")"))
}
}
type sortByKey []*keyValuePair
func (s sortByKey) Len() int { return len(s) }
func (s sortByKey) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortByKey) Less(i, j int) bool {
return s[i].less(s[j])
}
func spillKeyValuePairToDisk(arr []*keyValuePair) string {
tmpfile, err := ioutil.TempFile("", "datachan_partial")
if err != nil {
log.Fatal(err)
}
defer tmpfile.Close()
bufTmp := bufio.NewWriter(tmpfile)
defer bufTmp.Flush()
enc := gob.NewEncoder(bufTmp)
for k, v := range arr {
err := enc.Encode(v)
keyValuePairPool.Put(v)
arr[k] = nil
if err != nil {
panic(fmt.Sprint("Unable to encode", v, ":", err))
}
}
return tmpfile.Name()
}
func readKeyValuePairFromDisk(file string) <-chan *keyValuePair {
// The buffer value was selected testing with a Word Count program
output := make(chan *keyValuePair, 1)
go func() {
defer os.Remove(file)
fd, err := os.Open(file)
if err != nil {
log.Fatalln(err)
}
defer fd.Close()
buf := bufio.NewReader(fd)
dec := gob.NewDecoder(buf)
more := true
for more {
data := keyValuePairPool.Get().(*keyValuePair)
err := dec.Decode(data)
if err != nil && err != io.EOF {
log.Fatal(err)
} else if err == io.EOF {
more = false
close(output)
} else {
output <- data
}
}
}()
return output
}
func readKeyValuePairFromMemory(arr []*keyValuePair) <-chan *keyValuePair {
output := make(chan *keyValuePair)
go func() {
for k, v := range arr {
output <- v
arr[k] = nil
}
close(output)
}()
return output
}
func (s *Stage) Top(N int, keyer T) *Stage {
keyFun := reflect.ValueOf(keyer)
if keyFun.Kind() != reflect.Func {
panic("Reduce Keyer argument must be a function")
}
if keyFun.Type().NumIn() != 1 {
panic("Reduce function output must support method Key(T)Comparable")
}
if !keyFun.Type().Out(0).Comparable() {
panic("Reduce function output must support method Key(T)Comparable")
}
if keyFun.Type().NumOut() != 1 {
panic("Reduce function output must support method Key(T)Comparable")
}
output := reflect.MakeChan(s.output.Type(), N)
var executor func()
executor = func() {
// Process and accumulate all the inputs in batches
pq := make(TopKeyValuePriorityQueue, 0, N)
heap.Init(&pq)
for e, ok := s.output.Recv(); ok; e, ok = s.output.Recv() {
eKey := keyFun.Call([]reflect.Value{e})[0]
pv := keyValuePairPool.Get().(*keyValuePair)
pv.Key = eKey.Interface()
pv.Value = e.Interface()
node := TopkeyValuePriorityQueueNodePool.Get().(*TopkeyValuePriorityQueueNode)
node.value = pv
heap.Push(&pq, node)
for pq.Len() > N {
node = heap.Pop(&pq).(*TopkeyValuePriorityQueueNode)
node.value.Value = nil
node.value.Key = nil
keyValuePairPool.Put(node.value)
node.value = nil
TopkeyValuePriorityQueueNodePool.Put(node)
}
}
for pq.Len() > 0 {
node := heap.Pop(&pq).(*TopkeyValuePriorityQueueNode)
output.Send(reflect.ValueOf(node.value.Value))
keyValuePairPool.Put(node.value)
TopkeyValuePriorityQueueNodePool.Put(node)
}
output.Close()
}
go executor()
return &Stage{output}
}