/
operations.py
1529 lines (1302 loc) · 55.5 KB
/
operations.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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
# cython: language_level=3
# cython: profile=True
"""Worker operations executor."""
# pytype: skip-file
# pylint: disable=super-with-arguments
import collections
import logging
import threading
import warnings
from typing import TYPE_CHECKING
from typing import Any
from typing import DefaultDict
from typing import Dict
from typing import FrozenSet
from typing import Hashable
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from apache_beam import coders
from apache_beam.internal import pickler
from apache_beam.io import iobase
from apache_beam.metrics import monitoring_infos
from apache_beam.metrics.cells import DistributionData
from apache_beam.metrics.execution import MetricsContainer
from apache_beam.portability.api import metrics_pb2
from apache_beam.runners import common
from apache_beam.runners.common import Receiver
from apache_beam.runners.worker import opcounters
from apache_beam.runners.worker import operation_specs
from apache_beam.runners.worker import sideinputs
from apache_beam.runners.worker.data_sampler import DataSampler
from apache_beam.transforms import sideinputs as apache_sideinputs
from apache_beam.transforms import combiners
from apache_beam.transforms import core
from apache_beam.transforms import userstate
from apache_beam.transforms import window
from apache_beam.transforms.combiners import PhasedCombineFnExecutor
from apache_beam.transforms.combiners import curry_combine_fn
from apache_beam.transforms.window import GlobalWindows
from apache_beam.typehints.batch import BatchConverter
from apache_beam.utils.windowed_value import WindowedBatch
from apache_beam.utils.windowed_value import WindowedValue
if TYPE_CHECKING:
from apache_beam.runners.sdf_utils import SplitResultPrimary
from apache_beam.runners.sdf_utils import SplitResultResidual
from apache_beam.runners.worker.bundle_processor import ExecutionContext
from apache_beam.runners.worker.data_sampler import OutputSampler
from apache_beam.runners.worker.statesampler import StateSampler
from apache_beam.transforms.userstate import TimerSpec
# Allow some "pure mode" declarations.
try:
import cython
except ImportError:
class FakeCython(object):
compiled = False
globals()['cython'] = FakeCython()
_globally_windowed_value = GlobalWindows.windowed_value(None)
_global_window_type = type(_globally_windowed_value.windows[0])
_LOGGER = logging.getLogger(__name__)
SdfSplitResultsPrimary = Tuple['DoOperation', 'SplitResultPrimary']
SdfSplitResultsResidual = Tuple['DoOperation', 'SplitResultResidual']
# TODO(BEAM-9324) Remove these workarounds once upgraded to Cython 3
def _cast_to_operation(value):
if cython.compiled:
return cython.cast(Operation, value)
else:
return value
# TODO(BEAM-9324) Remove these workarounds once upgraded to Cython 3
def _cast_to_receiver(value):
if cython.compiled:
return cython.cast(Receiver, value)
else:
return value
class ConsumerSet(Receiver):
"""A ConsumerSet represents a graph edge between two Operation nodes.
The ConsumerSet object collects information from the output of the
Operation at one end of its edge and the input of the Operation at
the other edge.
ConsumerSet are attached to the outputting Operation.
"""
@staticmethod
def create(counter_factory,
step_name, # type: str
output_index,
consumers, # type: List[Operation]
coder,
producer_type_hints,
producer_batch_converter, # type: Optional[BatchConverter]
output_sampler=None, # type: Optional[OutputSampler]
):
# type: (...) -> ConsumerSet
if len(consumers) == 1:
consumer = consumers[0]
consumer_batch_preference = consumer.get_batching_preference()
consumer_batch_converter = consumer.get_input_batch_converter()
if (not consumer_batch_preference.supports_batches and
producer_batch_converter is None and
consumer_batch_converter is None):
return SingletonElementConsumerSet(
counter_factory,
step_name,
output_index,
consumer,
coder,
producer_type_hints,
output_sampler)
return GeneralPurposeConsumerSet(
counter_factory,
step_name,
output_index,
coder,
producer_type_hints,
consumers,
producer_batch_converter,
output_sampler)
def __init__(self,
counter_factory,
step_name, # type: str
output_index,
consumers,
coder,
producer_type_hints,
producer_batch_converter,
output_sampler
):
self.opcounter = opcounters.OperationCounters(
counter_factory,
step_name,
coder,
output_index,
producer_type_hints=producer_type_hints,
producer_batch_converter=producer_batch_converter)
# Used in repr.
self.step_name = step_name
self.output_index = output_index
self.coder = coder
self.consumers = consumers
self.output_sampler = output_sampler
self.element_sampler = (
output_sampler.element_sampler if output_sampler else None)
self.execution_context = None # type: Optional[ExecutionContext]
def try_split(self, fraction_of_remainder):
# type: (...) -> Optional[Any]
# TODO(SDF): Consider supporting splitting each consumer individually.
# This would never come up in the existing SDF expansion, but might
# be useful to support fused SDF nodes.
# This would require dedicated delivery of the split results to each
# of the consumers separately.
return None
def current_element_progress(self):
# type: () -> Optional[iobase.RestrictionProgress]
"""Returns the progress of the current element.
This progress should be an instance of
apache_beam.io.iobase.RestrictionProgress, or None if progress is unknown.
"""
# TODO(SDF): Could implement this as a weighted average, if it becomes
# useful to split on.
return None
def update_counters_start(self, windowed_value):
# type: (WindowedValue) -> None
self.opcounter.update_from(windowed_value)
if self.execution_context is not None:
self.execution_context.output_sampler = self.output_sampler
# The following code is optimized by inlining a function call. Because this
# is called for every element, a function call is too expensive (order of
# 100s of nanoseconds). Furthermore, a lock was purposefully not used
# between here and the DataSampler as an additional operation. The tradeoff
# is that some samples might be dropped, but it is better than the
# alternative which is double sampling the same element.
if self.element_sampler is not None:
if not self.element_sampler.has_element:
self.element_sampler.el = windowed_value
self.element_sampler.has_element = True
def update_counters_finish(self):
# type: () -> None
self.opcounter.update_collect()
def update_counters_batch(self, windowed_batch):
# type: (WindowedBatch) -> None
self.opcounter.update_from_batch(windowed_batch)
def __repr__(self):
return '%s[%s.out%s, coder=%s, len(consumers)=%s]' % (
self.__class__.__name__,
self.step_name,
self.output_index,
self.coder,
len(self.consumers))
class SingletonElementConsumerSet(ConsumerSet):
"""ConsumerSet representing a single consumer that can only process elements
(not batches)."""
def __init__(self,
counter_factory,
step_name,
output_index,
consumer, # type: Operation
coder,
producer_type_hints,
output_sampler
):
super().__init__(
counter_factory,
step_name,
output_index, [consumer],
coder,
producer_type_hints,
None,
output_sampler)
self.consumer = consumer
def receive(self, windowed_value):
# type: (WindowedValue) -> None
self.update_counters_start(windowed_value)
self.consumer.process(windowed_value)
self.update_counters_finish()
def receive_batch(self, windowed_batch):
raise AssertionError(
"SingletonElementConsumerSet.receive_batch is not implemented")
def flush(self):
# SingletonElementConsumerSet has no buffer to flush
pass
def try_split(self, fraction_of_remainder):
# type: (...) -> Optional[Any]
return self.consumer.try_split(fraction_of_remainder)
def current_element_progress(self):
return self.consumer.current_element_progress()
class GeneralPurposeConsumerSet(ConsumerSet):
"""ConsumerSet implementation that handles all combinations of possible edges.
"""
MAX_BATCH_SIZE = 4096
def __init__(self,
counter_factory,
step_name, # type: str
output_index,
coder,
producer_type_hints,
consumers, # type: List[Operation]
producer_batch_converter,
output_sampler):
super().__init__(
counter_factory,
step_name,
output_index,
consumers,
coder,
producer_type_hints,
producer_batch_converter,
output_sampler)
self.producer_batch_converter = producer_batch_converter
# Partition consumers into three groups:
# - consumers that will be passed elements
# - consumers that will be passed batches (where their input batch type
# matches the output of the producer)
# - consumers that will be passed converted batches
self.element_consumers: List[Operation] = []
self.passthrough_batch_consumers: List[Operation] = []
other_batch_consumers: DefaultDict[
BatchConverter, List[Operation]] = collections.defaultdict(lambda: [])
for consumer in consumers:
if not consumer.get_batching_preference().supports_batches:
self.element_consumers.append(consumer)
elif (consumer.get_input_batch_converter() ==
self.producer_batch_converter):
self.passthrough_batch_consumers.append(consumer)
else:
# Batch consumer with a mismatched batch type
if consumer.get_batching_preference().supports_elements:
# Pass it elements if we can
self.element_consumers.append(consumer)
else:
# As a last resort, explode and rebatch
consumer_batch_converter = consumer.get_input_batch_converter()
# This consumer supports batches, it must have a batch converter
assert consumer_batch_converter is not None
other_batch_consumers[consumer_batch_converter].append(consumer)
self.other_batch_consumers: Dict[BatchConverter, List[Operation]] = dict(
other_batch_consumers)
self.has_batch_consumers = (
self.passthrough_batch_consumers or self.other_batch_consumers)
self._batched_elements: List[Any] = []
def receive(self, windowed_value):
# type: (WindowedValue) -> None
self.update_counters_start(windowed_value)
for consumer in self.element_consumers:
_cast_to_operation(consumer).process(windowed_value)
# TODO: Do this branching when contstructing ConsumerSet
if self.has_batch_consumers:
self._batched_elements.append(windowed_value)
if len(self._batched_elements) >= self.MAX_BATCH_SIZE:
self.flush()
# TODO(https://github.com/apache/beam/issues/21655): Properly estimate
# sizes in the batch-consumer only case, this undercounts large iterables
self.update_counters_finish()
def receive_batch(self, windowed_batch):
if self.element_consumers:
for wv in windowed_batch.as_windowed_values(
self.producer_batch_converter.explode_batch):
for consumer in self.element_consumers:
_cast_to_operation(consumer).process(wv)
for consumer in self.passthrough_batch_consumers:
_cast_to_operation(consumer).process_batch(windowed_batch)
for (consumer_batch_converter,
consumers) in self.other_batch_consumers.items():
# Explode and rebatch into the new batch type (ouch!)
# TODO: Register direct conversions for equivalent batch types
for consumer in consumers:
warnings.warn(
f"Input to operation {consumer} must be rebatched from type "
f"{self.producer_batch_converter.batch_type!r} to "
f"{consumer_batch_converter.batch_type!r}.\n"
"This is very inefficient, consider re-structuring your pipeline "
"or adding a DoFn to directly convert between these types.",
InefficientExecutionWarning)
_cast_to_operation(consumer).process_batch(
windowed_batch.with_values(
consumer_batch_converter.produce_batch(
self.producer_batch_converter.explode_batch(
windowed_batch.values))))
self.update_counters_batch(windowed_batch)
def flush(self):
if not self.has_batch_consumers or not self._batched_elements:
return
for batch_converter, consumers in self.other_batch_consumers.items():
for windowed_batch in WindowedBatch.from_windowed_values(
self._batched_elements, produce_fn=batch_converter.produce_batch):
for consumer in consumers:
_cast_to_operation(consumer).process_batch(windowed_batch)
for consumer in self.passthrough_batch_consumers:
for windowed_batch in WindowedBatch.from_windowed_values(
self._batched_elements,
produce_fn=self.producer_batch_converter.produce_batch):
_cast_to_operation(consumer).process_batch(windowed_batch)
self._batched_elements = []
class Operation(object):
"""An operation representing the live version of a work item specification.
An operation can have one or more outputs and for each output it can have
one or more receiver operations that will take that as input.
"""
def __init__(self,
name_context, # type: common.NameContext
spec,
counter_factory,
state_sampler # type: StateSampler
):
"""Initializes a worker operation instance.
Args:
name_context: A NameContext instance, with the name information for this
operation.
spec: A operation_specs.Worker* instance.
counter_factory: The CounterFactory to use for our counters.
state_sampler: The StateSampler for the current operation.
"""
assert isinstance(name_context, common.NameContext)
self.name_context = name_context
self.spec = spec
self.counter_factory = counter_factory
self.execution_context = None # type: Optional[ExecutionContext]
self.consumers = collections.defaultdict(
list) # type: DefaultDict[int, List[Operation]]
# These are overwritten in the legacy harness.
self.metrics_container = MetricsContainer(self.name_context.metrics_name())
self.state_sampler = state_sampler
self.scoped_start_state = self.state_sampler.scoped_state(
self.name_context, 'start', metrics_container=self.metrics_container)
self.scoped_process_state = self.state_sampler.scoped_state(
self.name_context, 'process', metrics_container=self.metrics_container)
self.scoped_finish_state = self.state_sampler.scoped_state(
self.name_context, 'finish', metrics_container=self.metrics_container)
# TODO(ccy): the '-abort' state can be added when the abort is supported in
# Operations.
self.receivers = [] # type: List[ConsumerSet]
# Legacy workers cannot call setup() until after setting additional state
# on the operation.
self.setup_done = False
self.step_name = None # type: Optional[str]
self.data_sampler: Optional[DataSampler] = None
def setup(self, data_sampler=None):
# type: (Optional[DataSampler]) -> None
"""Set up operation.
This must be called before any other methods of the operation."""
with self.scoped_start_state:
self.data_sampler = data_sampler
self.debug_logging_enabled = logging.getLogger().isEnabledFor(
logging.DEBUG)
transform_id = self.name_context.transform_id
# Everything except WorkerSideInputSource, which is not a
# top-level operation, should have output_coders
#TODO(pabloem): Define better what step name is used here.
if getattr(self.spec, 'output_coders', None):
def get_output_sampler(output_num):
if data_sampler is None:
return None
return data_sampler.sampler_for_output(transform_id, output_num)
self.receivers = [
ConsumerSet.create(
self.counter_factory,
self.name_context.logging_name(),
i,
self.consumers[i],
coder,
self._get_runtime_performance_hints(),
self.get_output_batch_converter(),
get_output_sampler(i)) for i,
coder in enumerate(self.spec.output_coders)
]
self.setup_done = True
def start(self):
# type: () -> None
"""Start operation."""
if not self.setup_done:
# For legacy workers.
self.setup(self.data_sampler)
# The ExecutionContext is per instruction and so cannot be set at
# initialization time.
if self.data_sampler is not None:
for receiver in self.receivers:
receiver.execution_context = self.execution_context
def get_batching_preference(self):
# By default operations don't support batching, require Receiver to unbatch
return common.BatchingPreference.BATCH_FORBIDDEN
def get_input_batch_converter(self) -> Optional[BatchConverter]:
"""Returns a batch type converter if this operation can accept a batch,
otherwise None."""
return None
def get_output_batch_converter(self) -> Optional[BatchConverter]:
"""Returns a batch type converter if this operation can produce a batch,
otherwise None."""
return None
def process(self, o):
# type: (WindowedValue) -> None
"""Process element in operation."""
pass
def process_batch(self, batch: WindowedBatch):
pass
def finalize_bundle(self):
# type: () -> None
pass
def needs_finalization(self):
return False
def try_split(self, fraction_of_remainder):
# type: (...) -> Optional[Any]
return None
def current_element_progress(self):
return None
def finish(self):
# type: () -> None
"""Finish operation."""
for receiver in self.receivers:
_cast_to_receiver(receiver).flush()
def teardown(self):
# type: () -> None
"""Tear down operation.
No other methods of this operation should be called after this."""
pass
def reset(self):
# type: () -> None
self.metrics_container.reset()
def output(self, windowed_value, output_index=0):
# type: (WindowedValue, int) -> None
_cast_to_receiver(self.receivers[output_index]).receive(windowed_value)
def add_receiver(self, operation, output_index=0):
# type: (Operation, int) -> None
"""Adds a receiver operation for the specified output."""
self.consumers[output_index].append(operation)
def monitoring_infos(self, transform_id, tag_to_pcollection_id):
# type: (str, Dict[str, str]) -> Dict[FrozenSet, metrics_pb2.MonitoringInfo]
"""Returns the list of MonitoringInfos collected by this operation."""
all_monitoring_infos = self.execution_time_monitoring_infos(transform_id)
all_monitoring_infos.update(
self.pcollection_count_monitoring_infos(tag_to_pcollection_id))
all_monitoring_infos.update(self.user_monitoring_infos(transform_id))
return all_monitoring_infos
def pcollection_count_monitoring_infos(self, tag_to_pcollection_id):
# type: (Dict[str, str]) -> Dict[FrozenSet, metrics_pb2.MonitoringInfo]
"""Returns the element count MonitoringInfo collected by this operation."""
# Skip producing monitoring infos if there is more then one receiver
# since there is no way to provide a mapping from tag to pcollection id
# within Operation.
if len(self.receivers) != 1 or len(tag_to_pcollection_id) != 1:
return {}
all_monitoring_infos = {}
pcollection_id = next(iter(tag_to_pcollection_id.values()))
receiver = self.receivers[0]
elem_count_mi = monitoring_infos.int64_counter(
monitoring_infos.ELEMENT_COUNT_URN,
receiver.opcounter.element_counter.value(),
pcollection=pcollection_id,
)
(unused_mean, sum, count, min, max) = (
receiver.opcounter.mean_byte_counter.value())
sampled_byte_count = monitoring_infos.int64_distribution(
monitoring_infos.SAMPLED_BYTE_SIZE_URN,
DistributionData(sum, count, min, max),
pcollection=pcollection_id,
)
all_monitoring_infos[monitoring_infos.to_key(elem_count_mi)] = elem_count_mi
all_monitoring_infos[monitoring_infos.to_key(
sampled_byte_count)] = sampled_byte_count
return all_monitoring_infos
def user_monitoring_infos(self, transform_id):
# type: (str) -> Dict[FrozenSet, metrics_pb2.MonitoringInfo]
"""Returns the user MonitoringInfos collected by this operation."""
return self.metrics_container.to_runner_api_monitoring_infos(transform_id)
def execution_time_monitoring_infos(self, transform_id):
# type: (str) -> Dict[FrozenSet, metrics_pb2.MonitoringInfo]
total_time_spent_msecs = (
self.scoped_start_state.sampled_msecs_int() +
self.scoped_process_state.sampled_msecs_int() +
self.scoped_finish_state.sampled_msecs_int())
mis = [
monitoring_infos.int64_counter(
monitoring_infos.START_BUNDLE_MSECS_URN,
self.scoped_start_state.sampled_msecs_int(),
ptransform=transform_id),
monitoring_infos.int64_counter(
monitoring_infos.PROCESS_BUNDLE_MSECS_URN,
self.scoped_process_state.sampled_msecs_int(),
ptransform=transform_id),
monitoring_infos.int64_counter(
monitoring_infos.FINISH_BUNDLE_MSECS_URN,
self.scoped_finish_state.sampled_msecs_int(),
ptransform=transform_id),
monitoring_infos.int64_counter(
monitoring_infos.TOTAL_MSECS_URN,
total_time_spent_msecs,
ptransform=transform_id),
]
return {monitoring_infos.to_key(mi): mi for mi in mis}
def __str__(self):
"""Generates a useful string for this object.
Compactly displays interesting fields. In particular, pickled
fields are not displayed. Note that we collapse the fields of the
contained Worker* object into this object, since there is a 1-1
mapping between Operation and operation_specs.Worker*.
Returns:
Compact string representing this object.
"""
return self.str_internal()
def str_internal(self, is_recursive=False):
"""Internal helper for __str__ that supports recursion.
When recursing on receivers, keep the output short.
Args:
is_recursive: whether to omit some details, particularly receivers.
Returns:
Compact string representing this object.
"""
printable_name = self.__class__.__name__
if hasattr(self, 'step_name'):
printable_name += ' %s' % self.name_context.logging_name()
if is_recursive:
# If we have a step name, stop here, no more detail needed.
return '<%s>' % printable_name
if self.spec is None:
printable_fields = []
else:
printable_fields = operation_specs.worker_printable_fields(self.spec)
if not is_recursive and getattr(self, 'receivers', []):
printable_fields.append(
'receivers=[%s]' %
', '.join([str(receiver) for receiver in self.receivers]))
return '<%s %s>' % (printable_name, ', '.join(printable_fields))
def _get_runtime_performance_hints(self):
# type: () -> Optional[Dict[Optional[str], Tuple[Optional[str], Any]]]
"""Returns any type hints required for performance runtime
type-checking."""
return None
class ReadOperation(Operation):
def start(self):
with self.scoped_start_state:
super(ReadOperation, self).start()
range_tracker = self.spec.source.source.get_range_tracker(
self.spec.source.start_position, self.spec.source.stop_position)
for value in self.spec.source.source.read(range_tracker):
if isinstance(value, WindowedValue):
windowed_value = value
else:
windowed_value = _globally_windowed_value.with_value(value)
self.output(windowed_value)
class ImpulseReadOperation(Operation):
def __init__(
self,
name_context, # type: common.NameContext
counter_factory,
state_sampler, # type: StateSampler
consumers, # type: Mapping[Any, List[Operation]]
source, # type: iobase.BoundedSource
output_coder):
super(ImpulseReadOperation,
self).__init__(name_context, None, counter_factory, state_sampler)
self.source = source
self.receivers = [
ConsumerSet.create(
self.counter_factory,
self.name_context.step_name,
0,
next(iter(consumers.values())),
output_coder,
self._get_runtime_performance_hints(),
self.get_output_batch_converter())
]
def process(self, unused_impulse):
# type: (WindowedValue) -> None
with self.scoped_process_state:
range_tracker = self.source.get_range_tracker(None, None)
for value in self.source.read(range_tracker):
if isinstance(value, WindowedValue):
windowed_value = value
else:
windowed_value = _globally_windowed_value.with_value(value)
self.output(windowed_value)
class InMemoryWriteOperation(Operation):
"""A write operation that will write to an in-memory sink."""
def process(self, o):
# type: (WindowedValue) -> None
with self.scoped_process_state:
if self.debug_logging_enabled:
_LOGGER.debug('Processing [%s] in %s', o, self)
self.spec.output_buffer.append(
o if self.spec.write_windowed_values else o.value)
class _TaggedReceivers(dict):
def __init__(self, counter_factory, step_name):
self._counter_factory = counter_factory
self._step_name = step_name
def __missing__(self, tag):
self[tag] = receiver = ConsumerSet.create(
self._counter_factory, self._step_name, tag, [], None, None, None)
return receiver
def total_output_bytes(self):
# type: () -> int
total = 0
for receiver in self.values():
elements = receiver.opcounter.element_counter.value()
if elements > 0:
mean = (receiver.opcounter.mean_byte_counter.value())[0]
total += elements * mean
return total
OpInputInfo = NamedTuple(
'OpInputInfo',
[
('transform_id', str),
('main_input_tag', str),
('main_input_coder', coders.WindowedValueCoder),
('outputs', Iterable[str]),
])
class DoOperation(Operation):
"""A Do operation that will execute a custom DoFn for each input element."""
def __init__(self,
name, # type: common.NameContext
spec, # operation_specs.WorkerDoFn # need to fix this type
counter_factory,
sampler,
side_input_maps=None,
user_state_context=None,
):
super(DoOperation, self).__init__(name, spec, counter_factory, sampler)
self.side_input_maps = side_input_maps
self.user_state_context = user_state_context
self.tagged_receivers = None # type: Optional[_TaggedReceivers]
# A mapping of timer tags to the input "PCollections" they come in on.
self.input_info = None # type: Optional[OpInputInfo]
# See fn_data in dataflow_runner.py
# TODO: Store all the items from spec?
self.fn, _, _, _, _ = (pickler.loads(self.spec.serialized_fn))
def _read_side_inputs(self, tags_and_types):
# type: (...) -> Iterator[apache_sideinputs.SideInputMap]
"""Generator reading side inputs in the order prescribed by tags_and_types.
Args:
tags_and_types: List of tuples (tag, type). Each side input has a string
tag that is specified in the worker instruction. The type is actually
a boolean which is True for singleton input (read just first value)
and False for collection input (read all values).
Yields:
With each iteration it yields the result of reading an entire side source
either in singleton or collection mode according to the tags_and_types
argument.
"""
# Only call this on the old path where side_input_maps was not
# provided directly.
assert self.side_input_maps is None
# We will read the side inputs in the order prescribed by the
# tags_and_types argument because this is exactly the order needed to
# replace the ArgumentPlaceholder objects in the args/kwargs of the DoFn
# getting the side inputs.
#
# Note that for each tag there could be several read operations in the
# specification. This can happen for instance if the source has been
# sharded into several files.
for i, (side_tag, view_class, view_options) in enumerate(tags_and_types):
sources = []
# Using the side_tag in the lambda below will trigger a pylint warning.
# However in this case it is fine because the lambda is used right away
# while the variable has the value assigned by the current iteration of
# the for loop.
# pylint: disable=cell-var-from-loop
for si in filter(lambda o: o.tag == side_tag, self.spec.side_inputs):
if not isinstance(si, operation_specs.WorkerSideInputSource):
raise NotImplementedError('Unknown side input type: %r' % si)
sources.append(si.source)
si_counter = opcounters.SideInputReadCounter(
self.counter_factory,
self.state_sampler,
declaring_step=self.name_context.step_name,
# Inputs are 1-indexed, so we add 1 to i in the side input id
input_index=i + 1)
element_counter = opcounters.OperationCounters(
self.counter_factory,
self.name_context.step_name,
view_options['coder'],
i,
suffix='side-input')
iterator_fn = sideinputs.get_iterator_fn_for_sources(
sources, read_counter=si_counter, element_counter=element_counter)
yield apache_sideinputs.SideInputMap(
view_class, view_options, sideinputs.EmulatedIterable(iterator_fn))
def setup(self, data_sampler=None):
# type: (Optional[DataSampler]) -> None
with self.scoped_start_state:
super(DoOperation, self).setup(data_sampler)
# See fn_data in dataflow_runner.py
fn, args, kwargs, tags_and_types, window_fn = (
pickler.loads(self.spec.serialized_fn))
state = common.DoFnState(self.counter_factory)
state.step_name = self.name_context.logging_name()
# Tag to output index map used to dispatch the output values emitted
# by the DoFn function to the appropriate receivers. The main output is
# either the only output or the output tagged with 'None' and is
# associated with its corresponding index.
self.tagged_receivers = _TaggedReceivers(
self.counter_factory, self.name_context.logging_name())
if len(self.spec.output_tags) == 1:
self.tagged_receivers[None] = self.receivers[0]
self.tagged_receivers[self.spec.output_tags[0]] = self.receivers[0]
else:
for index, tag in enumerate(self.spec.output_tags):
self.tagged_receivers[tag] = self.receivers[index]
if tag == 'None':
self.tagged_receivers[None] = self.receivers[index]
if self.user_state_context:
self.timer_specs = {
spec.name: spec
for spec in userstate.get_dofn_specs(fn)[1]
} # type: Dict[str, TimerSpec]
if self.side_input_maps is None:
if tags_and_types:
self.side_input_maps = list(self._read_side_inputs(tags_and_types))
else:
self.side_input_maps = []
self.dofn_runner = common.DoFnRunner(
fn,
args,
kwargs,
self.side_input_maps,
window_fn,
tagged_receivers=self.tagged_receivers,
step_name=self.name_context.logging_name(),
state=state,
user_state_context=self.user_state_context,
transform_id=self.name_context.transform_id,
operation_name=self.name_context.metrics_name())
self.dofn_runner.setup()
def start(self):
# type: () -> None
with self.scoped_start_state:
super(DoOperation, self).start()
self.dofn_runner.execution_context = self.execution_context
self.dofn_runner.start()
def get_batching_preference(self):
if self.fn._process_batch_defined:
if self.fn._process_defined:
return common.BatchingPreference.DO_NOT_CARE
else:
return common.BatchingPreference.BATCH_REQUIRED
else:
return common.BatchingPreference.BATCH_FORBIDDEN
def get_input_batch_converter(self) -> Optional[BatchConverter]:
return getattr(self.fn, 'input_batch_converter', None)
def get_output_batch_converter(self) -> Optional[BatchConverter]:
return getattr(self.fn, 'output_batch_converter', None)
def process(self, o):
# type: (WindowedValue) -> None
with self.scoped_process_state:
delayed_applications = self.dofn_runner.process(o)
if delayed_applications:
assert self.execution_context is not None
for delayed_application in delayed_applications:
self.execution_context.delayed_applications.append(
(self, delayed_application))
def process_batch(self, windowed_batch: WindowedBatch) -> None:
self.dofn_runner.process_batch(windowed_batch)
def finalize_bundle(self):
# type: () -> None
self.dofn_runner.finalize()
def needs_finalization(self):
# type: () -> bool
return self.dofn_runner.bundle_finalizer_param.has_callbacks()
def add_timer_info(self, timer_family_id, timer_info):
self.user_state_context.add_timer_info(timer_family_id, timer_info)
def process_timer(self, tag, timer_data):
timer_spec = self.timer_specs[tag]
self.dofn_runner.process_user_timer(
timer_spec,
timer_data.user_key,
timer_data.windows[0],
timer_data.fire_timestamp,
timer_data.paneinfo,
timer_data.dynamic_timer_tag)
def finish(self):
# type: () -> None
super(DoOperation, self).finish()
with self.scoped_finish_state:
self.dofn_runner.finish()
if self.user_state_context:
self.user_state_context.commit()
def teardown(self):
# type: () -> None
with self.scoped_finish_state:
self.dofn_runner.teardown()
if self.user_state_context:
self.user_state_context.reset()
def reset(self):