/
Execution.scala
1152 lines (1030 loc) · 43.3 KB
/
Execution.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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 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 com.twitter.scalding.typed.{Output, TypedPipe}
import com.twitter.scalding.dagon.{Dag, Id, Rule}
import com.twitter.algebird.monad.Trampoline
import com.twitter.algebird.{Monad, Monoid, Semigroup}
import com.twitter.scalding.typed.functions.{ConsList, ReverseList}
import com.twitter.scalding.dagon.{Memoize, RefPair}
import java.io.Serializable
import java.util.UUID
import scala.collection.mutable
import scala.concurrent.duration.SECONDS
import scala.concurrent.{
blocking,
duration,
Await,
ExecutionContext => ConcurrentExecutionContext,
Future,
Promise
}
import scala.util.{Failure, Success, Try}
import scala.util.control.NonFatal
import scala.util.hashing.MurmurHash3
/**
* Execution[T] represents and computation that can be run and will produce a value T and keep track of
* counters incremented inside of TypedPipes using a Stat.
*
* Execution[T] is the recommended way to compose multistep computations that involve branching (if/then),
* intermediate calls to remote services, file operations, or looping (e.g. testing for convergence).
*
* Library functions are encouraged to implement functions from TypedPipes or ValuePipes to Execution[R] for
* some result R. Refrain from calling run in library code. Let the caller of your library call run.
*
* Note this is a Monad, meaning flatMap composes in series as you expect. It is also an applicative functor,
* which means zip (called join in some libraries) composes two Executions is parallel. Prefer zip to flatMap
* if you want to run two Executions in parallel.
*/
sealed trait Execution[+T] extends Serializable { self: Product =>
import Execution.{
EvalCache,
FlatMapped,
GetCounters,
Mapped,
OnComplete,
RecoverWith,
ResetCounters,
Zipped
}
/**
* Lift an Execution into a Try
*
* When this function is called the Execution should never be failed instead only the Try.
*/
def liftToTry: Execution[Try[T]] =
map(e => Success(e)).recoverWith { case throwable => Execution.from(Failure(throwable)) }
/**
* Scala uses the filter method in for syntax for pattern matches that can fail. If this filter is false,
* the result of run will be an exception in the future
*/
def filter(pred: T => Boolean): Execution[T] =
flatMap {
case good if pred(good) => Execution.from(good)
case failed => Execution.from(sys.error("Filter failed on: " + failed.toString))
}
/**
* First run this Execution, then move to the result of the function
*/
def flatMap[U](fn: T => Execution[U]): Execution[U] =
FlatMapped(this, fn)
/**
* This is the same as flatMap(identity)
*/
def flatten[U](implicit ev: T <:< Execution[U]): Execution[U] =
flatMap(ev)
/**
* Apply a pure function to the result. This may not be called if subsequently the result is discarded with
* .unit For side effects see onComplete.
*/
def map[U](fn: T => U): Execution[U] =
Mapped(this, fn)
/**
* Reads the counters into the value, but does not reset them. You may want .getAndResetCounters.
*/
def getCounters: Execution[(T, ExecutionCounters)] =
GetCounters(this)
/**
* Reads the counters and resets them to zero. Probably what you want in a loop that is using counters to
* check for convergence.
*/
def getAndResetCounters: Execution[(T, ExecutionCounters)] =
getCounters.resetCounters
/**
* This function is called when the current run is completed. This is only a side effect (see unit return).
*
* ALSO You must .run the result. If you throw away the result of this call, your fn will never be called.
* When you run the result, the Future you get will not be complete unless fn has completed running. If fn
* throws, it will be handled be the scala.concurrent.ExecutionContext.reportFailure NOT by returning a
* Failure in the Future.
*/
def onComplete(fn: Try[T] => Unit): Execution[T] = OnComplete(this, fn)
/**
* This allows you to handle a failure by giving a replacement execution in some cases. This execution may
* be a retry if you know that your execution can have spurious errors, or it could be a constant or an
* alternate way to compute. Be very careful creating looping retries that could hammer your cluster when
* the data is missing or when when there is some real problem with your job logic.
*/
def recoverWith[U >: T](rec: PartialFunction[Throwable, Execution[U]]): Execution[U] =
RecoverWith(this, rec)
/**
* Resets the counters back to zero. This is useful if you want to reset before a zip or a call to flatMap
*/
def resetCounters: Execution[T] =
ResetCounters(this)
/**
* This causes the Execution to occur. The result is not cached, so each call to run will result in the
* computation being re-run. Avoid calling this until the last possible moment by using flatMap, zip and
* recoverWith.
*
* Seriously: pro-style is for this to be called only once in a program.
*/
final def run(conf: Config, mode: Mode)(implicit cec: ConcurrentExecutionContext): Future[T] = {
val writer: Execution.Writer = mode.newWriter()
val ec = new EvalCache(writer)
val confWithId = conf.setScaldingExecutionId(UUID.randomUUID.toString)
val exec = Execution.optimize(conf, this)
// get on Trampoline
val CFuture(fut, cancelHandler) = exec.runStats(confWithId, mode, ec)(cec).get
// When the final future in complete we stop the submit thread
val result = fut.map(_._1).andThen { case t =>
if (t.isFailure) {
blocking {
// cancel running executions if this was a failure
Await.ready(cancelHandler.stop(), duration.Duration(30, SECONDS))
}
}
writer.finished()
}
// wait till the end to start the thread in case the above throws
writer.start()
result
}
/**
* This is the internal method that must be implemented Given a config, mode, and cache of evaluations for
* this config and mode, return the new cache with as much evaluation as possible before the future
* completes, and a future of the result, counters and cache after the future is complete
*/
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
): Trampoline[CFuture[(T, Map[Long, ExecutionCounters])]]
/**
* This is convenience for when we don't care about the result. like .map(_ => ())
*/
def unit: Execution[Unit] = map(_ => ())
/**
* This waits synchronously on run, using the global execution context Avoid calling this if possible,
* prefering run or just Execution composition. Every time someone calls this, be very suspect. It is always
* code smell. Very seldom should you need to wait on a future.
*/
def waitFor(conf: Config, mode: Mode): Try[T] =
Try(Await.result(run(conf, mode)(ConcurrentExecutionContext.global), duration.Duration.Inf))
/**
* This is here to silence warnings in for comprehensions, but is identical to .filter.
*
* Users should never directly call this method, call .filter
*/
def withFilter(p: T => Boolean): Execution[T] = filter(p)
/*
* run this and that in parallel, without any dependency. This will
* be done in a single cascading flow if possible.
*/
def zip[U](that: Execution[U]): Execution[(T, U)] =
Zipped(this, that)
override val hashCode: Int = MurmurHash3.productHash(self)
/**
* since executions, particularly Zips can cause two executions to merge we can have exponential cost to
* computing equals if we are not careful
*/
override def equals(other: Any): Boolean =
other match {
case otherEx: Execution[_] =>
if (otherEx eq this) true
else if (otherEx.hashCode != hashCode) false
else {
// If we get here, we have two executions that either
// collide in hashcode, or they are truely equal. Since
// collisions are rare, most of these will be true equality
// so we will fully walk the graph. If we don't remember
// the branches we go down, Zipped will be very expensize
import Execution._
val fn = Memoize.function[RefPair[Execution[Any], Execution[Any]], Boolean] {
case (RefPair(a, b), _) if a eq b => true
case (RefPair(BackendExecution(fn0), BackendExecution(fn1)), rec) =>
fn0 == fn1
case (RefPair(FlatMapped(ex0, fn0), FlatMapped(ex1, fn1)), rec) =>
(fn0 == fn1) && rec(RefPair(ex0, ex1))
case (RefPair(FutureConst(fn0), FutureConst(fn1)), rec) =>
fn0 == fn1
case (RefPair(GetCounters(ex0), GetCounters(ex1)), rec) =>
rec(RefPair(ex0, ex1))
case (RefPair(Mapped(ex0, fn0), Mapped(ex1, fn1)), rec) =>
(fn0 == fn1) && rec(RefPair(ex0, ex1))
case (RefPair(OnComplete(ex0, fn0), OnComplete(ex1, fn1)), rec) =>
(fn0 == fn1) && rec(RefPair(ex0, ex1))
case (RefPair(ReaderExecution, ReaderExecution), _) => true
case (RefPair(RecoverWith(ex0, fn0), RecoverWith(ex1, fn1)), rec) =>
(fn0 == fn1) && rec(RefPair(ex0, ex1))
case (RefPair(ResetCounters(ex0), ResetCounters(ex1)), rec) =>
rec(RefPair(ex0, ex1))
case (RefPair(TransformedConfig(ex0, fn0), TransformedConfig(ex1, fn1)), rec) =>
(fn0 == fn1) && rec(RefPair(ex0, ex1))
case (RefPair(UniqueIdExecution(fn0), UniqueIdExecution(fn1)), _) =>
fn0 == fn1
case (RefPair(WithNewCache(ex0), WithNewCache(ex1)), rec) =>
rec(RefPair(ex0, ex1))
case (RefPair(WriteExecution(h0, t0, f0), WriteExecution(h1, t1, f1)), _) =>
(f0 == f1) && ((h0 :: t0) == (h1 :: t1))
case (RefPair(Zipped(a0, b0), Zipped(a1, b1)), rec) =>
rec(RefPair(a0, a1)) && rec(RefPair(b0, b1))
case (rp, _) =>
require(rp._1.getClass != rp._2.getClass)
false // the executions are not of the same type
}
fn(RefPair(this, otherEx))
}
case _ => false
}
}
/**
* Execution has many methods for creating Execution[T] instances, which are the preferred way to compose
* computations in scalding libraries.
*/
object Execution {
private[Execution] class AsyncSemaphore(initialPermits: Int = 0) {
private[this] val waiters = new mutable.Queue[() => Unit]
private[this] var availablePermits = initialPermits
private[Execution] class SemaphorePermit {
def release() =
AsyncSemaphore.this.synchronized {
availablePermits += 1
if (availablePermits > 0 && waiters.nonEmpty) {
availablePermits -= 1
waiters.dequeue()()
}
}
}
def acquire(): Future[SemaphorePermit] = {
val promise = Promise[SemaphorePermit]()
def setAcquired(): Unit =
promise.success(new SemaphorePermit)
synchronized {
if (availablePermits > 0) {
availablePermits -= 1
setAcquired()
} else {
waiters.enqueue(setAcquired)
}
}
promise.future
}
}
private def optimize[A](conf: Config, ex: Execution[A]): Execution[A] =
if (conf.getExecutionOptimization) {
ExecutionOptimizationRules.stdOptimizations(ex)
} else {
ex
}
/**
* This is an instance of Monad for execution so it can be used in functions that apply to all Monads
*/
implicit object ExecutionMonad extends Monad[Execution] {
override def apply[T](t: T): Execution[T] = Execution.from(t)
override def map[T, U](e: Execution[T])(fn: T => U): Execution[U] = e.map(fn)
override def flatMap[T, U](e: Execution[T])(fn: T => Execution[U]): Execution[U] = e.flatMap(fn)
override def join[T, U](t: Execution[T], u: Execution[U]): Execution[(T, U)] = t.zip(u)
}
def withConfig[T](ex: Execution[T])(c: Config => Config): Execution[T] =
TransformedConfig(ex, c)
/**
* This function allows running the passed execution with its own cache. This will mean anything inside
* won't benefit from Execution's global attempts to avoid repeated executions.
*
* The main use case here is when generating a lot of Execution results which are large. Executions caching
* in this case can lead to out of memory errors as the cache keeps references to many heap objects.
*
* Ex. (0 until 1000).map { _ => Execution.withNewCache(myLargeObjectProducingExecution)}
*/
def withNewCache[T](ex: Execution[T]): Execution[T] =
WithNewCache(ex)
/**
* This is the standard semigroup on an Applicative (zip, then inside the Execution do plus)
*/
implicit def semigroup[T: Semigroup]: Semigroup[Execution[T]] = Semigroup.from[Execution[T]] { (a, b) =>
a.zip(b).map { case (ta, tb) => Semigroup.plus(ta, tb) }
}
/**
* This is the standard monoid on an Applicative (zip, then inside the Execution do plus) useful to combine
* unit Executions: Monoid.sum(ex1, ex2, ex3, ex4): Execution[Unit] where each are exi are Execution[Unit]
*/
implicit def monoid[T: Monoid]: Monoid[Execution[T]] = Monoid.from(Execution.from(Monoid.zero[T])) {
(a, b) =>
a.zip(b).map { case (ta, tb) => Monoid.plus(ta, tb) }
}
/**
* This is a mutable state that is kept internal to an execution as it is evaluating.
*/
private[scalding] class EvalCache(val writer: Execution.Writer) {
type Counters = Map[Long, ExecutionCounters]
private[this] val cache =
new FutureCacheGeneric[(Config, Execution[Any]), (Any, Counters), CPromise, CFuture]
private[this] val toWriteCache = new FutureCacheGeneric[(Config, ToWrite[_]), Counters, CPromise, CFuture]
// This method with return a 'clean' cache, that shares
// the underlying thread and message queue of the parent evalCache
def cleanCache: EvalCache = new EvalCache(writer)
def getOrLock(cfg: Config, write: ToWrite[_]): Either[CPromise[Counters], CFuture[Counters]] =
toWriteCache.getOrPromise((cfg, write))
def getOrElseInsertWithFeedback[T](
cfg: Config,
ex: Execution[T],
res: => CFuture[(T, Counters)]
): (Boolean, CFuture[(T, Counters)]) =
// This cast is safe because we always insert with match T types
cache
.getOrElseUpdateIsNew((cfg, ex), res)
.asInstanceOf[(Boolean, CFuture[(T, Counters)])]
def getOrElseInsert[T](
cfg: Config,
ex: Execution[T],
res: => CFuture[(T, Counters)]
): CFuture[(T, Counters)] =
getOrElseInsertWithFeedback(cfg, ex, res)._2
}
private[scalding] final case class FutureConst[T](get: ConcurrentExecutionContext => Future[T])
extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline {
lazy val fut = for {
futt <- toFuture(Try(get(cec)))
t <- futt
} yield (t, Map.empty[Long, ExecutionCounters])
lazy val cfut = CFuture.uncancellable(fut)
cache.getOrElseInsert(conf, this, cfut)
}
// Note that unit is not optimized away, since Futures are often used with side-effects, so,
// we ensure that get is always called in contrast to Mapped, which assumes that fn is pure.
}
private[scalding] final case class FlatMapped[S, T](prev: Execution[S], fn: S => Execution[T])
extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline.call(prev.runStats(conf, mode, cache)).map { case CFuture(fut1, cancelHandler1) =>
lazy val uncachedCFut = for {
(s, st1) <- fut1
next0 = fn(s)
// next0 has not been optimized yet, we need to try
next = optimize(conf, next0)
} yield {
Trampoline.call(next.runStats(conf, mode, cache)).get.map { case (t, st2) =>
(t, st1 ++ st2)
}
}
val futCancel = cache.getOrElseInsert(conf, this, CFuture.fromFuture(uncachedCFut))
CFuture(futCancel.future, cancelHandler1.compose(futCancel.cancellationHandler))
}
}
private[scalding] final case class Mapped[S, T](prev: Execution[S], fn: S => T) extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline.call(prev.runStats(conf, mode, cache)).map { cfuture =>
cache.getOrElseInsert(conf, this, cfuture.map { case (s, stats) => (fn(s), stats) })
}
}
private[scalding] final case class GetCounters[T](prev: Execution[T])
extends Execution[(T, ExecutionCounters)] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline.call(prev.runStats(conf, mode, cache)).map { cfuture =>
cache.getOrElseInsert(
conf,
this,
cfuture.map { case (t, c) =>
val totalCount = Monoid.sum(c.map(_._2))
((t, totalCount), c)
}
)
}
}
private[scalding] final case class ResetCounters[T](prev: Execution[T]) extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline.call(prev.runStats(conf, mode, cache)).map { cfuture =>
cache
.getOrElseInsert(conf, this, cfuture.map { case (t, _) => (t, Map.empty[Long, ExecutionCounters]) })
}
}
private[scalding] final case class TransformedConfig[T](prev: Execution[T], fn: Config => Config)
extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) = {
val mutatedConfig = fn(conf)
Trampoline.call(prev.runStats(mutatedConfig, mode, cache))
}
}
/**
* This class allows running the passed execution with its own cache. This will mean anything inside won't
* benefit from Execution's global attempts to avoid repeated executions.
*
* The main use case here is when generating a lot of Execution results which are large. Executions caching
* in this case can lead to out of memory errors as the cache keeps references to many heap objects.
*
* We operate here by getting a copy of the super EvalCache, without its cache's. This is so we can share
* the singleton thread for scheduling jobs against Cascading.
*/
private[scalding] final case class WithNewCache[T](prev: Execution[T]) extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) = {
val ec = cache.cleanCache
Trampoline.call(prev.runStats(conf, mode, ec))
}
}
private[scalding] final case class OnComplete[T](prev: Execution[T], fn: Try[T] => Unit)
extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline.call(prev.runStats(conf, mode, cache)).map { cfuture =>
cache.getOrElseInsert(
conf,
this,
cfuture.mapFuture { fut =>
/**
* The result we give is only completed AFTER fn is run so callers can wait on the result of this
* OnComplete
*/
val finished = Promise[(T, Map[Long, ExecutionCounters])]()
fut.onComplete { tryT =>
try {
fn(tryT.map(_._1))
} finally {
// Do our best to signal when we are done
finished.complete(tryT)
}
}
finished.future
}
)
}
}
private[scalding] final case class RecoverWith[T](
prev: Execution[T],
fn: PartialFunction[Throwable, Execution[T]]
) extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline.call(prev.runStats(conf, mode, cache)).map { case CFuture(fut, cancelHandler) =>
lazy val uncachedFut =
fut
.map(v => (v, CancellationHandler.empty)) // map this to the right shape
.recoverWith {
val flowStop: PartialFunction[Throwable, Future[Nothing]] = {
case t: FatalExecutionError => // do not recover when the flow was stopped
Future.failed(t)
}
flowStop.orElse(fn.andThen { ex0 =>
// we haven't optimized ex0 yet
val ex = optimize(conf, ex0)
val CFuture(f, c) = ex.runStats(conf, mode, cache).get
f.map(v => (v, c))
})
}
val recoveredFut = cache.getOrElseInsert(
conf,
this,
CFuture(uncachedFut.map(_._1), CancellationHandler.fromFuture(uncachedFut.map(_._2)))
)
CFuture(recoveredFut.future, cancelHandler.compose(recoveredFut.cancellationHandler))
}
}
/**
* Standard scala zip waits forever on the left side, even if the right side fails
*/
def failFastZip[T, U](ft: Future[T], fu: Future[U])(implicit
cec: ConcurrentExecutionContext
): Future[(T, U)] = {
type State = Either[(T, Promise[U]), (U, Promise[T])]
val middleState = Promise[State]()
ft.onComplete {
case f @ Failure(err) =>
if (!middleState.tryFailure(err)) {
// the right has already succeeded
middleState.future.foreach {
case Right((_, pt)) => pt.complete(f)
case Left((t1, _)) => // This should never happen
sys.error(s"Logic error: tried to set Failure($err) but Left($t1) already set")
}
}
case Success(t) =>
// Create the next promise:
val pu = Promise[U]()
if (!middleState.trySuccess(Left((t, pu)))) {
// we can't set, so the other promise beat us here.
middleState.future.foreach {
case Right((_, pt)) => pt.success(t)
case Left((t1, _)) => // This should never happen
sys.error(s"Logic error: tried to set Left($t) but Left($t1) already set")
}
}
}
fu.onComplete {
case f @ Failure(err) =>
if (!middleState.tryFailure(err)) {
// we can't set, so the other promise beat us here.
middleState.future.foreach {
case Left((_, pu)) => pu.complete(f)
case Right((u1, _)) => // This should never happen
sys.error(s"Logic error: tried to set Failure($err) but Right($u1) already set")
}
}
case Success(u) =>
// Create the next promise:
val pt = Promise[T]()
if (!middleState.trySuccess(Right((u, pt)))) {
// we can't set, so the other promise beat us here.
middleState.future.foreach {
case Left((_, pu)) => pu.success(u)
case Right((u1, _)) => // This should never happen
sys.error(s"Logic error: tried to set Right($u) but Right($u1) already set")
}
}
}
middleState.future.flatMap {
case Left((t, pu)) => pu.future.map((t, _))
case Right((u, pt)) => pt.future.map((_, u))
}
}
private[scalding] final case class Zipped[S, T](one: Execution[S], two: Execution[T])
extends Execution[(S, T)] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
for {
futCancel1 <- Trampoline.call(one.runStats(conf, mode, cache))
futCancel2 <- Trampoline.call(two.runStats(conf, mode, cache))
} yield {
cache.getOrElseInsert(
conf,
this,
futCancel1.zip(futCancel2).map { case ((s, ss), (t, st)) => ((s, t), ss ++ st) }
)
}
}
private[scalding] final case class UniqueIdExecution[T](fn: UniqueID => Execution[T]) extends Execution[T] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline(
cache.getOrElseInsert(
conf,
this, {
val (uid, nextConf) = conf.ensureUniqueId
val next0 = fn(uid)
// next0 has not been optimized yet, we need to try
val next = optimize(conf, next0)
next.runStats(nextConf, mode, cache).get
}
)
)
}
/*
* This allows you to run platform specific executions
*/
private[scalding] final case class BackendExecution[A](
result: (Config, Mode, Writer, ConcurrentExecutionContext) => CFuture[(Long, ExecutionCounters, A)]
) extends Execution[A] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline(
cache.getOrElseInsert(
conf,
this,
try result(conf, mode, cache.writer, cec).map { case (id, c, a) => (a, Map(id -> c)) }
catch {
case NonFatal(e) => CFuture.failed(e)
}
)
)
}
/*
* This is here so we can call without knowing the type T
* but with proof that pipe matches sink
*
* We capture these objects in calls of TypedPipe.toIterableExecution,
* but can safely ignore serializing planning objects for the same reasons mentioned in KryoHadoop.scala
*/
sealed trait ToWrite[T] extends Serializable {
def pipe: TypedPipe[T]
def replacePipe(p: TypedPipe[T]): ToWrite[T] =
this match {
case ToWrite.Force(_) => ToWrite.Force(p)
case ToWrite.ToIterable(_) => ToWrite.ToIterable(p)
case ToWrite.SimpleWrite(_, sink) => ToWrite.SimpleWrite(p, sink)
}
}
object ToWrite extends Serializable {
final case class Force[T](@transient pipe: TypedPipe[T]) extends ToWrite[T]
final case class ToIterable[T](@transient pipe: TypedPipe[T]) extends ToWrite[T]
final case class SimpleWrite[T](@transient pipe: TypedPipe[T], @transient sink: Output[T])
extends ToWrite[T]
final case class OptimizedWrite[F[_], T](@transient original: F[T], toWrite: ToWrite[T])
/**
* Optimize these writes into new writes and provide a mapping from the original TypedPipe to the new
* TypedPipe
*/
def optimizeWriteBatch(
writes: List[ToWrite[_]],
rules: Seq[Rule[TypedPipe]]
): List[OptimizedWrite[TypedPipe, _]] = {
val dag = Dag.empty(typed.OptimizationRules.toLiteral)
val (d1, ws) = writes.foldLeft((dag, List.empty[OptimizedWrite[Id, _]])) { case ((dag, ws), toWrite) =>
val (d1, id) = dag.addRoot(toWrite.pipe)
(d1, OptimizedWrite(id, toWrite) :: ws)
}
// now we optimize the graph
val d2 = d1.applySeq(rules)
// convert back to TypedPipe:
ws.foldLeft(List.empty[OptimizedWrite[TypedPipe, _]]) { case (tail, optWrite) =>
def go[A](optWriteId: OptimizedWrite[Id, A]): OptimizedWrite[TypedPipe, A] = {
val idA = optWriteId.original
val origPipe = d1.evaluate(idA)
val optPipe = d2.evaluate(idA)
OptimizedWrite(original = origPipe, toWrite = optWriteId.toWrite.replacePipe(optPipe))
}
go(optWrite) :: tail
}
}
}
/**
* Something that can handle a batch of writes that may be optimized before running. Return a unique Long
* for each run and Counters
*/
trait Writer {
/**
* This is called by an Execution to begin processing
*/
def start(): Unit
/**
* This is called by an Execution to end processing
*/
def finished(): Unit
/**
* do a batch of writes, possibly optimizing, and return a new unique Long.
*
* empty writes are legitimate and should still return a Long
*/
def execute(conf: Config, writes: List[ToWrite[_]])(implicit
cec: ConcurrentExecutionContext
): CFuture[(Long, ExecutionCounters)]
/**
* This should only be called after a call to execute
*/
private[Execution] def getForced[T](
conf: Config,
initial: TypedPipe[T]
)(implicit cec: ConcurrentExecutionContext): Future[TypedPipe[T]]
/**
* This should only be called after a call to execute
*/
private[Execution] def getIterable[T](
conf: Config,
initial: TypedPipe[T]
)(implicit cec: ConcurrentExecutionContext): Future[Iterable[T]]
}
/**
* This is the fundamental execution that actually happens in TypedPipes, all the rest are based on on this
* one. By keeping the Pipe and the Sink, can inspect the Execution DAG and optimize it later (a goal, but
* not done yet).
*/
private[scalding] final case class WriteExecution[T](
head: ToWrite[_],
tail: List[ToWrite[_]],
result: ((Config, Mode, Writer, ConcurrentExecutionContext)) => Future[T]
) extends Execution[T] {
/**
* We override this here to enable inlining the zip optimization below.
*
* This is such an important optimization, that we apply it locally. It is a bit ugly to have it here and
* in ExecutionOptimizationRules but since this is so important, we do so anyway.
*
* Note Execution optimizations are not always applied, they are something users can disable, which they
* may since in some cases giant Execution graphs have seen stack overflows. It doesn't hurt to apply this
* optimization here, but it doesn't cover all cases since it only combines adjacent writes.
*/
override def map[U](mapFn: T => U): Execution[U] =
WriteExecution(head, tail, ExecutionOptimizationRules.MapWrite.ComposeMap(result, mapFn))
private def unwrapListEither[A, B, C](it: List[(A, Either[B, C])]): (List[(A, B)], List[(A, C)]) =
it match {
case (a, Left(b)) :: tail =>
val (l, r) = unwrapListEither(tail)
((a, b) :: l, r)
case (a, Right(c)) :: tail =>
val (l, r) = unwrapListEither(tail)
(l, (a, c) :: r)
case Nil => (Nil, Nil)
}
// We look up to see if any of our ToWrite elements have already been ran
// if so we remove them from the cache.
// Anything not already ran we run as part of a single flow def, using their combined counters for the others
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) = {
lazy val uncachedFutureCancel = {
val cacheLookup: List[
(
ToWrite[_],
(Either[CPromise[Map[Long, ExecutionCounters]], CFuture[Map[Long, ExecutionCounters]]])
)
] =
(head :: tail).map(tw => (tw, cache.getOrLock(conf, tw)))
val (weDoOperation, someoneElseDoesOperation) = unwrapListEither(cacheLookup)
val otherResult = CFuture.failFastSequence(someoneElseDoesOperation.map(_._2))
otherResult.future.value match {
case Some(Failure(e)) => CFuture.failed(e)
case _ => // Either successful or not completed yet
val localFlowDefCountersFuture: CFuture[Map[Long, ExecutionCounters]] =
weDoOperation match {
case all @ (h :: tail) =>
val CFuture(fut, cancelHandler) = cache.writer
.execute(conf, all.map(_._1))
val futCounters: Future[Map[Long, ExecutionCounters]] =
fut.map(Map(_))
// Complete all of the promises we put into the cache
// with this future counters set
all.foreach { case (toWrite, cpromise) =>
cpromise.completeWith(CFuture(futCounters, cancelHandler))
}
CFuture(futCounters, cancelHandler)
case Nil =>
// No work to do, provide a fulled set of 0 counters to operate on
CFuture(Future.successful(Map.empty), CancellationHandler.empty)
}
val bothFutures = otherResult.zip(localFlowDefCountersFuture)
val fut = for {
(lCounters, fdCounters) <- bothFutures.future
t <- result(
(conf, mode, cache.writer, cec)
) // TODO do i need to do something here to make this cancellable?
summedCounters = (fdCounters :: lCounters).reduce(_ ++ _)
} yield (t, summedCounters)
CFuture(fut, bothFutures.cancellationHandler)
}
}
Trampoline(cache.getOrElseInsert(conf, this, uncachedFutureCancel))
}
/**
* This is such an important optimization, that we apply it locally. It is a bit ugly to have it here and
* in ExecutionOptimizationRules but since this is so important, we do so anyway.
*
* Note Execution optimizations are not always applied, they are something users can disable, which they
* may since in some cases giant Execution graphs have seen stack overflows. It doesn't hurt to apply this
* optimization here, but it doesn't cover all cases since it only combines adjacent writes.
*
* Note, each Write is individually cached so it won't happen twice, but it is usually better to compose
* into the biggest set of writes so the planner can optimize the largest graph possible.
*
* run this and that in parallel, without any dependency. This will be done in a single cascading flow if
* possible.
*
* If both sides are write executions then merge them
*/
override def zip[U](that: Execution[U]): Execution[(T, U)] =
that match {
case w1 @ WriteExecution(_, _, _) =>
ExecutionOptimizationRules.ZipWrite.mergeWrite(this, w1)
case that => Zipped(this, that)
}
}
/**
* This is called Reader, because it just returns its input to run as the output
*/
private[scalding] case object ReaderExecution extends Execution[(Config, Mode)] {
protected def runStats(conf: Config, mode: Mode, cache: EvalCache)(implicit
cec: ConcurrentExecutionContext
) =
Trampoline(CFuture.successful(((conf, mode), Map.empty)))
override def equals(that: Any): Boolean =
that match {
// this has to be here or we get an infinite loop in the default equals
case _: ReaderExecution.type => true
case _ => false
}
}
private def toFuture[R](t: Try[R]): Future[R] =
t match {
case Success(s) => Future.successful(s)
case Failure(err) => Future.failed(err)
}
/**
* This creates a definitely failed Execution.
*/
def failed(t: Throwable): Execution[Nothing] = fromTry(Failure(t))
/**
* This makes a constant execution that runs no job. Note this is a lazy parameter that is evaluated every
* time run is called and does so in the ExecutionContext given to run
*/
def from[T](t: => T): Execution[T] = fromFuture(implicit ec => Future(t))
/**
* This evaluates the argument every time run is called, and does so in the ExecutionContext given to run
*/
def fromTry[T](t: => Try[T]): Execution[T] = fromFuture { implicit ec =>
Future(t).flatMap(toFuture)
}
/**
* The call to fn will happen when the run method on the result is called. The ConcurrentExecutionContext
* will be the same one used on run. This is intended for cases where you need to make asynchronous calls in
* the middle or end of execution. Presumably this is used with flatMap either before or after
*/
def fromFuture[T](fn: ConcurrentExecutionContext => Future[T]): Execution[T] = FutureConst(fn)
/** Returns a constant Execution[Unit] */
val unit: Execution[Unit] = from(())
/**
* This should be avoided if at all possible. It is here to allow backend authors to implement custom
* executions which should very rarely be needed.
*
* The CFuture returned should have three elements:
* 1. unique ID (Long) for the scope of the Writer 2. Counter values created by this Execution 3. the
* final result of the Execution (maybe Unit)
*/
def backendSpecific[A](
fn: (Config, Mode, Writer, ConcurrentExecutionContext) => CFuture[(Long, ExecutionCounters, A)]
): Execution[A] =
BackendExecution(fn)
def forceToDisk[T](t: TypedPipe[T]): Execution[TypedPipe[T]] =
WriteExecution(ToWrite.Force(t), Nil, { case (conf, _, w, cec) => w.getForced(conf, t)(cec) })
def toIterable[T](t: TypedPipe[T]): Execution[Iterable[T]] =
WriteExecution(ToWrite.ToIterable(t), Nil, { case (conf, _, w, cec) => w.getIterable(conf, t)(cec) })
/**
* The simplest form, just sink the typed pipe into the sink and get a unit execution back
*/
private[scalding] def write[T](pipe: TypedPipe[T], sink: Output[T]): Execution[Unit] =
write(pipe, sink, ())
private[scalding] def write[T, U](pipe: TypedPipe[T], sink: Output[T], presentType: => U): Execution[U] =
WriteExecution(ToWrite.SimpleWrite(pipe, sink), Nil, tup => Future(presentType)(tup._4))
/**
* Convenience method to get the Args
*/
def getArgs: Execution[Args] = ReaderExecution.map(_._1.getArgs)
/**
* Use this to read the configuration, which may contain Args or options which describe input on which to
* run
*/
def getConfig: Execution[Config] = ReaderExecution.map(_._1)
/** Use this to get the mode, which may contain the job conf */
def getMode: Execution[Mode] = ReaderExecution.map(_._2)
/** Use this to get the config and mode. */
def getConfigMode: Execution[(Config, Mode)] = ReaderExecution
/**
* This is convenience method only here to make it slightly cleaner to get Args, which are in the Config
*/
def withArgs[T](fn: Args => Execution[T]): Execution[T] =
getConfig.flatMap(conf => fn(conf.getArgs))
/**
* Use this to use counters/stats with Execution. You do this: Execution.withId { implicit uid => val myStat
* \= Stat("myStat") // uid is implicitly pulled in pipe.map { t => if(someCase(t)) myStat.inc fn(t) }
* .writeExecution(mySink) }
*/
def withId[T](fn: UniqueID => Execution[T]): Execution[T] = UniqueIdExecution(fn)
/**
* combine several executions and run them in parallel when .run is called
*/
def zip[A, B](ax: Execution[A], bx: Execution[B]): Execution[(A, B)] =
ax.zip(bx)
/**
* combine several executions and run them in parallel when .run is called
*/
def zip[A, B, C](ax: Execution[A], bx: Execution[B], cx: Execution[C]): Execution[(A, B, C)] =
ax.zip(bx).zip(cx).map { case ((a, b), c) => (a, b, c) }