|
| 1 | +import argparse |
| 2 | +import logging |
| 3 | + |
| 4 | +import apache_beam as beam |
| 5 | +import apache_beam.transforms.window as window |
| 6 | +from apache_beam.options.pipeline_options import PipelineOptions |
| 7 | +from apache_beam.options.pipeline_options import SetupOptions |
| 8 | +from apache_beam.options.pipeline_options import StandardOptions |
| 9 | + |
| 10 | + |
| 11 | +def run(argv=None): |
| 12 | + parser = argparse.ArgumentParser() |
| 13 | + parser.add_argument( |
| 14 | + '--input_topic', |
| 15 | + help=('The Cloud Pub/Sub topic to read from.' |
| 16 | + '"projects/<PROJECT_NAME>/topics/<TOPIC_NAME>".')) |
| 17 | + parser.add_argument( |
| 18 | + '--window_size', |
| 19 | + type=int, |
| 20 | + default=1, |
| 21 | + help=('Output file\'s window size in number of minutes.')) |
| 22 | + parser.add_argument( |
| 23 | + '--output_path', |
| 24 | + help=('GCS Path of the output file including filename prefix.')) |
| 25 | + known_args, pipeline_args = parser.parse_known_args(argv) |
| 26 | + |
| 27 | + # One or more DoFn's rely on global context. |
| 28 | + pipeline_options = PipelineOptions(pipeline_args) |
| 29 | + pipeline_options.view_as(SetupOptions).save_main_session = True |
| 30 | + pipeline_options.view_as(StandardOptions).streaming = True |
| 31 | + p = beam.Pipeline(options=pipeline_options) |
| 32 | + |
| 33 | + # Read from Cloud Pub/Sub into a PCollection. |
| 34 | + if known_args.input_topic: |
| 35 | + messages = (p |
| 36 | + | 'Read Pub/Sub Messages' >> beam.io.ReadFromPubSub( |
| 37 | + topic=known_args.input_topic) |
| 38 | + .with_output_types(bytes)) |
| 39 | + |
| 40 | + # Group messages by fixed-sized minute intervals. |
| 41 | + transformed = (messages |
| 42 | + | beam.WindowInto( |
| 43 | + window.FixedWindows(known_args.window_size)) |
| 44 | + .with_output_types(bytes)) |
| 45 | + |
| 46 | + # Output to GCS |
| 47 | + transformed | beam.io.WriteToText(file_path_prefix=known_args.output_path) |
| 48 | + |
| 49 | + result = p.run() |
| 50 | + result.wait_until_finish() |
| 51 | + |
| 52 | +if __name__ == '__main__': # noqa |
| 53 | + logging.getLogger().setLevel(logging.INFO) |
| 54 | + run() |
0 commit comments