forked from dgryski/dmrgo
/
emitter.go
108 lines (87 loc) · 2.19 KB
/
emitter.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
package dmrgo
// Logic for handling mapper and reducer output
// Copyright (c) 2011 Damian Gryski <damian@gryski.com>
// License: GPLv3 or, at your option, any later version
import (
"bufio"
"fmt"
"hash/adler32"
"net/url"
"os"
)
// Emitter emits key/value pairs
type Emitter interface {
Emit(reduceKey string, sortKey string, value string)
Flush()
}
type printEmitter struct {
w *bufio.Writer
}
func newPrintEmitter(w *bufio.Writer) *printEmitter {
e := new(printEmitter)
e.w = w
return e
}
func (e *printEmitter) Emit(reduceKey string, sortKey string, value string) {
e.w.WriteString(url.QueryEscape(reduceKey))
if sortKey != "" {
e.w.WriteString(",")
e.w.WriteString(url.QueryEscape(sortKey))
}
e.w.WriteByte('\t')
e.w.WriteString(value)
e.w.WriteByte('\n')
}
func (e *printEmitter) Flush() {
e.w.Flush()
}
type partitionEmitter struct {
partitions uint32
FileNames []string
fds []*os.File
emitters []Emitter
fileNameTemplate string
}
// data sink -- useful for benchmarking
type nullEmitter struct{}
func (*nullEmitter) Emit(key string, value string) { /* nothing */
}
func (*nullEmitter) Flush() { /* nothing */
}
func newPartitionEmitter(partitions uint, template string) *partitionEmitter {
pe := new(partitionEmitter)
pe.partitions = uint32(partitions)
pe.fileNameTemplate = template
pe.FileNames = make([]string, partitions)
pe.fds = make([]*os.File, partitions)
pe.emitters = make([]Emitter, partitions)
return pe
}
func (e *partitionEmitter) Emit(reduceKey string, sortKey string, value string) {
partition := uint32(0)
if e.partitions > 1 {
partition = adler32.Checksum([]byte(reduceKey)) % uint32(e.partitions)
}
if e.emitters[partition] == nil {
e.FileNames[partition] = fmt.Sprintf("%s.%04d", e.fileNameTemplate, partition)
fd, _ := os.Create(e.FileNames[partition])
e.fds[partition] = fd
w := bufio.NewWriter(fd)
e.emitters[partition] = newPrintEmitter(w)
}
e.emitters[partition].Emit(reduceKey, sortKey, value)
}
func (e *partitionEmitter) Flush() {
for _, w := range e.emitters {
if w != nil {
w.Flush()
}
}
}
func (e *partitionEmitter) Close() {
for _, w := range e.fds {
if w != nil {
w.Close()
}
}
}