/
TaxiCount.java
165 lines (131 loc) · 6.19 KB
/
TaxiCount.java
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
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.amazonaws.samples.beam.taxi.count;
import com.amazonaws.regions.Regions;
import com.amazonaws.samples.beam.taxi.count.kinesis.TripEvent;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream;
import org.apache.beam.runners.flink.FlinkRunner;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.kinesis.KinesisIO;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.PipelineOptionsValidator;
import org.apache.beam.sdk.transforms.*;
import org.apache.beam.sdk.transforms.windowing.*;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
public class TaxiCount {
private static final Logger LOG = LoggerFactory.getLogger(TaxiCount.class);
public static void main(String[] args) {
String[] kinesisArgs = TaxiCountOptions.argsFromKinesisApplicationProperties(args,"BeamApplicationProperties");
TaxiCountOptions options = PipelineOptionsFactory.fromArgs(ArrayUtils.addAll(args, kinesisArgs)).as(TaxiCountOptions.class);
options.setRunner(FlinkRunner.class);
options.setAwsRegion(Regions.getCurrentRegion().getName());
PipelineOptionsValidator.validate(TaxiCountOptions.class, options);
Pipeline p = Pipeline.create(options);
LOG.info("Running pipeline with options: {}", options.toString());
int batchSize;
PCollection<TripEvent> input;
switch (options.getSource()) {
case "kinesis":
batchSize = 1;
input = p
.apply("Kinesis source", KinesisIO
.read()
.withStreamName(options.getInputStreamName())
.withAWSClientsProvider(new DefaultCredentialsProviderClientsProvider(Regions.fromName(options.getAwsRegion())))
.withInitialPositionInStream(InitialPositionInStream.LATEST)
)
.apply("Parse Kinesis events", ParDo.of(new EventParser.KinesisParser()));
LOG.info("Start consuming events from stream {}", options.getInputStreamName());
break;
case "s3":
batchSize = 20;
input = p
.apply("S3 source", TextIO
.read()
.from(options.getInputS3Pattern())
)
.apply("Parse S3 events",ParDo.of(new EventParser.S3Parser()));
LOG.info("Start consuming events from s3 bucket {}", options.getInputS3Pattern());
break;
default:
throw new IllegalArgumentException("expecting 'kinesis' or 's3' as parameter of 'inputSource'");
}
PCollection<TripEvent> window = input
.apply("Group into 5 second windows", Window
.<TripEvent>into(FixedWindows.of(Duration.standardSeconds(5)))
.triggering(AfterWatermark
.pastEndOfWindow()
.withEarlyFirings(AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardSeconds(15)))
)
.withAllowedLateness(Duration.ZERO)
.discardingFiredPanes()
);
PCollection<Metric> metrics;
if (! options.getOutputBoroughs()) {
metrics = window
.apply("Count globally", Combine
.globally(Count.<TripEvent>combineFn())
.withoutDefaults()
)
.apply("Map to Metric", ParDo.of(
new DoFn<Long, Metric>() {
@ProcessElement
public void process(ProcessContext c) {
c.output(new Metric(c.element().longValue(), c.timestamp()));
}
}
));
} else {
metrics = window
.apply("Partition by borough", ParDo.of(new PartitionByBorough()))
.apply("Count per borough", Count.perKey())
.apply("Map to Metric", ParDo.of(
new DoFn<KV<String, Long>, Metric>() {
@ProcessElement
public void process(ProcessContext c) {
long count = c.element().getValue();
String borough = c.element().getKey();
Instant timestamp = c.timestamp();
LOG.debug("adding metric for borough {}", borough);
c.output(new Metric(count, borough, timestamp));
}
}
));
}
String streamName = options.getInputStreamName()==null ? "Unknown" : options.getInputStreamName();
Dimension dimension = Dimension.builder().name("StreamName").value(streamName).build();
metrics
.apply("Void key", WithKeys.of((Void) null))
.apply("Global Metric window", Window.<KV<Void, Metric>>into(new GlobalWindows())
.triggering(Repeatedly.forever(AfterFirst.of(
AfterPane.elementCountAtLeast(20),
AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardSeconds(1)))))
.discardingFiredPanes()
)
.apply("Group into batches", GroupIntoBatches.ofSize(batchSize))
.apply("CloudWatch sink", ParDo.of(new CloudWatchSink(dimension)));
p.run().waitUntilFinish();
}
}