在数据处理中,我们经常需要构建ETL的任务,对数据进行加载,转换处理后再写入到数据存储中。Google的云平台提供了多种方案来构建ETL任务,我也研究了一下这些方案,比较方案之间的优缺点,从而找到一个最适合我业务场景的方案。
假设我们的业务场景需要定期从Kafka中获取数据,经过一些数据清洗,数据关联,数据Enrich操作之后,把数据写入到Bigquery数据仓库,从而方便以后生成统计分析报表。
Google云平台提供了几个方案来完成这个任务:
1. Datafusion,通过在UI界面设计ETL pipeline,然后把Pipeline转换为Spark应用,部署在Dataproc上运行。
2. 编写Spark应用代码,然后在Dataproc上运行或者在K8S集群上通过Spark operator来调度执行。
3. 编写Apache Beam代码,通过Dataflow runner在VM上执行任务。
方案一的优点是基本不需要编写代码,在图形界面上即可完成Pipeline的设计。缺点是如果有一些额外的需求可能不太方便实现,另外最主要是太贵。Datafusion需要单独部署在一个Instance上24小时运行,这个Instance企业版的收费大概一小时要几美元。另外Pipeline运行的时候会调度Dataproc的Instance,这里会产生额外的费用。
方案二的优点是可以灵活的通过Spark代码来完成各种需求。缺点也是比较贵,因为Dataproc是基于Hadoop集群的,需要有Zookeeper, driver和executor这几个VM。如果采用K8S集群,则Spark operator也是需要单独24小时运行在一个pod上,另外还有额外的driver, executor的Pod需要调度执行。
方案三是综合考虑最优的方案,因为Beam的代码是提供了一个通用的流批处理框架,可以运行在Spark,Flink,Dataflow等引擎上,而Dataflow是Google提供的一个优秀的引擎,在运行任务时,Dataflow按需调度VM来运行,只收取运行时的费用。
因此,对于我的这个业务场景,使用方案三是最合适的。下面我将介绍一下整个实现的过程。
在Dataflow的官方Template里面,有一个消费Kafka数据写入到Bigquery的例子,但是这个是流处理方式实现的,对于我的业务场景来说,并不需要这么实时的处理数据,只需要定期消费即可,因此用批处理的方式更合适,这样也能大幅节约费用。
Beam的Kafka I/O connector是默认处理的数据是无边界的,即流式数据。要以批处理的方式来处理,需要调用withStartReadTime和withStopReadTime两个方法获取要读取的Kafka topic的start和end offset,这样就可以把数据转换为有边界数据。调用这两个方法需要注意的是,如果Kafka没有任何一条消息的时间戳是大于等于这个时间戳的话,那么会报错,因此我们需要确定一下具体的时间戳。
以下的代码是检查Kafka消息的所有分区是否存在消息的时间戳是大于我们指定的时间戳,如果不存在的话,那么我们需要找出这些分区里面的最晚时间戳里面的最早的一个。例如Topic有3个分区,要指定的时间戳是1697289783000,但是3个分区里面的所有消息都小于这个时间戳,因此我们需要分别找出每个分区里面的消息的最晚的时间戳,然后取这3个分区的最晚时间戳里面最早的那个,作为我们的指定时间戳。
- public class CheckKafkaMsgTimestamp {
- private static final Logger LOG = LoggerFactory.getLogger(CheckKafkaMsgTimestamp.class);
-
- public static KafkaResult getTimestamp(String bootstrapServer, String topic, long startTimestamp, long stopTimestamp) {
- long max_timestamp = stopTimestamp;
- long max_records = 5L;
- Properties props = new Properties();
- props.setProperty("bootstrap.servers", bootstrapServer);
- props.setProperty("group.id", "test");
- props.setProperty("enable.auto.commit", "true");
- props.setProperty("auto.commit.interval.ms", "1000");
- props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
- props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
- KafkaConsumer
consumer = new KafkaConsumer<>(props); -
- // Get all the partitions of the topic
- int partition_num = consumer.partitionsFor(topic).size();
- HashMap
search_map = new HashMap<>(); - ArrayList
tp = new ArrayList<>(); - for (int i=0;i
- search_map.put(new TopicPartition(topic, i), stopTimestamp);
- tp.add(new TopicPartition(topic, i));
- }
- // Check if message exist with timestamp greater than search timestamp
- Boolean flag = true;
- ArrayList
selected_tp = new ArrayList<>(); - //LOG.info("Start to check the timestamp {}", stopTimestamp);
- Map
results = consumer.offsetsForTimes(search_map); - for (Map.Entry
entry : results.entrySet()) { - OffsetAndTimestamp value = entry.getValue();
- if (value==null) { //there is at least one partition don't have timestamp greater or equal to the stopTime
- flag = false;
- break;
- }
- }
- // Get the latest timestamp of all partitions if the above check result is false
- // Note the timestamp is the earliest of all the partitions.
- if (!flag) {
- max_timestamp = 0L;
- consumer.assign(tp);
- Map
endoffsets = consumer.endOffsets(tp); - for (Map.Entry
entry : endoffsets.entrySet()) { - Long temp_timestamp = 0L;
- int record_count = 0;
- TopicPartition t = entry.getKey();
- long offset = entry.getValue();
- if (offset < 1) {
- LOG.warn("Can not get max_timestamp as partition has no record!");
- continue;
- }
- consumer.assign(Arrays.asList(t));
- consumer.seek(t, offset>max_records?offset-5:0);
-
- Iterator
> records = consumer.poll(Duration.ofSeconds(2)).iterator(); - while (records.hasNext()) {
- record_count++;
- ConsumerRecord
record = records.next(); - LOG.info("Topic: {}, Record Timestamp: {}, recordcount: {}", t, record.timestamp(), record_count);
- if (temp_timestamp == 0L || record.timestamp() > temp_timestamp) {
- temp_timestamp = record.timestamp();
- }
- }
- //LOG.info("Record count: {}", record_count);
- if (temp_timestamp > 0L && temp_timestamp > startTimestamp) {
- if (max_timestamp == 0L || max_timestamp > temp_timestamp) {
- max_timestamp = temp_timestamp;
- }
- selected_tp.add(t);
- LOG.info("Temp_timestamp {}", temp_timestamp);
- LOG.info("Selected topic partition {}", t);
- LOG.info("Partition offset {}", consumer.position(t));
- //consumer.seek(t, -1L);
- }
- }
- } else {
- selected_tp = tp;
- }
- consumer.close();
- LOG.info("Max Timestamp: {}", max_timestamp);
- return new KafkaResult(max_timestamp, selected_tp);
- }
- }
调用以上代码,我们可以获取要选择的分区以及对应的时间戳。利用这两个信息,我们就可以把指定时间范围内的Kafka数据转换为有边界数据了。以下是Beam建立Pipeline并处理数据,然后写入到Bigquery的代码:
- KafkaResult checkResult = CheckKafkaMsgTimestamp.getTimestamp(options.getBootstrapServer(), options.getInputTopic(), start_read_time, stop_read_time);
- stop_read_time = checkResult.max_timestamp;
- ArrayList
selected_tp = checkResult.selected_tp; -
- PCollection
input = pipeline - .apply("Read messages from Kafka",
- KafkaIO.
read() - .withBootstrapServers(options.getBootstrapServer())
- .withKeyDeserializer(StringDeserializer.class)
- .withValueDeserializer(StringDeserializer.class)
- .withConsumerConfigUpdates(ImmutableMap.of("group.id", "telematics_statistic.app", "enable.auto.commit", true))
- .withStartReadTime(Instant.ofEpochMilli(start_read_time))
- .withStopReadTime(Instant.ofEpochMilli(stop_read_time))
- .withTopicPartitions(selected_tp)
- .withoutMetadata())
- .apply("Get message contents", Values.
create()); -
- PCollectionTuple msgTuple = input
- .apply("Filter message", ParDo.of(new DoFn
() { - @ProcessElement
- public void processElement(@Element String element, MultiOutputReceiver out) {
- TelematicsStatisticsMsg msg = GSON.fromJson(element, TelematicsStatisticsMsg.class);
- if (msg.timestamp==0 || msg.vin==null) {
- out.get(otherMsgTag).output(element);
- } else {
- if (msg.timestamp
=stop_process_time) { - out.get(otherMsgTag).output(element);
- } else {
- out.get(statisticsMsgTag).output(msg);
- }
- }
- }
- })
- .withOutputTags(statisticsMsgTag, TupleTagList.of(otherMsgTag)));
-
- // Get the filter out msg
- PCollection
statisticsMsg = msgTuple.get(statisticsMsgTag); - // Save the raw records to Bigquery
- statisticsMsg
- .apply("Convert raw records to BigQuery TableRow", MapElements.into(TypeDescriptor.of(TableRow.class))
- .via(TelematicsStatisticsMsg -> new TableRow()
- .set("timestamp", Instant.ofEpochMilli(TelematicsStatisticsMsg.timestamp).toString())
- .set("vin", TelematicsStatisticsMsg.vin)
- .set("service", TelematicsStatisticsMsg.service)
- .set("type", TelematicsStatisticsMsg.messageType)))
- .apply("Save raw records to BigQuery", BigQueryIO.writeTableRows()
- .to(options.getStatisticsOutputTable())
- .withSchema(new TableSchema().setFields(Arrays.asList(
- new TableFieldSchema().setName("timestamp").setType("TIMESTAMP"),
- new TableFieldSchema().setName("vin").setType("STRING"),
- new TableFieldSchema().setName("service").setType("STRING"),
- new TableFieldSchema().setName("type").setType("STRING"))))
- .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)
- .withWriteDisposition(WriteDisposition.WRITE_APPEND));
-
- PipelineResult result = pipeline.run();
- try {
- result.getState();
- result.waitUntilFinish();
- } catch (UnsupportedOperationException e) {
- // do nothing
- } catch (Exception e) {
- e.printStackTrace();
- }
需要注意的是,每次处理任务完成后,我们需要把当前的stopReadTime记录下来,下次任务运行的时候把这个时间戳作为startReadTime,这样可以避免某些情况下的数据缺失读取的问题。这个时间戳我们可以把其记录在GCS的bucket里面。这里略过这部分代码。
提交Dataflow任务
之后我们就可以调用Google的Cloud Build功能来把代码打包为Flex Template
首先在Java项目中运行mvn clean package,打包jar文件
然后在命令行中设置以下环境变量:
- export TEMPLATE_PATH="gs://[your project ID]/dataflow/templates/telematics-pipeline.json"
- export TEMPLATE_IMAGE="gcr.io/[your project ID]/telematics-pipeline:latest"
- export REGION="us-west1"
之后运行gcloud build的命令来构建镜像:
gcloud dataflow flex-template build $TEMPLATE_PATH --image-gcr-path "$TEMPLATE_IMAGE" --sdk-language "JAVA" --flex-template-base-image "gcr.io/dataflow-templates-base/java17-template-launcher-base:20230308_RC00" --jar "target/telematics-pipeline-1.0-SNAPSHOT.jar" --env FLEX_TEMPLATE_JAVA_MAIN_CLASS="com.example.TelematicsBatch"
最后就可以调用命令来提交任务执行了:
gcloud dataflow flex-template run "analytics-pipeline-`date +%Y%m%d-%H%M%S`" --template-file-gcs-location "$TEMPLATE_PATH" --region "us-west1" --parameters ^~^bootstrapServer="kafka-1:9094,kafka-2:9094"~statisticsOutputTable="youprojectid:dataset.tablename"~serviceAccount="xxx@projectid.iam.gserviceaccount.com"~region="us-west1"~usePublicIps=false~runner=DataflowRunner~subnetwork="XXXX"~tempLocation=gs://bucketname/temp/~startTime=1693530000000~stopTime=1697216400000~processStartTime=1693530000000~processStopTime=1697216400000
如果我们需要任务自动定期执行,还可以在dataflow里面import一个Pipeline,用之前指定的Template_path来导入。然后设置任务的定期周期和启动时间即可,非常方便。