summaryrefslogtreecommitdiffstats
path: root/components/datalake-handler/feeder/src/main/java/org/onap/datalake/feeder/service/PullThread.java
blob: 3a07e2f9a6327ceb15d61b37b7416960b47f43cb (plain)
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
/*
* ============LICENSE_START=======================================================
* ONAP : DATALAKE
* ================================================================================
* Copyright 2019 China Mobile
*=================================================================================
* Licensed 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.
* ============LICENSE_END=========================================================
*/

package org.onap.datalake.feeder.service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.onap.datalake.feeder.config.ApplicationConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * Thread that pulls messages from DMaaP and save them to Big Data DBs
 *
 * @author Guobiao Mo
 *
 */

@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PullThread implements Runnable {

	@Autowired
	private DmaapService dmaapService;

	@Autowired
	private StoreService storeService;

	@Autowired
	private ApplicationConfiguration config;

	private final Logger log = LoggerFactory.getLogger(this.getClass());

	private KafkaConsumer<String, String> consumer; //<String, String> is key-value type, in our case key is empty, value is JSON text
	private int id;

	private final AtomicBoolean active = new AtomicBoolean(false);
	private boolean async;

	public PullThread(int id) {
		this.id = id;
	}

	@PostConstruct
	private void init() {
		async = config.isAsync();
		Properties consumerConfig = getConsumerConfig();
		log.info("Kafka ConsumerConfig: {}", consumerConfig);
		consumer = new KafkaConsumer<>(consumerConfig);
	}

	private Properties getConsumerConfig() {
		Properties consumerConfig = new Properties();

		consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getDmaapKafkaHostPort());
		consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, config.getDmaapKafkaGroup());
		consumerConfig.put(ConsumerConfig.CLIENT_ID_CONFIG, String.valueOf(id));
		consumerConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
		consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		consumerConfig.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");
		consumerConfig.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

		return consumerConfig;
	}

	/**
	 * start pulling.
	 */
	@Override
	public void run() {
		active.set(true);

		DummyRebalanceListener rebalanceListener = new DummyRebalanceListener();

		try {
			List<String> topics = dmaapService.getActiveTopics(); //TODO get updated topic list within loop

			log.info("Thread {} going to subscribe to topics: {}", id, topics);

			consumer.subscribe(topics, rebalanceListener);

			while (active.get()) {

				ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(config.getDmaapKafkaTimeout()));
				if (records != null) {
					List<Pair<Long, String>> messages = new ArrayList<>(records.count());
					for (TopicPartition partition : records.partitions()) {
						messages.clear();
						List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
						for (ConsumerRecord<String, String> record : partitionRecords) {
							messages.add(Pair.of(record.timestamp(), record.value()));
							//log.debug("threadid={} topic={}, timestamp={} key={}, offset={}, partition={}, value={}", id, record.topic(), record.timestamp(), record.key(), record.offset(), record.partition(), record.value());
						}
						storeService.saveMessages(partition.topic(), messages);
						log.info("saved to topic={} count={}", partition.topic(), partitionRecords.size());//TODO we may record this number to DB

						if (!async) {//for reliability, sync commit offset to Kafka, this slows down a bit
							long lastOffset = partitionRecords.get(partitionRecords.size() - 1).offset();
							consumer.commitSync(Collections.singletonMap(partition, new OffsetAndMetadata(lastOffset + 1)));
						}
					}

					if (async) {//for high Throughput, async commit offset in batch to Kafka
						consumer.commitAsync();
					}
				}
				storeService.flushStall();
			}
		} catch (Exception e) {
			log.error("Puller {} run():   exception={}", id, e.getMessage());
			log.error("", e);
		} finally {
			consumer.close();
		}
	}

	public void shutdown() {
		active.set(false);
		consumer.wakeup();
	}

	private class DummyRebalanceListener implements ConsumerRebalanceListener {
		@Override
		public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
			log.info("Called onPartitionsRevoked with partitions: {}", partitions);
		}

		@Override
		public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
			log.info("Called onPartitionsAssigned with partitions: {}", partitions);
		}
	}

}