forked from twitter/scalding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Operations.scala
371 lines (314 loc) · 12.5 KB
/
Operations.scala
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
/*
Copyright 2012 Twitter, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.twitter.scalding {
import cascading.operation._
import cascading.tuple._
import cascading.flow._
import cascading.pipe.assembly.AggregateBy
import cascading.pipe._
import scala.collection.JavaConverters._
import org.apache.hadoop.conf.Configuration
import com.esotericsoftware.kryo.Kryo;
import com.twitter.chill.ClosureCleaner
object CascadingUtils {
def flowProcessToConfiguration(fp : FlowProcess[_]) : Configuration = {
val confCopy = fp.asInstanceOf[FlowProcess[AnyRef]].getConfigCopy
if (confCopy.isInstanceOf[Configuration]) {
confCopy.asInstanceOf[Configuration]
}
else {
// For local mode, we don't have a hadoop configuration
val conf = new Configuration()
fp.getPropertyKeys.asScala.foreach { key =>
conf.set(key, fp.getStringProperty(key))
}
conf
}
}
def kryoFor(fp : FlowProcess[_]) : Kryo = {
(new cascading.kryo.KryoSerialization(flowProcessToConfiguration(fp)))
.populatedKryo
}
}
import CascadingUtils.kryoFor
class FlatMapFunction[S,T](fn : S => Iterable[T], fields : Fields,
conv : TupleConverter[S], set : TupleSetter[T])
extends BaseOperation[Any](fields) with Function[Any] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fn)
def operate(flowProcess : FlowProcess[_], functionCall : FunctionCall[Any]) {
fn(conv(functionCall.getArguments)).foreach { arg : T =>
val this_tup = set(arg)
functionCall.getOutputCollector.add(this_tup)
}
}
}
class MapFunction[S,T](fn : S => T, fields : Fields,
conv : TupleConverter[S], set : TupleSetter[T])
extends BaseOperation[Any](fields) with Function[Any] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fn)
def operate(flowProcess : FlowProcess[_], functionCall : FunctionCall[Any]) {
val res = fn(conv(functionCall.getArguments))
functionCall.getOutputCollector.add(set(res))
}
}
/*
* BaseOperation with support for context
*/
abstract class SideEffectBaseOperation[C] (
bf: => C, // begin function returns a context
ef: C => Unit, // end function to clean up context object
fields: Fields
) extends BaseOperation[C](fields) {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(ef)
override def prepare(flowProcess: FlowProcess[_], operationCall: OperationCall[C]) {
operationCall.setContext(bf)
}
override def cleanup(flowProcess: FlowProcess[_], operationCall: OperationCall[C]) {
ef(operationCall.getContext)
}
}
/*
* A map function that allows state object to be set up and tear down.
*/
class SideEffectMapFunction[S, C, T] (
bf: => C, // begin function returns a context
fn: (C, S) => T, // function that takes a context and a tuple and generate a new tuple
ef: C => Unit, // end function to clean up context object
fields: Fields,
conv: TupleConverter[S],
set: TupleSetter[T]
) extends SideEffectBaseOperation[C](bf, ef, fields) with Function[C] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fn)
override def operate(flowProcess: FlowProcess[_], functionCall: FunctionCall[C]) {
val context = functionCall.getContext
val s = conv(functionCall.getArguments)
val res = fn(context, s)
functionCall.getOutputCollector.add(set(res))
}
}
/*
* A flatmap function that allows state object to be set up and tear down.
*/
class SideEffectFlatMapFunction[S, C, T] (
bf: => C, // begin function returns a context
fn: (C, S) => Iterable[T], // function that takes a context and a tuple, returns iterable of T
ef: C => Unit, // end function to clean up context object
fields: Fields,
conv: TupleConverter[S],
set: TupleSetter[T]
) extends SideEffectBaseOperation[C](bf, ef, fields) with Function[C] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fn)
override def operate(flowProcess: FlowProcess[_], functionCall: FunctionCall[C]) {
val context = functionCall.getContext
val s = conv(functionCall.getArguments)
fn(context, s) foreach { t => functionCall.getOutputCollector.add(set(t)) }
}
}
class FilterFunction[T](fn : T => Boolean, conv : TupleConverter[T]) extends BaseOperation[Any] with Filter[Any] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fn)
def isRemove(flowProcess : FlowProcess[_], filterCall : FilterCall[Any]) = {
!fn(conv(filterCall.getArguments))
}
}
// All the following are operations for use in GroupBuilder
class FoldAggregator[T,X](fn : (X,T) => X, init : X, fields : Fields,
conv : TupleConverter[T], set : TupleSetter[X])
extends BaseOperation[X](fields) with Aggregator[X] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fn)
def start(flowProcess : FlowProcess[_], call : AggregatorCall[X]) {
val deepCopyInit = kryoFor(flowProcess).copy(init)
call.setContext(deepCopyInit)
}
def aggregate(flowProcess : FlowProcess[_], call : AggregatorCall[X]) {
val left = call.getContext
val right = conv(call.getArguments)
call.setContext(fn(left, right))
}
def complete(flowProcess : FlowProcess[_], call : AggregatorCall[X]) {
emit(flowProcess, call)
}
def emit(flowProcess : FlowProcess[_], call : AggregatorCall[X]) {
call.getOutputCollector.add(set(call.getContext))
}
}
/*
* fields are the declared fields of this aggregator
*/
class MRMAggregator[T,X,U](fsmf : T => X, rfn : (X,X) => X, mrfn : X => U, fields : Fields,
conv : TupleConverter[T], set : TupleSetter[U])
extends BaseOperation[Tuple](fields) with Aggregator[Tuple] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(fsmf)
ClosureCleaner(rfn)
ClosureCleaner(mrfn)
// The context is a singleton Tuple, which is mutable so
// we don't have to allocate at every step of the loop:
def start(flowProcess : FlowProcess[_], call : AggregatorCall[Tuple]) {
call.setContext(null)
}
def extractArgument(call : AggregatorCall[Tuple]) : X = fsmf(conv(call.getArguments))
def aggregate(flowProcess : FlowProcess[_], call : AggregatorCall[Tuple]) {
val arg = extractArgument(call)
val ctx = call.getContext
if (null == ctx) {
// Initialize the context, this is the only allocation done by this loop.
val newCtx = Tuple.size(1)
newCtx.set(0, arg.asInstanceOf[AnyRef])
call.setContext(newCtx)
}
else {
// Mutate the context:
val oldValue = ctx.getObject(0).asInstanceOf[X]
val newValue = rfn(oldValue, arg)
ctx.set(0, newValue.asInstanceOf[AnyRef])
}
}
def complete(flowProcess : FlowProcess[_], call : AggregatorCall[Tuple]) {
val ctx = call.getContext
if (null != ctx) {
val lastValue = ctx.getObject(0).asInstanceOf[X]
// Make sure to drop the reference to the lastValue as soon as possible (it may be big)
call.setContext(null)
call.getOutputCollector.add(set(mrfn(lastValue)))
}
else {
throw new Exception("MRMAggregator completed without any args")
}
}
}
/**
* This handles the mapReduceMap work on the map-side of the operation. The code below
* attempts to be optimal with respect to memory allocations and performance, not functional
* style purity.
*/
abstract class FoldFunctor[X](fields : Fields) extends AggregateBy.Functor {
// Extend these three methods:
def first(args : TupleEntry) : X
def subsequent(oldValue : X, newArgs : TupleEntry) : X
def finish(lastValue : X) : Tuple
override final def getDeclaredFields = fields
/*
* It's important to keep all state in the context as Cascading seems to
* reuse these objects, so any per instance state might give unexpected
* results.
*/
override final def aggregate(flowProcess : FlowProcess[_], args : TupleEntry, context : Tuple) = {
var nextContext : Tuple = null
val newContextObj = if (null == context) {
// First call, make a new mutable tuple to reduce allocations:
nextContext = Tuple.size(1)
first(args)
}
else {
//We are updating
val oldValue = context.getObject(0).asInstanceOf[X]
nextContext = context
subsequent(oldValue, args)
}
nextContext.set(0, newContextObj.asInstanceOf[AnyRef])
//Return context for reuse next time:
nextContext
}
override final def complete(flowProcess : FlowProcess[_], context : Tuple) = {
if (null == context) {
throw new Exception("FoldFunctor completed with any aggregate calls")
}
else {
val res = context.getObject(0).asInstanceOf[X]
// Make sure we remove the ref to the context ASAP:
context.set(0, null)
finish(res)
}
}
}
/**
* This handles the mapReduceMap work on the map-side of the operation. The code below
* attempts to be optimal with respect to memory allocations and performance, not functional
* style purity.
*/
class MRMFunctor[T,X](mrfn : T => X, rfn : (X, X) => X, fields : Fields,
conv : TupleConverter[T], set : TupleSetter[X])
extends FoldFunctor[X](fields) {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(mrfn)
ClosureCleaner(rfn)
override def first(args : TupleEntry) : X = mrfn(conv(args))
override def subsequent(oldValue : X, newArgs : TupleEntry) = {
val right = mrfn(conv(newArgs))
rfn(oldValue, right)
}
override def finish(lastValue : X) = set(lastValue)
}
/**
* MapReduceMapBy Class
*/
class MRMBy[T,X,U](arguments : Fields,
middleFields : Fields,
declaredFields : Fields,
mfn : T => X,
rfn : (X,X) => X,
mfn2 : X => U,
startConv : TupleConverter[T],
midSet : TupleSetter[X],
midConv : TupleConverter[X],
endSet : TupleSetter[U]) extends AggregateBy(
arguments,
new MRMFunctor[T,X](mfn, rfn, middleFields, startConv, midSet),
new MRMAggregator[X,X,U](args => args, rfn, mfn2, declaredFields, midConv, endSet)) {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(mfn)
ClosureCleaner(rfn)
ClosureCleaner(mfn2)
}
class BufferOp[I,T,X](init : I, iterfn : (I, Iterator[T]) => TraversableOnce[X], fields : Fields,
conv : TupleConverter[T], set : TupleSetter[X])
extends BaseOperation[Any](fields) with Buffer[Any] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(iterfn)
def operate(flowProcess : FlowProcess[_], call : BufferCall[Any]) {
val deepCopyInit = kryoFor(flowProcess).copy(init)
val oc = call.getOutputCollector
val in = call.getArgumentsIterator.asScala.map { entry => conv(entry) }
iterfn(deepCopyInit, in).foreach { x => oc.add(set(x)) }
}
}
/*
* A buffer that allows state object to be set up and tear down.
*/
class SideEffectBufferOp[I,T,C,X](
init : I,
bf: => C, // begin function returns a context
iterfn: (I, C, Iterator[T]) => TraversableOnce[X],
ef: C => Unit, // end function to clean up context object
fields: Fields,
conv: TupleConverter[T],
set: TupleSetter[X]
) extends SideEffectBaseOperation[C](bf, ef, fields) with Buffer[C] {
//Clean the outer$ refs off if they are not accessed
ClosureCleaner(iterfn)
def operate(flowProcess : FlowProcess[_], call : BufferCall[C]) {
val deepCopyInit = kryoFor(flowProcess).copy(init)
val context = call.getContext
val oc = call.getOutputCollector
val in = call.getArgumentsIterator.asScala.map { entry => conv(entry) }
iterfn(deepCopyInit, context, in).foreach { x => oc.add(set(x)) }
}
}
}