-
Notifications
You must be signed in to change notification settings - Fork 4
/
guineapig1_1.py
1246 lines (1047 loc) · 49.8 KB
/
guineapig1_1.py
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
# earlier version of guineapig.py
##############################################################################
# (C) Copyright 2014 William W. Cohen. All rights reserved.
##############################################################################
import sys
import logging
import getopt
import os
import os.path
import subprocess
import collections
import urlparse
import csv
###############################################################################
# helpers and data structures
###############################################################################
class GPig(object):
"""Collection of utilities for Guinea Pig."""
HADOOP_LOC = 'hadoop' #assume hadoop is on the path at planning time
#global options for Guinea Pig can be passed in with the --opts
#command-line option, and these are the default values
envjar = os.environ.get('GP_STREAMJAR')
defaultJar = '/usr/lib/hadoop/contrib/streaming/hadoop-streaming-1.2.0.1.3.0.0-107.jar'
DEFAULT_OPTS = {'streamJar': envjar or defaultJar,
'parallel':5,
'target':'shell',
'echo':0,
'viewdir':'gpig_views',
}
#there are the types of each option that has a non-string value
DEFAULT_OPT_TYPES = {'parallel':int,'echo':int}
#we need to pass non-default options in to mappers and reducers,
#but since the remote worker's environment can be different, we
#also need to pass in options computed from the environment
COMPUTED_OPTION_DEFAULTS = {'streamJar':defaultJar}
@staticmethod
def getArgvParams(): return GPig.getArgvDict('--params')
@staticmethod
def getArgvOpts(): return GPig.getArgvDict('--opts')
@staticmethod
def getArgvDict(optname):
"""Return a dictionary of parameter values that were defined on the command line
view an option like '--params filename:foo.txt,basedir:/tmp/glob/'.
"""
assert optname.startswith('--')
for i,a in enumerate(sys.argv):
if a==optname:
paramString = sys.argv[i+1]
return dict(pair.split(":") for pair in paramString.split(","))
return {}
@staticmethod
def rowsOf(view):
"""Iterate over the rows in a view."""
for line in open(view.distributableFile()):
yield view.planner._serializer.fromString(line.strip())
@staticmethod
def onlyRowOf(view):
"""Return the first row in a side view, and raise an error if it
is not the only row of the view."""
result = None
logging.info('loading '+view.distributableFile())
for line in open(view.distributableFile()):
assert not result,'multiple rows in stored file for '+view.tag
result = view.planner._serializer.fromString(line.strip())
return result
class Jin(object):
""""Object to hold descripton of a single join input."""
def __init__(self,view,by=(lambda x:x),outer=False):
self.view = view
self.joinBy = by
self.outer = outer
self._padWithNulls = False
def __str__(self):
if self.view: viewStr = View.asTag(self.view)
else: viewStr = '_'
if self.outer: outerStr = ',outer=True'
else: outerStr = ''
if self._padWithNulls: padStr = ',_padWithNulls=True'
else: padStr = ''
return "Jin(%s,by=%s%s%s)" % (viewStr,self.joinBy,outerStr,padStr)
class ReduceTo(object):
"""An object x that can be the argument of a reducingTo=x
parameter in a Group view."""
def __init__(self,baseType,by=lambda accum,val:accum+val):
self.baseType = baseType
self.reduceBy = by
class ReduceToCount(ReduceTo):
"""Produce the count of the number of objects that would be placed in a group."""
def __init__(self):
ReduceTo.__init__(self,int,by=lambda accum,val:accum+1)
class ReduceToSum(ReduceTo):
"""Produce the count of the number of objects that would be placed in a group."""
def __init__(self):
ReduceTo.__init__(self,int,by=lambda accum,val:accum+val)
class ReduceToList(ReduceTo):
"""Produce a list of the objects that would be placed in a group."""
def __init__(self):
ReduceTo.__init__(self,list,by=lambda accum,val:accum+[val])
###############################################################################
# abstract views
##############################################################################
class View(object):
"""A relation object for guineaPig. A view - usually abbreviated rel,
r, s, t, - can be "materialized" to produce and unordered bag of
rows - usually abbreviated ro. A row is just an arbitrary python
data structure, which must be something that can be stored and
retrieved by the RowSerializer. A row can be anything, but often
the top-level structure is a python tuple (a,b,c,...) or a dict
mapping small integers 0,1,... to different parts of the row.
A guineapig "planner" knows how to construct "plans" that store
materialized relations on disk. These plans sometimes include
creating 'checkpoints', which are things places on disk, often
stored materialized relations, or sometimes intermediate outputs
or these."""
def __init__(self):
"""The planner and tag must be set before this is used."""
self.planner = None #pointer to planner object
self.tag = None #for naming storedFile and checkpoints
self.storeMe = None #try and store this view if true
self.retainedPart = None #used in map-reduce views only
#
# ways to modify a view
#
def opts(self,stored=None):
"""Return the same view with options set appropriately.e"""
self.storeMe = stored
return self
def showExtras(self):
"""Printable representation of the options for a view."""
result = ''
flagPairs = []
if self.storeMe: flagPairs += ['stored=%s' % repr(self.storeMe)]
if flagPairs: result += '.opts(' + ",".join(flagPairs) + ')'
return result
#
# how the view is saved on disk
#
def storedFile(self):
"""The file that will hold the materialized relation."""
return self.planner.opts['viewdir'] + '/' + self.tag + '.gp'
def distributableFile(self):
"""The file that will hold the materialized relation in the working directory
in preparation to be uploaded to the distributed cache."""
return self.tag + '.gp'
@staticmethod
def viewNameFor(fileName):
"""The view associated with the given file name"""
vname = os.path.basename(fileName)
if vname.endswith(".gp"): vname = vname[0:-len(".gp")]
elif vname.endswith(".done"): vname = vname[0:-len(".done")]
return vname
#
# semantics of the view
#
def checkpoint(self):
"""A checkpoint is a file that is created in the course of
materializing a view. This function is the latest checkpoint
from which the the relation can be materialized."""
if self.storeMe: return self.storedFile()
else: return self.unstoredCheckpoint()
def unstoredCheckpoint(self):
"""Checkpoint for this view, if the storeMe flag is not set."""
assert False, 'abstract method called'
def checkpointPlan(self):
"""A plan to produce checkpoint(). Plans are constructed with the
help of the planner, and steps in the plan are executed by
delegation, thru the planner, to methods of this class named
doFoo."""
if self.storeMe: return self.storagePlan()
else: return self.unstoredCheckpointPlan()
def unstoredCheckpointPlan(self):
"""Plan to produce the checkpoint for this view, if the
storeMe flag is not set."""
assert False, 'abstract method called'
def rowGenerator(self):
"""A generator for the rows in this relation."""
if self.storeMe and (self.tag in self.planner.alreadyStored):
for line in sys.stdin:
yield self.planner._serializer.fromString(line.strip())
else:
for row in self.unstoredRowGenerator():
yield row
def explanation(self):
"""Return an explanation of how rows are generated."""
if self.storeMe and (self.tag in self.planner.viewsPlannedToExist):
return ['read %s with %s' % (self.storedFile(),self.tag)]
else:
return self.unstoredExplanation()
def unstoredExplanation(self):
"""Return an explanation of how rows were generated, ignoring caching issues."""
assert False,'abstract method called'
def storagePlan(self):
"""A plan to materialize the relation. """
if self.storeMe and self.tag in self.planner.viewsPlannedToExist:
return Plan()
else:
#WARNING: these computations have to be done in the right order, since planning has the side effect of updating
#the filePlannedToExist predicate.
# 1) build the pre-plan, to set up the view's checkpoints
plan = self.unstoredCheckpointPlan()
# 2a) compute the next step of the plan, along with the explanation
step = Step(self,'doStoreRows',self.unstoredCheckpoint(),self.storedFile(),
why=self.explanation(),
existingViews=set(self.planner.viewsPlannedToExist)) #shallow copy of current state
result = plan.extend( step )
# 2b) if necessary, add a step to upload the
# 3) Record that this file has been stored for lated calls to explanation() and storagePlan()
logging.debug('marking %s as planned-to-exist' % self.tag)
self.planner.viewsPlannedToExist.add(self.tag)
# 4) return the result
return result
def doStoreRows(self):
"""Called by planner at execution time to store the rows of the view."""
for row in self.rowGenerator():
print self.planner._serializer.toString(row)
#
# traversing and defining views
#
def innerViews(self):
"""List of all views that are used as direct inputs."""
return []
def nonInnerPrereqViews(self):
"""List any non-inner views that need to be created before the view is executed."""
return []
def __or__(self,otherView):
"""Overload the pipe operator x | y to return with y, with x as its inner view."""
otherView.acceptInnerView(self)
return otherView
def acceptInnerView(self,otherView):
"""Replace an appropriate input view with otherView. To be
used with the pipe operator."""
assert False,'abstract method called'
#
# meta plans - sequence of store commands
#
def metaplan(self,previouslyExistingViews):
plannedViews = set(previouslyExistingViews) #copy
return self._metaplanTraverse(plannedViews) + [self.tag]
def _metaplanTraverse(self,plannedViews):
mplan = []
try:
sideInnerviews = self.sideviews
except AttributeError:
sideInnerviews = []
for inner in self.innerViews() + sideInnerviews:
if not inner.tag in plannedViews:
mplan += inner._metaplanTraverse(plannedViews)
if inner.storeMe:
mplan += [inner.tag]
plannedViews.add(inner.tag)
return mplan
#
# printing views
#
def pprint(self,depth=0,alreadyPrinted=None,sideview=False):
"""Print a readable representation of the view."""
if alreadyPrinted==None: alreadyPrinted = set()
tabStr = '| ' * depth
tagStr = str(self.tag)
sideviewIndicator = '*' if sideview else ''
if self in alreadyPrinted:
print tabStr + sideviewIndicator + tagStr + ' = ' + '...'
else:
sideViewInfo = " sideviews: {"+",".join(map(lambda x:x.tag, self.nonInnerPrereqViews()))+"}" if self.nonInnerPrereqViews() else ""
print tabStr + sideviewIndicator + tagStr + ' = ' + str(self) + sideViewInfo
alreadyPrinted.add(self)
for inner in self.innerViews():
inner.pprint(depth+1,alreadyPrinted)
try:
for inner in self.sideviews:
inner.pprint(depth+1,alreadyPrinted,sideview=True)
except AttributeError:
pass
@staticmethod
def asTag(view):
"""Helper for printing views."""
if not view: return '(null view)'
elif view.tag: return view.tag
else: return str(view)
#
# abstract view types
#
class Reader(View):
"""Wrapper around a stored file relation."""
def __init__(self,src):
View.__init__(self)
self.src = src
def unstoredCheckpoint(self):
return self.src
def unstoredCheckpointPlan(self):
return Plan()
def unstoredExplanation(self):
return [ 'read %s with %s' % (str(self.src),self.tag) ]
class Transformation(View):
"""A relation that takes an inner relation and processes in a
stream-like way, including operators like project, flatten,
select."""
def __init__(self,inner=None):
View.__init__(self)
self.inner = inner
def innerViews(self):
return [self.inner]
def nonInnerPrereqViews(self):
assert self.inner, 'no inner view defined for ' + str(self)
return self.inner.nonInnerPrereqViews()
def acceptInnerView(self,otherView):
assert not self.inner,'An inner view is defined for '+self.tag+' so you cannot use it as RHS of a pipe'
self.inner = otherView
# The transformation will stream through the inner relation,
# and produce a new version, so the latest checkpoint and
# plan to produce it are delegated to the inner View.
def unstoredCheckpoint(self):
return self.inner.checkpoint()
def unstoredCheckpointPlan(self):
plan = Plan()
plan.append(self.inner.checkpointPlan())
return plan
def unstoredExplanation(self):
return self.inner.explanation() + [ 'transform to %s' % self.tag ]
class MapReduce(View):
"""A view that takes an inner relation and processes in a
map-reduce-like way."""
def __init__(self,inners,retaining):
View.__init__(self)
self.inners = inners
self.retainedPart = retaining
def innerViews(self):
return self.inners
def nonInnerPrereqViews(self):
result = []
for inner in self.inners:
result += inner.nonInnerPrereqViews()
return result
def reduceInputFile(self):
## the checkpoint is the reducer input file
return self.planner.opts['viewdir'] + '/' + self.tag + '.gpri'
@staticmethod
def isReduceInputFile(fileName):
return fileName.endswith('.gpri')
def unstoredCheckpoint(self):
return self.reduceInputFile()
def unstoredCheckpointPlan(self):
plan = Plan()
for inner in self.inners:
plan = plan.append(inner.checkpointPlan())
return plan.append(self.mapPlan())
def innerCheckpoints(self):
result = []
for inner in self.inners:
result += [inner.checkpoint()]
return result
def mapPlan(self):
log.error("abstract method not implemented")
def doStoreKeyedRows(self,subview,key,index):
"""Utility method to compute keys and store key-value pairs. Usually
used as the main step in a mapPlan. """
for row in subview.rowGenerator():
keyStr = self.planner._serializer.toString(key(row))
rrow = self.retainedPart(row) if self.retainedPart else row
valStr = self.planner._serializer.toString(rrow)
if index<0:
print "%s\t%s" % (keyStr,valStr)
else:
print "%s\t%d\t%s" % (keyStr,index,valStr)
##############################################################################
#
# concrete View classes
#
##############################################################################
class ReadLines(Reader):
""" Returns the lines in a file, as python strings."""
def __init__(self,src):
Reader.__init__(self,src)
def unstoredRowGenerator(self):
for line in sys.stdin:
yield line
def __str__(self):
return 'ReadLines("%s")' % self.src + self.showExtras()
class ReadCSV(Reader):
""" Returns the lines in a CSV file, converted to Python tuples."""
def __init__(self,src,**kw):
Reader.__init__(self,src)
self.kw = kw
def unstoredRowGenerator(self):
for tup in csv.reader(sys.stdin,**self.kw):
yield tup
def __str__(self):
return 'ReadCVS("%s",%s)' % (self.src,str(self.kw)) + self.showExtras()
class ReplaceEach(Transformation):
""" In 'by=f'' f is a python function that takes a row and produces
its replacement."""
def __init__(self,inner=None,by=lambda x:x):
Transformation.__init__(self,inner)
self.replaceBy = by
def unstoredRowGenerator(self):
for row in self.inner.rowGenerator():
yield self.replaceBy(row)
def unstoredExplanation(self):
return self.inner.explanation() + [ 'replaced to %s' % self.tag ]
def __str__(self):
return 'ReplaceEach(%s, by=%s)' % (View.asTag(self.inner),str(self.replaceBy)) + self.showExtras()
class Augment(Transformation):
def __init__(self,inner=None,sideviews=None,sideview=None,loadedBy=lambda v:list(GPig.rowsOf(v))):
Transformation.__init__(self,inner)
assert not (sideviews and sideview), 'cannot specify both "sideview" and "sideviews"'
self.sideviews = list(sideviews) if sideviews else [sideview]
self.loader = loadedBy
assert self.loader,'must specify a "loadedBy" function for Augment'
def nonInnerPrereqViews(self):
return self.inner.nonInnerPrereqViews() + self.sideviews
def unstoredRowGenerator(self):
augend = self.loader(*self.sideviews)
for row in self.inner.rowGenerator():
yield (row,augend)
def unstoredCheckpointPlan(self):
plan = Plan()
for sv in self.sideviews:
plan = plan.append(sv.storagePlan())
plan = plan.extend(Step(sv, 'DISTRIBUTE'))
plan.append(self.inner.checkpointPlan())
return plan
def unstoredExplanation(self):
return self.inner.explanation() + [ 'augmented to %s' % self.tag ]
def __str__(self):
sideviewTags = loaderTag = '*UNSPECIFIED*'
if self.sideviews!=None:
sideviewTags = ",".join(map(View.asTag,self.sideviews))
if self.loader!=None:
loaderTag = str(self.loader)
return 'Augment(%s,sideviews=%s,loadedBy=s%s)' % (View.asTag(self.inner),sideviewTags,loaderTag) + self.showExtras()
class Format(ReplaceEach):
""" Like ReplaceEach, but output should be a string, and it will be be
stored as strings, ie without using the serializer."""
def __init__(self,inner=None,by=lambda x:str(x)):
ReplaceEach.__init__(self,inner,by)
def doStoreRows(self):
for row in self.rowGenerator():
print row
def __str__(self):
return 'Format(%s, by=%s)' % (View.asTag(self.inner),str(self.replaceBy)) + self.showExtras()
class Flatten(Transformation):
""" Example:
def idwordGen(row):
for w in row['words']: yield (row['id'],w)
x = gp.Flatten(y, by=idwordGen(row))
In 'by=f', f is a python function that takes a row and yields
multiple new rows. """
def __init__(self,inner=None,by=None):
Transformation.__init__(self,inner)
self.flattenBy = by
def unstoredRowGenerator(self):
for row in self.inner.rowGenerator():
for flatrow in self.flattenBy(row):
yield flatrow
def unstoredExplanation(self):
return self.inner.explanation() + [ 'flatten to %s' % self.tag ]
def __str__(self):
return 'Flatten(%s, by=%s)' % (View.asTag(self.inner),str(self.flattenBy)) + self.showExtras()
class Filter(Transformation):
"""Filter out a subset of rows that match some predicate."""
def __init__(self,inner=None,by=lambda x:x):
Transformation.__init__(self,inner)
self.filterBy = by
def unstoredRowGenerator(self):
for row in self.inner.rowGenerator():
if self.filterBy(row):
yield row
def unstoredExplanation(self):
return self.inner.explanation() + [ 'filtered to %s' % self.tag ]
def __str__(self):
return 'Filter(%s, by=%s)' % (View.asTag(self.inner),str(self.filterBy)) + self.showExtras()
class Distinct(MapReduce):
"""Remove duplicate rows."""
def __init__(self,inner=None,retaining=None):
MapReduce.__init__(self,[inner],retaining)
self.inner = inner
def acceptInnerView(self,otherView):
assert not self.inner,'An inner view is defined for '+self.tag+' so you cannot use it as RHS of a pipe'
self.inner = otherView
self.inners = [self.inner]
def mapPlan(self):
step = Step(self, 'doDistinctMap', self.inner.checkpoint(), self.checkpoint(), prereduce=True,
why=self.explanation(),
existingViews=set(self.planner.viewsPlannedToExist)) #shallow of current state
return Plan().extend(step)
def doDistinctMap(self):
# called by groupMapAndSortStep
self.inner.doStoreRows()
def unstoredRowGenerator(self):
"""Extract distinct elements from a sorted list."""
lastval = None
for line in sys.stdin:
valStr = line.strip()
val = self.planner._serializer.fromString(valStr)
if val != lastval and lastval:
yield lastval
lastval = val
if lastval:
yield lastval
def unstoredExplanation(self):
return self.inner.explanation() + [ 'make distinct to %s' % self.tag]
def __str__(self):
return 'Distinct(%s)' % (View.asTag(self.inner)) + self.showExtras()
class Group(MapReduce):
"""Group by some property of a row, defined with the 'by' option.
Default outputs are tuples (x,[r1,...,rk]) where the ri's are rows
that have property values of x."""
def __init__(self,inner=None,by=lambda x:x,reducingTo=ReduceToList(),retaining=None):
MapReduce.__init__(self,[inner],retaining)
self.inner = inner
self.groupBy = by
self.reducingTo = reducingTo
def acceptInnerView(self,otherView):
assert not self.inner,'An inner view is defined for '+self.tag+' so you cannot use it as RHS of a pipe'
self.inner = otherView
self.inners = [self.inner]
def mapPlan(self):
step = Step(self, 'doGroupMap',self.inner.checkpoint(),self.checkpoint(),prereduce=True,
why=self.explanation(),
existingViews=set(self.planner.viewsPlannedToExist)) #shallow copy of current state
return Plan().extend(step)
def doGroupMap(self):
# called by groupMapAndSortStep
self.doStoreKeyedRows(self.inner,self.groupBy,-1)
def unstoredRowGenerator(self):
"""Group objects from stdin by key, yielding tuples (key,[g1,..,gn])."""
lastkey = key = None
accum = self.reducingTo.baseType()
for line in sys.stdin:
keyStr,valStr = line.strip().split("\t")
key = self.planner._serializer.fromString(keyStr)
val = self.planner._serializer.fromString(valStr)
if key != lastkey and lastkey!=None:
yield (lastkey,accum)
accum = self.reducingTo.baseType()
accum = self.reducingTo.reduceBy(accum, val)
lastkey = key
if key:
yield (key,accum)
def unstoredExplanation(self):
return self.inner.explanation() + ['group to %s' % self.tag]
def __str__(self):
return 'Group(%s,by=%s,reducingTo=%s)' % (View.asTag(self.inner),str(self.groupBy),str(self.reducingTo)) + self.showExtras()
class Join(MapReduce):
"""Outputs tuples of the form (row1,row2,...rowk) where
rowi is from the i-th join input, and the rowi's have the same
value of the property being joined on."""
def __init__(self,*joinInputs):
#sets self.inners
MapReduce.__init__(self,map(lambda x:x.view, joinInputs),None)
self.joinInputs = joinInputs
#re-interpret the 'outer' join parameters - semantically
#if jin[i] is outer, then all other inputs must be marked as _padWithNulls
if any(map(lambda jin:jin.outer, self.joinInputs)):
assert len(self.joinInputs)==2,'outer joins are only supported on two-way joins '+str(self.joinInputs)
for i in range(len(self.joinInputs)):
if self.joinInputs[i].outer:
j = 1-i #the other index
self.joinInputs[j]._padWithNulls = True
def acceptInnerView(self,otherView):
assert self.unpairedJoinBy, 'join cannot be RHS of a pipe'
#assert self.unpairedJoinBy, 'join can only be RHS of a pipe if it contains a "by" argument not inside a "Jin" join-input'
#self.joinInputs = joinInputs + [Jin(otherView,by=unpairedJoinBy)]
#self.inners = map(lambda x:x.view, self.joinInputs)
def mapPlan(self):
previousCheckpoints = self.innerCheckpoints()
midfile = self.planner.opts['viewdir'] + '/' + self.tag+'.gpmo'
step = Step(self, 'doJoinMap', src=previousCheckpoints, dst=self.checkpoint(), prereduce=True, hasIndex=True, mid=midfile,
existingViews=set(self.planner.viewsPlannedToExist), #shallow copy of current state
why=self.explanation())
return Plan().extend(step)
def doJoinMap(self,i):
# called by joinMapPlan with argument index, and stdin pointing to previousCheckpoints[index]
self.doStoreKeyedRows(self.joinInputs[i].view,self.joinInputs[i].joinBy,i)
def unstoredRowGenerator(self):
"""Group objects from stdin by key, yielding tuples (row1,row2,...)."""
lastkey = None
lastIndex = len(self.joinInputs)-1
somethingProducedForLastKey = False
#accumulate a list of lists of all non-final inputs
accumList = [ [] for i in range(lastIndex) ]
for line in sys.stdin:
keyStr,indexStr,valStr = line.strip().split("\t")
key = self.planner._serializer.fromString(keyStr)
index = int(indexStr)
val = self.planner._serializer.fromString(valStr)
if key != lastkey and lastkey!=None:
#if the final join is marked as _padWithNulls, clear
#the accumulators, since we're doing an outer join
#with the last view
if self.joinInputs[lastIndex]._padWithNulls and not somethingProducedForLastKey:
for tup in self._joinAccumulatedValuesTo(accumList,lastIndex,None):
yield tup
#reset the accumulators, since they pertain to the
accumList = [ [] for i in range(lastIndex) ]
somethingProducedForLastKey = False
if index!=lastIndex:
#accumulate values to use in the join
accumList[index] = accumList[index] + [val]
else:
#produce tuples that match the key for the last view
for tup in self._joinAccumulatedValuesTo(accumList,lastIndex,val):
somethingProducedForLastKey = True
yield tup
lastkey = key
def _joinAccumulatedValuesTo(self,accumList,lastIndex,finalVal):
# _padWithNulls as needed
for i in range(lastIndex):
if self.joinInputs[i]._padWithNulls and not accumList[i]:
accumList[i] = [None]
tupbuf = [ None for i in range(lastIndex+1) ] #holds output
tupbuf[lastIndex] = finalVal
for i in range(lastIndex):
for a in accumList[i]:
tupbuf[i] = a
if i==lastIndex-1 and any(tupbuf):
yield tuple(tupbuf)
def unstoredExplanation(self):
innerEx = []
for inner in self.inners:
if innerEx: innerEx += ['THEN']
innerEx += inner.explanation()
return innerEx + [ 'FINALLY join to %s' % self.tag ]
def __str__(self):
return "Join(%s)" % ",".join(map(str,self.joinInputs)) + self.showExtras()
class JoinTo(Join):
"""Special case of Join which can be used as the RHS of a pipe operator."""
def __init__(self,joinInput,by=None):
Join.__init__(self,Jin(None,by),joinInput)
def acceptInnerView(self,otherView):
self.joinInputs[0].view = otherView
self.inners[0] = otherView
##############################################################################
#
# the top-level planner, and its supporting classes
#
##############################################################################
class Plan(object):
"""A plan constructed by a GuineaPig."""
def __init__(self): self.steps = []
def extend(self,step):
self.steps += [step]
return self
def append(self,subPlan):
self.steps += subPlan.steps
return self
def execute(self,gp,echo=False):
script = self.compile(gp)
for shellcom in script:
if echo: print 'calling:',shellcom
subprocess.check_call(shellcom,shell=True)
def compile(self,gp):
"""Return a list of strings that can be run as shell commands."""
script = []
i = 0
while (i<len(self.steps)):
s = self.steps[i]
i += 1
if s.whatToDo=='DISTRIBUTE':
script += s.distribute(gp)
elif not s.prereduce:
script += s.mapOnlySubscript(gp)
else:
reduceStep = self.steps[i]
assert not reduceStep.prereduce, 'chained mapreduce steps:' + str(s) + str(reduceStep)
i += 1
if s.src.__class__ != [].__class__:
script += s.mapReduceSubscript(reduceStep,gp)
else:
script += s.multiMapReduceSubscript(reduceStep,gp)
return script
class Step(object):
"""Steps for the planner."""
def __init__(self,view,whatToDo,src=None,dst=None,prereduce=False,hasIndex=False,mid=None,why=[],existingViews=set()):
"""Arguments:
- view is view that created this step
- whatToDo is the operator, eg doStoreKeyedRows, or else DISTRIBUTE
- existingViews is a set of views that are expected to be already stored
- src is the file used as input, or possibly a LIST of files if there are multiple inputs
- dst is the file used as output
- mid is a file used as tmp storage for an unsorted version of output, if needed
- prereduce is True iff this is a checkpoint in a map-reduce step
- hasIndex is True iff the data is of the form <key,index,value> such that
items should be partitioned by key and sorted by index
- why is documentation/explanation. """
self.view = view
self.whatToDo = whatToDo
self.existingViews = existingViews
self.src = src
self.dst = dst
self.prereduce = prereduce
self.hasIndex = hasIndex
self.mid = mid
self.why = why
def __str__(self):
return repr(self)
def __repr__(self):
return "Step('%s','%s',src=%s,dst='%s',prereduce=%s,mid=%s,why=%s,existingViews=%s)" \
% (self.view.tag,self.whatToDo,repr(self.src),
self.dst,repr(self.prereduce),repr(self.mid),repr(self.explain()),repr(self.existingViews))
def explain(self):
"""Convert an explanation - which is a list of strings - into a string"""
return "...".join(self.why)
# actual code generation for the steps
class HadoopCommand(object):
def __init__(self,gp,view):
self.invocation = [GPig.HADOOP_LOC,'jar',gp.opts['streamJar']]
self.defs = []
self.args = []
self.files = []
for f in gp._shippedFiles:
self.files += ['-file',f]
for v in view.nonInnerPrereqViews():
self.files += ['-file',v.distributableFile()]
def append(self,*toks):
self.args += list(toks)
def appendDef(self,*toks):
self.defs += list(toks)
def asEcho(self):
return " ".join(['echo','hadoop'] + self.args + ['...'])
def asString(self):
return " ".join(self.invocation+self.defs+self.files+self.args)
def subplanHeader(self,reduceStep=None):
"""Generate an explanatory header for a step."""
if not reduceStep: return ['#', 'echo map '+self.view.tag + ': '+self.explain()]
else: return ['#', 'echo map/reduce '+self.view.tag+ '/'+ reduceStep.view.tag + ': '+reduceStep.explain()]
def coreCommand(self,gp):
"""Python command to call an individual plan step."""
return 'python %s --view=%s --do=%s' % (gp._gpigSourceFile,self.view.tag,self.whatToDo) + self.coreCommandOptions(gp)
def ithCoreCommand(self,gp,i):
"""Like coreCommand but allows index parameter to 'do' option"""
return 'python %s --view=%s --do=%s.%d' % (gp._gpigSourceFile,self.view.tag,self.whatToDo,i) + self.coreCommandOptions(gp)
def coreCommandOptions(self,gp):
paramOpts = '' if not gp.param else " --params " + ",".join(map(lambda(k,v):k+':'+v, gp.param.items()))
alreadyStoredOpts = '' if not self.existingViews else " --alreadyStored "+",".join(self.existingViews)
nonDefaults = []
for (k,v) in gp.opts.items():
#pass in non-default options, or options computed from the environment
if (gp.opts[k] != GPig.DEFAULT_OPTS[k]) or ((k in GPig.COMPUTED_OPTION_DEFAULTS) and (gp.opts[k] != GPig.COMPUTED_OPTION_DEFAULTS[k])):
nonDefaults += ["%s:%s" % (k,str(v))]
optsOpts = '' if not nonDefaults else " --opts " + ",".join(nonDefaults)
return paramOpts + optsOpts + alreadyStoredOpts
def hadoopClean(self,gp,fileName):
"""A command to remove a hdfs directory if it exists."""
return '(%s fs -test -e %s && %s fs -rmr %s) || echo no need to remove %s' % (GPig.HADOOP_LOC,fileName, GPig.HADOOP_LOC,fileName, fileName)
def distribute(self,gp):
"""Make a view availablefor use as a side view."""
localCopy = self.view.distributableFile()
maybeRemoteCopy = self.view.storedFile()
echo = 'echo making a local copy of %s in %s' % (maybeRemoteCopy,localCopy)
if gp.opts['target']=='hadoop':
return [echo, 'rm -f %s' % localCopy, '%s fs -getmerge %s %s' % (GPig.HADOOP_LOC,maybeRemoteCopy, localCopy)]
else:
return [echo, 'cp -f %s %s || echo warning: the copy failed!' % (maybeRemoteCopy,localCopy)]
def mapOnlySubscript(self,gp):
"""A subplan for a mapper-only step."""
if gp.opts['target']=='shell':
command = None
if self.src: command = self.coreCommand(gp) + ' < %s > %s' % (self.src,self.dst)
else: command = self.coreCommand(gp) + (' > %s' % (self.dst))
return self.subplanHeader() + [command]
elif gp.opts['target']=='hadoop':
assert self.src,'Wrap not supported for hadoop'
hcom = self.HadoopCommand(gp,self.view)
hcom.appendDef('-D','mapred.reduce.tasks=0')
hcom.append('-input',self.src,'-output',self.dst)
hcom.append("-mapper '%s'" % self.coreCommand(gp))
return self.subplanHeader() + [ hcom.asEcho(), self.hadoopClean(gp,self.dst), hcom.asString() ]
else:
assert False
def mapReduceSubscript(self,reduceStep,gp):
"""A subplan for a map-reduce step followed by a reduce, where the map has one input."""
if gp.opts['target']=='shell':
command = self.coreCommand(gp) + (' < %s' % self.src) + ' | sort -k1 | '+reduceStep.coreCommand(gp) + (' > %s' % reduceStep.dst)
return self.subplanHeader(reduceStep) + [command]
elif gp.opts['target']=='hadoop':
hcom = self.HadoopCommand(gp,self.view)
hcom.appendDef('-D','mapred.reduce.tasks=%d' % gp.opts['parallel'])
hcom.append('-input',self.src, '-output',reduceStep.dst)
hcom.append("-mapper '%s'" % self.coreCommand(gp))
hcom.append("-reducer '%s'" % reduceStep.coreCommand(gp))
return self.subplanHeader(reduceStep) + [ hcom.asEcho(), self.hadoopClean(gp,reduceStep.dst), hcom.asString() ]
else:
assert False
def multiMapReduceSubscript(self,reduceStep,gp):
"""A subplan for a map-reduce step followed by a reduce, where the map has many inputs."""
if gp.opts['target']=='shell':
subplan = ['rm -f %s' % self.mid]
for i in range(len(self.src)):
subplan += [ self.ithCoreCommand(gp,i) + ' < %s >> %s' % (self.src[i],self.mid) ]
sortOpts = '-k1,2' if self.hasIndex else '-k1'
subplan += [ 'sort ' + sortOpts + ' < ' + self.mid + ' | ' + reduceStep.coreCommand(gp) + (' > %s' % reduceStep.dst)]
return self.subplanHeader(reduceStep) + subplan
elif gp.opts['target']=='hadoop':
def midi(i): return self.mid + '-' + str(i)
subplan = []
for i in range(len(self.src)):
hcom = self.HadoopCommand(gp,self.view)
hcom.appendDef('-D','mapred.reduce.tasks=%d' % gp.opts['parallel'])
hcom.append('-input',self.src[i], '-output',midi(i))
hcom.append("-mapper","'%s'" % self.ithCoreCommand(gp,i))
subplan += [ self.hadoopClean(gp,midi(i)), hcom.asEcho(), hcom.asString() ]
hcombineCom = self.HadoopCommand(gp,self.view)
hcombineCom.appendDef('-D','mapred.reduce.tasks=%d' % gp.opts['parallel'])
if (self.hasIndex):
hcombineCom.appendDef('-jobconf','stream.num.map.output.key.fields=3')
hcombineCom.appendDef('-jobconf','num.key.fields.for.partition=1')
for i in range(len(self.src)):
hcombineCom.append('-input',midi(i))
hcombineCom.append('-output',reduceStep.dst)
hcombineCom.append('-mapper','cat')
hcombineCom.append('-reducer',"'%s'" % reduceStep.coreCommand(gp))
if (self.hasIndex):
hcombineCom.append('-partitioner','org.apache.hadoop.mapred.lib.KeyFieldBasedPartitioner')
subplan += [ self.hadoopClean(gp,reduceStep.dst), hcombineCom.asEcho(), hcombineCom.asString() ]
return self.subplanHeader(reduceStep) + subplan
else:
assert False
class RowSerializer(object):
"""Saves row objects to disk and retrieves them."""
def __init__(self,target):
self._target = target
self._reprInverse = None
def toString(self,x):
return repr(x)
def fromString(self,s):
if self._reprInverse: return self._reprInverse(s)
else: return eval(s)
#
# the planner
#