-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathrdd.go
694 lines (627 loc) · 19.6 KB
/
rdd.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
package gopark
import (
"fmt"
"io"
"log"
"os"
"sort"
)
type MapperFunc func(interface{}) interface{}
type PartitionMapperFunc func(Yielder) Yielder
type FlatMapperFunc func(interface{}) []interface{}
type ReducerFunc func(interface{}, interface{}) interface{}
type FilterFunc func(interface{}) bool
type LoopFunc func(interface{})
type RDD interface {
Map(f MapperFunc) RDD
MapPartition(f PartitionMapperFunc) RDD
FlatMap(f FlatMapperFunc) RDD
Filter(f FilterFunc) RDD
Sample(fraction float64, seed int64, withReplacement bool) RDD
GroupByKey() RDD
SortByKey(fn KeyLessFunc, reverse bool) RDD
SortByValue(fn KeyLessFunc, reverse bool) RDD
PartitionByKey() RDD
ReduceByKey(fn ReducerFunc) RDD
Distinct() RDD
Union(other RDD) RDD
Join(other RDD) RDD
LeftOuterJoin(other RDD) RDD
RightOuterJoin(other RDD) RDD
GroupWith(other RDD) RDD
Cartesian(other RDD) RDD
GroupByKey_N(numPartitions int) RDD
SortByKey_N(fn KeyLessFunc, reverse bool, numPartitions int) RDD
SortByValue_N(fn KeyLessFunc, reverse bool, numPartitions int) RDD
PartitionByKey_N(numPartitions int) RDD
ReduceByKey_N(fn ReducerFunc, numPartitions int) RDD
Distinct_N(numPartitions int) RDD
Join_N(other RDD, numPartitions int) RDD
LeftOuterJoin_N(other RDD, numPartitions int) RDD
RightOuterJoin_N(other RDD, numPartitions int) RDD
GroupWith_N(other RDD, numPartitions int) RDD
Reduce(fn ReducerFunc) interface{}
CountByKey() map[interface{}]int64
CountByValue() map[interface{}]int64
Take(n int64) []interface{}
Collect() []interface{}
CollectAsMap() map[interface{}]interface{}
Count() int64
Foreach(fn LoopFunc)
Foreach0(fn LoopFunc)
SaveAsTextFile(pathname string)
Cache() RDD
Persist() RDD
getId() int64
getContext() *Context
getSplits() []Split
getSplit(int) Split
len() int
traverse(split Split) Yielder
compute(split Split) Yielder
}
type Split interface {
getIndex() int
}
type _BaseRDD struct {
ctx *Context
prototype RDD
id int64
splits []Split
shouldCache bool
cache [][]interface{}
shouldPersist bool
persistLocation string
length int
}
//////////////////////////////////////////////////////
// Base RDD operations implementation
//////////////////////////////////////////////////////
func (r *_BaseRDD) Cache() RDD {
if !r.shouldCache {
r.shouldCache = true
r.cache = make([][]interface{}, r.length)
}
return r.prototype
}
func (r *_BaseRDD) Persist() RDD {
if !r.shouldPersist {
r.shouldPersist = true
}
return r.prototype
}
func (r *_BaseRDD) Union(other RDD) RDD {
rdds := []RDD{r.prototype, other}[:]
return newUnionRDD(r.ctx, rdds)
}
func (r *_BaseRDD) Join(other RDD) RDD {
return r.Join_N(other, 0)
}
func (r *_BaseRDD) Join_N(other RDD, numPartitions int) RDD {
return r.join(other, numPartitions, true, true)
}
func (r *_BaseRDD) LeftOuterJoin(other RDD) RDD {
return r.LeftOuterJoin_N(other, 0)
}
func (r *_BaseRDD) LeftOuterJoin_N(other RDD, numPartitions int) RDD {
return r.join(other, numPartitions, true, false)
}
func (r *_BaseRDD) RightOuterJoin(other RDD) RDD {
return r.RightOuterJoin_N(other, 0)
}
func (r *_BaseRDD) RightOuterJoin_N(other RDD, numPartitions int) RDD {
return r.join(other, numPartitions, false, true)
}
func (r *_BaseRDD) join(other RDD, numPartitions int, needLeft, needRight bool) RDD {
return r.GroupWith_N(other, numPartitions).FlatMap(func(x interface{}) []interface{} {
keyGroups := x.(*KeyGroups)
groups := keyGroups.Groups
if needLeft && len(groups[0]) == 0 {
return nil
}
if needRight && len(groups[1]) == 0 {
return nil
}
results := make([]interface{}, 0)
if len(groups[0]) == 0 {
groups[0] = append(groups[0], nil)
}
if len(groups[1]) == 0 {
groups[1] = append(groups[1], nil)
}
for _, leftValue := range groups[0] {
for _, rightValue := range groups[1] {
results = append(results, &KeyValue{
Key: keyGroups.Key,
Value: []interface{}{leftValue, rightValue}[:],
})
}
}
return results
})
}
func (r *_BaseRDD) GroupWith(other RDD) RDD {
return r.GroupWith_N(other, 0)
}
func (r *_BaseRDD) GroupWith_N(other RDD, numPartitions int) RDD {
if numPartitions <= 0 {
switch {
case env.parallel == 0:
numPartitions = r.len()
default:
numPartitions = env.parallel
}
}
rdds := []RDD{r.prototype, other}[:]
return newCoGroupedRDD(r.ctx, rdds, numPartitions)
}
func (r *_BaseRDD) SortByKey(fn KeyLessFunc, reverse bool) RDD {
return r.SortByKey_N(fn, reverse, 0)
}
func (r *_BaseRDD) SortByKey_N(fn KeyLessFunc, reverse bool, numPartitions int) RDD {
if numPartitions <= 0 {
switch {
case env.parallel == 0:
numPartitions = r.len()
default:
numPartitions = env.parallel
}
}
sortMapper := func(list []interface{}) []interface{} {
sorter := NewParkSorter(list, func(x, y interface{}) bool {
return fn(x.(*KeyValue).Key, y.(*KeyValue).Key)
})
if !reverse {
sort.Sort(sorter)
} else {
sort.Sort(sort.Reverse(sorter))
}
return list
}
goSortMapper := func(iter Yielder) Yielder {
yield := make(chan interface{}, 1)
go func() {
values := make([]interface{}, 0)
for value := range iter {
values = append(values, value)
}
sorted := sortMapper(values)
for _, value := range sorted {
yield <- value
}
close(yield)
}()
return yield
}
if r.len() == 1 {
return r.MapPartition(goSortMapper)
}
// we choose some sample records as the key to partition results
n := numPartitions * 10 / r.len()
samples := r.MapPartition(func(iter Yielder) Yielder {
yield := make(chan interface{}, 1)
go func() {
index := 0
for value := range iter {
yield <- value
index++
if index >= n {
break
}
}
close(yield)
}()
return yield
}).Collect()
samples = sortMapper(samples)
keys := make([]interface{}, 0)
for i := 0; i < numPartitions-1; i++ {
if i*10+5 >= len(samples) {
break
}
keys = append(keys, samples[i*10+5].(*KeyValue).Key)
}
partitioner := newRangePartitioner(fn, keys, reverse)
aggregator := newMergeAggregator()
shuffleRdd := newShuffledRDD(r.prototype, aggregator, partitioner)
return shuffleRdd.FlatMap(func(x interface{}) []interface{} {
keyValue := x.(*KeyValue)
values := keyValue.Value.([]interface{})
results := make([]interface{}, len(values))
for i := range values {
results[i] = &KeyValue{
Key: keyValue.Key,
Value: values[i],
}
}
return results
}).MapPartition(goSortMapper)
}
func (r *_BaseRDD) SortByValue(fn KeyLessFunc, reverse bool) RDD {
return r.SortByValue_N(fn, reverse, 0)
}
func (r *_BaseRDD) SortByValue_N(fn KeyLessFunc, reverse bool, numPartitions int) RDD {
return r.Map(func(x interface{}) interface{} {
kv := x.(*KeyValue)
return &KeyValue{kv.Value, kv.Key}
}).SortByKey_N(fn, reverse, numPartitions).Map(func(x interface{}) interface{} {
kv := x.(*KeyValue)
kv.Key, kv.Value = kv.Value, kv.Key
return kv
})
}
func (r *_BaseRDD) Cartesian(other RDD) RDD {
return newCartesianRDD(r.ctx, r.prototype, other)
}
func (r *_BaseRDD) Distinct() RDD {
return r.Distinct_N(0)
}
func (r *_BaseRDD) Distinct_N(numPartitions int) RDD {
d := r.Map(func(arg interface{}) interface{} {
return &KeyValue{arg, nil}
}).ReduceByKey_N(func(x, y interface{}) interface{} {
return nil
}, numPartitions).Map(func(arg interface{}) interface{} {
return arg.(*KeyValue).Key
})
return d
}
func (r *_BaseRDD) ReduceByKey(fn ReducerFunc) RDD {
return r.ReduceByKey_N(fn, 0)
}
func (r *_BaseRDD) ReduceByKey_N(fn ReducerFunc, numPartitions int) RDD {
combinerCreator := func(x interface{}) []interface{} {
y := []interface{}{x}[:]
return y
}
combinderMerger := func(x, y []interface{}) []interface{} {
x[0] = fn(x[0], y[0])
return x
}
valueMerger := func(x []interface{}, y interface{}) []interface{} {
x[0] = fn(x[0], y)
return x
}
aggregator := &_Aggregator{combinerCreator, combinderMerger, valueMerger}
return r.combineByKey(aggregator, numPartitions).Map(func(x interface{}) interface{} {
keyValue := x.(*KeyValue)
return &KeyValue{keyValue.Key, keyValue.Value.([]interface{})[0]}
})
}
func (r *_BaseRDD) PartitionByKey() RDD {
return r.PartitionByKey_N(0)
}
func (r *_BaseRDD) PartitionByKey_N(numPartitions int) RDD {
return r.GroupByKey_N(numPartitions).Map(func(arg interface{}) interface{} {
keyValue := arg.(*KeyValue)
values := keyValue.Value.([]interface{})
results := make([]interface{}, len(values))
for i := range values {
results[i] = &KeyValue{keyValue.Key, values[i]}
}
return results
}).FlatMap(func(arg interface{}) []interface{} {
return arg.([]interface{})
})
}
func (r *_BaseRDD) GroupByKey() RDD {
return r.GroupByKey_N(0)
}
func (r *_BaseRDD) GroupByKey_N(numPartitions int) RDD {
aggregator := newMergeAggregator()
return r.combineByKey(aggregator, numPartitions)
}
func (r *_BaseRDD) Map(f MapperFunc) RDD {
return newMappedRDD(r.prototype, f)
}
func (r *_BaseRDD) MapPartition(f PartitionMapperFunc) RDD {
return newPartitionMappedRDD(r.prototype, f)
}
func (r *_BaseRDD) FlatMap(f FlatMapperFunc) RDD {
return newFlatMappedRDD(r.prototype, f)
}
func (r *_BaseRDD) Filter(f FilterFunc) RDD {
return newFilteredRDD(r.prototype, f)
}
func (r *_BaseRDD) Sample(fraction float64, seed int64, withReplacement bool) RDD {
return newSampledRDD(r.prototype, fraction, seed, withReplacement)
}
func (r *_BaseRDD) CountByKey() map[interface{}]int64 {
return r.Map(func(arg interface{}) interface{} {
return arg.(*KeyValue).Key
}).CountByValue()
}
func (r *_BaseRDD) CountByValue() map[interface{}]int64 {
parklog("<CountByValue> %s", r.prototype)
iters := r.ctx.runRoutine(r.prototype, nil, func(yield Yielder, partition int) interface{} {
cnts := make(map[interface{}]int64)
for value := range yield {
if _, ok := cnts[value]; ok {
cnts[value]++
} else {
cnts[value] = 1
}
}
return cnts
})
cnts := make(map[interface{}]int64)
for _, iter := range iters {
for value := range iter {
for key, cnt := range value.(map[interface{}]int64) {
if _, ok := cnts[key]; ok {
cnts[key] += cnt
} else {
cnts[key] = cnt
}
}
}
}
return cnts
}
func (r *_BaseRDD) Reduce(fn ReducerFunc) interface{} {
parklog("<Reduce> %s", r.prototype)
iters := r.ctx.runRoutine(r.prototype, nil, func(yield Yielder, partition int) interface{} {
var accu interface{} = nil
for value := range yield {
switch {
case accu == nil:
accu = value
default:
accu = fn(accu, value)
}
}
return accu
})
var accu interface{} = nil
for _, iter := range iters {
for value := range iter {
if value != nil {
switch {
case accu == nil:
accu = value
default:
accu = fn(accu, value)
}
}
}
}
return accu
}
func (r *_BaseRDD) SaveAsTextFile(pathname string) {
newOutputTextFileRDD(r.prototype, pathname).Collect()
}
func (r *_BaseRDD) Collect() []interface{} {
parklog("<Collect> %s", r.prototype)
iters := r.ctx.runRoutine(r.prototype, nil, func(yield Yielder, partition int) interface{} {
subCollections := make([]interface{}, 0)
for value := range yield {
subCollections = append(subCollections, value)
}
return subCollections
})
collections := make([]interface{}, 0)
for _, iter := range iters {
subCollections := (<-iter).([]interface{})
collections = append(collections, subCollections...)
}
return collections
}
func (r *_BaseRDD) CollectAsMap() map[interface{}]interface{} {
parklog("<CollectAsMap> %s", r.prototype)
collections := r.Collect()
sets := make(map[interface{}]interface{})
for _, item := range collections {
keyValue := item.(*KeyValue)
sets[keyValue.Key] = keyValue.Value
}
return sets
}
func (r *_BaseRDD) Foreach0(fn LoopFunc) {
parklog("<Foreach0> %s", r.prototype)
for i := 0; i < r.prototype.len(); i++ {
dumps := r.ctx.runRoutine(r.prototype, []int{i}[:], func(yield Yielder, partition int) interface{} {
for value := range yield {
fn(value)
}
return struct{}{}
})
// we need to dump all the channels otherwise the function will not be executed.
for _, dump := range dumps {
for _ = range dump {
}
}
}
}
func (r *_BaseRDD) Foreach(fn LoopFunc) {
parklog("<Foreach> %s", r.prototype)
dumps := r.ctx.runRoutine(r.prototype, nil, func(yield Yielder, partition int) interface{} {
for value := range yield {
fn(value)
}
return struct{}{}
})
// we need to dump all the channels otherwise the function will not be executed.
for _, dump := range dumps {
for _ = range dump {
}
}
}
func (r *_BaseRDD) Count() int64 {
parklog("<Count> %s", r.prototype)
var cnt int64 = 0
iters := r.ctx.runRoutine(r.prototype, nil, func(yield Yielder, partition int) interface{} {
var total int64 = 0
for _ = range yield {
total++
}
return total
})
for _, iter := range iters {
for subCount := range iter {
cnt += subCount.(int64)
}
}
return cnt
}
func (r *_BaseRDD) Take(n int64) []interface{} {
if n < 0 {
return nil
}
parklog("<Take>=%d %s", n, r.prototype)
results := make([]interface{}, n)
var index int64 = 0
p := make([]int, 1)
p[0] = 0
for index < n && p[0] < r.prototype.len() {
if y := r.ctx.runRoutine(r.prototype, p, func(yield Yielder, partition int) interface{} {
s := make([]interface{}, n-index)
var i int64 = 0
for ; i < n-index; i++ {
if value, ok := <-yield; ok {
s[i] = value
} else {
break
}
}
return s[:i]
}); len(y) > 0 {
for taked := range y[0] {
takedSlice := taked.([]interface{})
copy(results[index:], takedSlice)
index += int64(len(takedSlice))
}
}
p[0]++
}
return results
}
func (r *_BaseRDD) combineByKey(aggregator *_Aggregator, numPartitions int) RDD {
if numPartitions <= 0 {
switch {
case env.parallel == 0:
numPartitions = r.len()
default:
numPartitions = env.parallel
}
}
patitioner := newHashPartitioner(numPartitions)
return newShuffledRDD(r.prototype, aggregator, patitioner)
}
func (r *_BaseRDD) getOrCompute(split Split) Yielder {
rdd := r.prototype
i := split.getIndex()
yield := make(chan interface{}, 1)
go func() {
if r.cache[i] != nil {
parklog("Cache hit <%s> on Split[%d]", rdd, i)
for _, value := range r.cache[i] {
yield <- value
}
} else {
r.cache[i] = make([]interface{}, 0)
for value := range rdd.compute(split) {
r.cache[i] = append(r.cache[i], value)
yield <- value
}
r.cache[i] = r.cache[i][:]
}
close(yield)
}()
return yield
}
func (r *_BaseRDD) persistOrCompute(split Split) Yielder {
rdd := r.prototype
i := split.getIndex()
yield := make(chan interface{}, 1)
go func() {
if len(r.persistLocation) != 0 {
pathname := env.getLocalRDDPath(r.id, i)
parklog("Decoding rdd-%d/%d[GOB] from local file %s", r.id, i, pathname)
input, err := os.Open(pathname)
if err != nil {
log.Panicf("Error when persist/decode rdd split[%d], %v", i, err)
}
defer input.Close()
var buffer []interface{}
encoder := NewBufferEncoder(ENCODE_BUFFER_SIZE)
for err == nil {
buffer, err = encoder.Decode(input)
if err != nil {
break
}
for _, value := range buffer {
yield <- value
}
}
if err != nil && err != io.EOF {
log.Panicf("Error when persist/decode rdd split[%d], %v", i, err)
}
} else {
pathname := env.getLocalRDDPath(r.id, i)
output, err := os.Create(pathname)
if err != nil {
log.Panicf("Error when creating presist file [%s] for rdd split[%d], %v", pathname, i, err)
}
defer output.Close()
encoder := NewBufferEncoder(ENCODE_BUFFER_SIZE)
for value := range rdd.compute(split) {
err = encoder.Encode(output, value)
if err != nil {
log.Panicf("Error when encoding object into file for rdd split[%d], %v", i, err)
}
yield <- value
}
err = encoder.Flush(output)
if err != nil {
log.Panicf("Error when encoding object into file for rdd split[%d], %v", i, err)
}
parklog("Encoding rdd-%d/%d[GOB] into local file %s", r.id, i, pathname)
r.persistLocation = pathname
}
close(yield)
}()
return yield
}
func (r *_BaseRDD) traverse(split Split) Yielder {
rdd := r.prototype
if r.shouldCache {
return r.getOrCompute(split)
}
if r.shouldPersist {
return r.persistOrCompute(split)
}
return rdd.compute(split)
}
func (r *_BaseRDD) getId() int64 {
return r.id
}
func (r *_BaseRDD) getContext() *Context {
return r.ctx
}
func (r *_BaseRDD) getSplits() []Split {
return r.splits
}
func (r *_BaseRDD) getSplit(index int) Split {
return r.splits[index]
}
func (r *_BaseRDD) len() int {
return r.length
}
func (r *_BaseRDD) init(ctx *Context, prototype RDD) {
r.ctx = ctx
r.prototype = prototype
r.id = r.newRddId()
r.splits = make([]Split, 0)
r.ctx.init()
}
var nextRddId AtomicInt = 0
func (r *_BaseRDD) newRddId() int64 {
nextRddId.Add(1)
return nextRddId.Get()
}
var nextShuffleId AtomicInt = 0
func (r *_BaseRDD) newShuffleId() int64 {
nextShuffleId.Add(1)
return nextShuffleId.Get()
}
var _ = fmt.Println