KafkaService.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. package com.provectus.kafka.ui.service;
  2. import com.provectus.kafka.ui.exception.ValidationException;
  3. import com.provectus.kafka.ui.model.CreateTopicMessage;
  4. import com.provectus.kafka.ui.model.ExtendedAdminClient;
  5. import com.provectus.kafka.ui.model.InternalBrokerDiskUsage;
  6. import com.provectus.kafka.ui.model.InternalBrokerMetrics;
  7. import com.provectus.kafka.ui.model.InternalClusterMetrics;
  8. import com.provectus.kafka.ui.model.InternalConsumerGroup;
  9. import com.provectus.kafka.ui.model.InternalPartition;
  10. import com.provectus.kafka.ui.model.InternalReplica;
  11. import com.provectus.kafka.ui.model.InternalSegmentSizeDto;
  12. import com.provectus.kafka.ui.model.InternalTopic;
  13. import com.provectus.kafka.ui.model.InternalTopicConfig;
  14. import com.provectus.kafka.ui.model.KafkaCluster;
  15. import com.provectus.kafka.ui.model.Metric;
  16. import com.provectus.kafka.ui.model.PartitionsIncrease;
  17. import com.provectus.kafka.ui.model.ReplicationFactorChange;
  18. import com.provectus.kafka.ui.model.ServerStatus;
  19. import com.provectus.kafka.ui.model.TopicCreation;
  20. import com.provectus.kafka.ui.model.TopicUpdate;
  21. import com.provectus.kafka.ui.serde.DeserializationService;
  22. import com.provectus.kafka.ui.serde.RecordSerDe;
  23. import com.provectus.kafka.ui.util.ClusterUtil;
  24. import com.provectus.kafka.ui.util.JmxClusterUtil;
  25. import com.provectus.kafka.ui.util.JmxMetricsName;
  26. import com.provectus.kafka.ui.util.JmxMetricsValueName;
  27. import java.math.BigDecimal;
  28. import java.util.ArrayList;
  29. import java.util.Collection;
  30. import java.util.Collections;
  31. import java.util.Comparator;
  32. import java.util.HashMap;
  33. import java.util.List;
  34. import java.util.LongSummaryStatistics;
  35. import java.util.Map;
  36. import java.util.Optional;
  37. import java.util.Properties;
  38. import java.util.UUID;
  39. import java.util.concurrent.CompletableFuture;
  40. import java.util.concurrent.ConcurrentHashMap;
  41. import java.util.stream.Collectors;
  42. import java.util.stream.Stream;
  43. import lombok.RequiredArgsConstructor;
  44. import lombok.Setter;
  45. import lombok.SneakyThrows;
  46. import lombok.extern.log4j.Log4j2;
  47. import org.apache.kafka.clients.admin.AdminClient;
  48. import org.apache.kafka.clients.admin.AdminClientConfig;
  49. import org.apache.kafka.clients.admin.AlterConfigOp;
  50. import org.apache.kafka.clients.admin.Config;
  51. import org.apache.kafka.clients.admin.ConfigEntry;
  52. import org.apache.kafka.clients.admin.ConsumerGroupListing;
  53. import org.apache.kafka.clients.admin.ListTopicsOptions;
  54. import org.apache.kafka.clients.admin.NewPartitionReassignment;
  55. import org.apache.kafka.clients.admin.NewPartitions;
  56. import org.apache.kafka.clients.admin.NewTopic;
  57. import org.apache.kafka.clients.admin.RecordsToDelete;
  58. import org.apache.kafka.clients.consumer.ConsumerConfig;
  59. import org.apache.kafka.clients.consumer.KafkaConsumer;
  60. import org.apache.kafka.clients.consumer.OffsetAndMetadata;
  61. import org.apache.kafka.clients.producer.KafkaProducer;
  62. import org.apache.kafka.clients.producer.ProducerConfig;
  63. import org.apache.kafka.clients.producer.ProducerRecord;
  64. import org.apache.kafka.clients.producer.RecordMetadata;
  65. import org.apache.kafka.common.Node;
  66. import org.apache.kafka.common.TopicPartition;
  67. import org.apache.kafka.common.config.ConfigResource;
  68. import org.apache.kafka.common.serialization.ByteArraySerializer;
  69. import org.apache.kafka.common.serialization.BytesDeserializer;
  70. import org.apache.kafka.common.utils.Bytes;
  71. import org.springframework.beans.factory.annotation.Value;
  72. import org.springframework.stereotype.Service;
  73. import reactor.core.publisher.Flux;
  74. import reactor.core.publisher.Mono;
  75. import reactor.util.function.Tuple2;
  76. import reactor.util.function.Tuple3;
  77. import reactor.util.function.Tuples;
  78. @Service
  79. @RequiredArgsConstructor
  80. @Log4j2
  81. public class KafkaService {
  82. private static final ListTopicsOptions LIST_TOPICS_OPTIONS =
  83. new ListTopicsOptions().listInternal(true);
  84. private final ZookeeperService zookeeperService;
  85. private final Map<String, ExtendedAdminClient> adminClientCache = new ConcurrentHashMap<>();
  86. private final JmxClusterUtil jmxClusterUtil;
  87. private final ClustersStorage clustersStorage;
  88. private final DeserializationService deserializationService;
  89. @Setter // used in tests
  90. @Value("${kafka.admin-client-timeout}")
  91. private int clientTimeout;
  92. public KafkaCluster getUpdatedCluster(KafkaCluster cluster, InternalTopic updatedTopic) {
  93. final Map<String, InternalTopic> topics = new HashMap<>(cluster.getTopics());
  94. topics.put(updatedTopic.getName(), updatedTopic);
  95. return cluster.toBuilder().topics(topics).build();
  96. }
  97. public KafkaCluster getUpdatedCluster(KafkaCluster cluster, String topicToDelete) {
  98. final Map<String, InternalTopic> topics = new HashMap<>(cluster.getTopics());
  99. topics.remove(topicToDelete);
  100. return cluster.toBuilder().topics(topics).build();
  101. }
  102. @SneakyThrows
  103. public Mono<KafkaCluster> getUpdatedCluster(KafkaCluster cluster) {
  104. return getOrCreateAdminClient(cluster)
  105. .flatMap(
  106. ac -> ClusterUtil.getClusterVersion(ac.getAdminClient()).flatMap(
  107. version ->
  108. getClusterMetrics(ac.getAdminClient())
  109. .flatMap(i -> fillJmxMetrics(i, cluster.getName(), ac.getAdminClient()))
  110. .flatMap(clusterMetrics ->
  111. getTopicsData(ac.getAdminClient()).flatMap(it ->
  112. updateSegmentMetrics(ac.getAdminClient(), clusterMetrics, it)
  113. ).map(segmentSizeDto -> buildFromData(cluster, version, segmentSizeDto))
  114. )
  115. )
  116. ).onErrorResume(
  117. e -> Mono.just(cluster.toBuilder()
  118. .status(ServerStatus.OFFLINE)
  119. .lastKafkaException(e)
  120. .build())
  121. );
  122. }
  123. private KafkaCluster buildFromData(KafkaCluster currentCluster,
  124. String version,
  125. InternalSegmentSizeDto segmentSizeDto) {
  126. var topics = segmentSizeDto.getInternalTopicWithSegmentSize();
  127. var brokersMetrics = segmentSizeDto.getClusterMetricsWithSegmentSize();
  128. var brokersIds = new ArrayList<>(brokersMetrics.getInternalBrokerMetrics().keySet());
  129. InternalClusterMetrics.InternalClusterMetricsBuilder metricsBuilder =
  130. brokersMetrics.toBuilder();
  131. InternalClusterMetrics topicsMetrics = collectTopicsMetrics(topics);
  132. ServerStatus zookeeperStatus = ServerStatus.OFFLINE;
  133. Throwable zookeeperException = null;
  134. try {
  135. zookeeperStatus = zookeeperService.isZookeeperOnline(currentCluster) ? ServerStatus.ONLINE :
  136. ServerStatus.OFFLINE;
  137. } catch (Throwable e) {
  138. zookeeperException = e;
  139. }
  140. InternalClusterMetrics clusterMetrics = metricsBuilder
  141. .activeControllers(brokersMetrics.getActiveControllers())
  142. .topicCount(topicsMetrics.getTopicCount())
  143. .brokerCount(brokersMetrics.getBrokerCount())
  144. .underReplicatedPartitionCount(topicsMetrics.getUnderReplicatedPartitionCount())
  145. .inSyncReplicasCount(topicsMetrics.getInSyncReplicasCount())
  146. .outOfSyncReplicasCount(topicsMetrics.getOutOfSyncReplicasCount())
  147. .onlinePartitionCount(topicsMetrics.getOnlinePartitionCount())
  148. .offlinePartitionCount(topicsMetrics.getOfflinePartitionCount())
  149. .zooKeeperStatus(ClusterUtil.convertToIntServerStatus(zookeeperStatus))
  150. .build();
  151. return currentCluster.toBuilder()
  152. .version(version)
  153. .status(ServerStatus.ONLINE)
  154. .zookeeperStatus(zookeeperStatus)
  155. .lastZookeeperException(zookeeperException)
  156. .lastKafkaException(null)
  157. .metrics(clusterMetrics)
  158. .topics(topics)
  159. .brokers(brokersIds)
  160. .build();
  161. }
  162. private InternalClusterMetrics collectTopicsMetrics(Map<String, InternalTopic> topics) {
  163. int underReplicatedPartitions = 0;
  164. int inSyncReplicasCount = 0;
  165. int outOfSyncReplicasCount = 0;
  166. int onlinePartitionCount = 0;
  167. int offlinePartitionCount = 0;
  168. for (InternalTopic topic : topics.values()) {
  169. underReplicatedPartitions += topic.getUnderReplicatedPartitions();
  170. inSyncReplicasCount += topic.getInSyncReplicas();
  171. outOfSyncReplicasCount += (topic.getReplicas() - topic.getInSyncReplicas());
  172. onlinePartitionCount +=
  173. topic.getPartitions().values().stream().mapToInt(s -> s.getLeader() == null ? 0 : 1)
  174. .sum();
  175. offlinePartitionCount +=
  176. topic.getPartitions().values().stream().mapToInt(s -> s.getLeader() != null ? 0 : 1)
  177. .sum();
  178. }
  179. return InternalClusterMetrics.builder()
  180. .underReplicatedPartitionCount(underReplicatedPartitions)
  181. .inSyncReplicasCount(inSyncReplicasCount)
  182. .outOfSyncReplicasCount(outOfSyncReplicasCount)
  183. .onlinePartitionCount(onlinePartitionCount)
  184. .offlinePartitionCount(offlinePartitionCount)
  185. .topicCount(topics.size())
  186. .build();
  187. }
  188. private Map<String, InternalTopic> mergeWithConfigs(
  189. List<InternalTopic> topics, Map<String, List<InternalTopicConfig>> configs) {
  190. return topics.stream().map(
  191. t -> t.toBuilder().topicConfigs(configs.get(t.getName())).build()
  192. ).collect(Collectors.toMap(
  193. InternalTopic::getName,
  194. e -> e
  195. ));
  196. }
  197. @SneakyThrows
  198. private Mono<List<InternalTopic>> getTopicsData(AdminClient adminClient) {
  199. return ClusterUtil.toMono(adminClient.listTopics(LIST_TOPICS_OPTIONS).names())
  200. .flatMap(topics -> getTopicsData(adminClient, topics).collectList());
  201. }
  202. private Flux<InternalTopic> getTopicsData(AdminClient adminClient, Collection<String> topics) {
  203. final Mono<Map<String, List<InternalTopicConfig>>> configsMono =
  204. loadTopicsConfig(adminClient, topics);
  205. return ClusterUtil.toMono(adminClient.describeTopics(topics).all()).map(
  206. m -> m.values().stream().map(ClusterUtil::mapToInternalTopic).collect(Collectors.toList())
  207. ).flatMap(internalTopics -> configsMono.map(configs ->
  208. mergeWithConfigs(internalTopics, configs).values()
  209. )).flatMapMany(Flux::fromIterable);
  210. }
  211. private Mono<InternalClusterMetrics> getClusterMetrics(AdminClient client) {
  212. return ClusterUtil.toMono(client.describeCluster().nodes())
  213. .flatMap(brokers ->
  214. ClusterUtil.toMono(client.describeCluster().controller()).map(
  215. c -> {
  216. InternalClusterMetrics.InternalClusterMetricsBuilder metricsBuilder =
  217. InternalClusterMetrics.builder();
  218. metricsBuilder.brokerCount(brokers.size()).activeControllers(c != null ? 1 : 0);
  219. return metricsBuilder.build();
  220. }
  221. )
  222. );
  223. }
  224. @SneakyThrows
  225. private Mono<String> createTopic(AdminClient adminClient, NewTopic newTopic) {
  226. return ClusterUtil.toMono(adminClient.createTopics(Collections.singletonList(newTopic)).all(),
  227. newTopic.name());
  228. }
  229. @SneakyThrows
  230. public Mono<InternalTopic> createTopic(AdminClient adminClient,
  231. Mono<TopicCreation> topicCreation) {
  232. return topicCreation.flatMap(
  233. topicData -> {
  234. NewTopic newTopic = new NewTopic(topicData.getName(), topicData.getPartitions(),
  235. topicData.getReplicationFactor().shortValue());
  236. newTopic.configs(topicData.getConfigs());
  237. return createTopic(adminClient, newTopic).map(v -> topicData);
  238. }).flatMap(
  239. topicData ->
  240. getTopicsData(adminClient, Collections.singleton(topicData.getName()))
  241. .next()
  242. ).switchIfEmpty(Mono.error(new RuntimeException("Can't find created topic")))
  243. .flatMap(t ->
  244. loadTopicsConfig(adminClient, Collections.singletonList(t.getName()))
  245. .map(c -> mergeWithConfigs(Collections.singletonList(t), c))
  246. .map(m -> m.values().iterator().next())
  247. );
  248. }
  249. public Mono<InternalTopic> createTopic(KafkaCluster cluster, Mono<TopicCreation> topicCreation) {
  250. return getOrCreateAdminClient(cluster)
  251. .flatMap(ac -> createTopic(ac.getAdminClient(), topicCreation));
  252. }
  253. public Mono<Void> deleteTopic(KafkaCluster cluster, String topicName) {
  254. return getOrCreateAdminClient(cluster)
  255. .map(ExtendedAdminClient::getAdminClient)
  256. .map(adminClient -> adminClient.deleteTopics(List.of(topicName)))
  257. .then();
  258. }
  259. @SneakyThrows
  260. public Mono<ExtendedAdminClient> getOrCreateAdminClient(KafkaCluster cluster) {
  261. return Mono.justOrEmpty(adminClientCache.get(cluster.getName()))
  262. .switchIfEmpty(createAdminClient(cluster))
  263. .map(e -> adminClientCache.computeIfAbsent(cluster.getName(), key -> e));
  264. }
  265. public Mono<ExtendedAdminClient> createAdminClient(KafkaCluster kafkaCluster) {
  266. return Mono.fromSupplier(() -> {
  267. Properties properties = new Properties();
  268. properties.putAll(kafkaCluster.getProperties());
  269. properties
  270. .put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaCluster.getBootstrapServers());
  271. properties.put(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, clientTimeout);
  272. return AdminClient.create(properties);
  273. }).flatMap(ExtendedAdminClient::extendedAdminClient);
  274. }
  275. @SneakyThrows
  276. private Mono<Map<String, List<InternalTopicConfig>>> loadTopicsConfig(
  277. AdminClient adminClient, Collection<String> topicNames) {
  278. List<ConfigResource> resources = topicNames.stream()
  279. .map(topicName -> new ConfigResource(ConfigResource.Type.TOPIC, topicName))
  280. .collect(Collectors.toList());
  281. return ClusterUtil.toMono(adminClient.describeConfigs(resources).all())
  282. .map(configs ->
  283. configs.entrySet().stream().map(
  284. c -> Tuples.of(
  285. c.getKey().name(),
  286. c.getValue().entries().stream().map(ClusterUtil::mapToInternalTopicConfig)
  287. .collect(Collectors.toList())
  288. )
  289. ).collect(Collectors.toMap(
  290. Tuple2::getT1,
  291. Tuple2::getT2
  292. ))
  293. );
  294. }
  295. public Mono<List<InternalConsumerGroup>> getConsumerGroupsInternal(
  296. KafkaCluster cluster) {
  297. return getOrCreateAdminClient(cluster).flatMap(ac ->
  298. ClusterUtil.toMono(ac.getAdminClient().listConsumerGroups().all())
  299. .flatMap(s ->
  300. getConsumerGroupsInternal(
  301. cluster,
  302. s.stream().map(ConsumerGroupListing::groupId).collect(Collectors.toList()))
  303. )
  304. );
  305. }
  306. public Mono<List<InternalConsumerGroup>> getConsumerGroupsInternal(
  307. KafkaCluster cluster, List<String> groupIds) {
  308. return getOrCreateAdminClient(cluster).flatMap(ac ->
  309. ClusterUtil.toMono(
  310. ac.getAdminClient().describeConsumerGroups(groupIds).all()
  311. ).map(Map::values)
  312. ).flatMap(descriptions ->
  313. Flux.fromIterable(descriptions)
  314. .parallel()
  315. .flatMap(d ->
  316. groupMetadata(cluster, d.groupId())
  317. .map(offsets -> ClusterUtil.convertToInternalConsumerGroup(d, offsets))
  318. )
  319. .sequential()
  320. .collectList()
  321. );
  322. }
  323. public Mono<List<InternalConsumerGroup>> getConsumerGroups(
  324. KafkaCluster cluster, Optional<String> topic, List<String> groupIds) {
  325. final Mono<List<InternalConsumerGroup>> consumerGroups;
  326. if (groupIds.isEmpty()) {
  327. consumerGroups = getConsumerGroupsInternal(cluster);
  328. } else {
  329. consumerGroups = getConsumerGroupsInternal(cluster, groupIds);
  330. }
  331. return consumerGroups.map(c ->
  332. c.stream()
  333. .map(d -> ClusterUtil.filterConsumerGroupTopic(d, topic))
  334. .filter(Optional::isPresent)
  335. .map(Optional::get)
  336. .map(g ->
  337. g.toBuilder().endOffsets(
  338. topicPartitionsEndOffsets(cluster, g.getOffsets().keySet())
  339. ).build()
  340. )
  341. .collect(Collectors.toList())
  342. );
  343. }
  344. public Mono<Map<TopicPartition, OffsetAndMetadata>> groupMetadata(KafkaCluster cluster,
  345. String consumerGroupId) {
  346. return getOrCreateAdminClient(cluster).map(ac ->
  347. ac.getAdminClient()
  348. .listConsumerGroupOffsets(consumerGroupId)
  349. .partitionsToOffsetAndMetadata()
  350. ).flatMap(ClusterUtil::toMono);
  351. }
  352. public Map<TopicPartition, Long> topicPartitionsEndOffsets(
  353. KafkaCluster cluster, Collection<TopicPartition> topicPartitions) {
  354. try (KafkaConsumer<Bytes, Bytes> consumer = createConsumer(cluster)) {
  355. return consumer.endOffsets(topicPartitions);
  356. }
  357. }
  358. public KafkaConsumer<Bytes, Bytes> createConsumer(KafkaCluster cluster) {
  359. return createConsumer(cluster, Map.of());
  360. }
  361. public KafkaConsumer<Bytes, Bytes> createConsumer(KafkaCluster cluster,
  362. Map<String, Object> properties) {
  363. Properties props = new Properties();
  364. props.putAll(cluster.getProperties());
  365. props.put(ConsumerConfig.CLIENT_ID_CONFIG, "kafka-ui-" + UUID.randomUUID());
  366. props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
  367. props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
  368. props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
  369. props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
  370. props.putAll(properties);
  371. return new KafkaConsumer<>(props);
  372. }
  373. @SneakyThrows
  374. public Mono<InternalTopic> updateTopic(KafkaCluster cluster, String topicName,
  375. TopicUpdate topicUpdate) {
  376. ConfigResource topicCr = new ConfigResource(ConfigResource.Type.TOPIC, topicName);
  377. return getOrCreateAdminClient(cluster)
  378. .flatMap(ac -> {
  379. if (ac.getSupportedFeatures()
  380. .contains(ExtendedAdminClient.SupportedFeature.INCREMENTAL_ALTER_CONFIGS)) {
  381. return incrementalAlterConfig(topicUpdate, topicCr, ac)
  382. .flatMap(c -> getUpdatedTopic(ac, topicName));
  383. } else {
  384. return alterConfig(topicUpdate, topicCr, ac)
  385. .flatMap(c -> getUpdatedTopic(ac, topicName));
  386. }
  387. });
  388. }
  389. private Mono<InternalTopic> getUpdatedTopic(ExtendedAdminClient ac, String topicName) {
  390. return getTopicsData(ac.getAdminClient())
  391. .map(s -> s.stream()
  392. .filter(t -> t.getName().equals(topicName)).findFirst().orElseThrow());
  393. }
  394. private Mono<String> incrementalAlterConfig(TopicUpdate topicUpdate, ConfigResource topicCr,
  395. ExtendedAdminClient ac) {
  396. List<AlterConfigOp> listOp = topicUpdate.getConfigs().entrySet().stream()
  397. .flatMap(cfg -> Stream.of(new AlterConfigOp(new ConfigEntry(cfg.getKey(), cfg.getValue()),
  398. AlterConfigOp.OpType.SET))).collect(Collectors.toList());
  399. return ClusterUtil.toMono(
  400. ac.getAdminClient().incrementalAlterConfigs(Collections.singletonMap(topicCr, listOp))
  401. .all(), topicCr.name());
  402. }
  403. @SuppressWarnings("deprecation")
  404. private Mono<String> alterConfig(TopicUpdate topicUpdate, ConfigResource topicCr,
  405. ExtendedAdminClient ac) {
  406. List<ConfigEntry> configEntries = topicUpdate.getConfigs().entrySet().stream()
  407. .flatMap(cfg -> Stream.of(new ConfigEntry(cfg.getKey(), cfg.getValue())))
  408. .collect(Collectors.toList());
  409. Config config = new Config(configEntries);
  410. Map<ConfigResource, Config> map = Collections.singletonMap(topicCr, config);
  411. return ClusterUtil.toMono(ac.getAdminClient().alterConfigs(map).all(), topicCr.name());
  412. }
  413. private InternalTopic mergeWithStats(InternalTopic topic,
  414. Map<String, LongSummaryStatistics> topics,
  415. Map<TopicPartition, LongSummaryStatistics> partitions) {
  416. final LongSummaryStatistics stats = topics.get(topic.getName());
  417. return topic.toBuilder()
  418. .segmentSize(stats.getSum())
  419. .segmentCount(stats.getCount())
  420. .partitions(
  421. topic.getPartitions().entrySet().stream().map(e ->
  422. Tuples.of(e.getKey(), mergeWithStats(topic.getName(), e.getValue(), partitions))
  423. ).collect(Collectors.toMap(
  424. Tuple2::getT1,
  425. Tuple2::getT2
  426. ))
  427. ).build();
  428. }
  429. private InternalPartition mergeWithStats(String topic, InternalPartition partition,
  430. Map<TopicPartition, LongSummaryStatistics> partitions) {
  431. final LongSummaryStatistics stats =
  432. partitions.get(new TopicPartition(topic, partition.getPartition()));
  433. return partition.toBuilder()
  434. .segmentSize(stats.getSum())
  435. .segmentCount(stats.getCount())
  436. .build();
  437. }
  438. private Mono<InternalSegmentSizeDto> updateSegmentMetrics(AdminClient ac,
  439. InternalClusterMetrics clusterMetrics,
  440. List<InternalTopic> internalTopics) {
  441. List<String> names =
  442. internalTopics.stream().map(InternalTopic::getName).collect(Collectors.toList());
  443. return ClusterUtil.toMono(ac.describeTopics(names).all()).flatMap(topic ->
  444. ClusterUtil.toMono(ac.describeCluster().nodes()).flatMap(nodes ->
  445. ClusterUtil.toMono(
  446. ac.describeLogDirs(nodes.stream().map(Node::id).collect(Collectors.toList())).all())
  447. .map(log -> {
  448. final List<Tuple3<Integer, TopicPartition, Long>> topicPartitions =
  449. log.entrySet().stream().flatMap(b ->
  450. b.getValue().entrySet().stream().flatMap(topicMap ->
  451. topicMap.getValue().replicaInfos.entrySet().stream()
  452. .map(e -> Tuples.of(b.getKey(), e.getKey(), e.getValue().size))
  453. )
  454. ).collect(Collectors.toList());
  455. final Map<TopicPartition, LongSummaryStatistics> partitionStats =
  456. topicPartitions.stream().collect(
  457. Collectors.groupingBy(
  458. Tuple2::getT2,
  459. Collectors.summarizingLong(Tuple3::getT3)
  460. )
  461. );
  462. final Map<String, LongSummaryStatistics> topicStats =
  463. topicPartitions.stream().collect(
  464. Collectors.groupingBy(
  465. t -> t.getT2().topic(),
  466. Collectors.summarizingLong(Tuple3::getT3)
  467. )
  468. );
  469. final Map<Integer, LongSummaryStatistics> brokerStats =
  470. topicPartitions.stream().collect(
  471. Collectors.groupingBy(
  472. Tuple2::getT1,
  473. Collectors.summarizingLong(Tuple3::getT3)
  474. )
  475. );
  476. final LongSummaryStatistics summary =
  477. topicPartitions.stream().collect(Collectors.summarizingLong(Tuple3::getT3));
  478. final Map<String, InternalTopic> resultTopics = internalTopics.stream().map(e ->
  479. Tuples.of(e.getName(), mergeWithStats(e, topicStats, partitionStats))
  480. ).collect(Collectors.toMap(
  481. Tuple2::getT1,
  482. Tuple2::getT2
  483. ));
  484. final Map<Integer, InternalBrokerDiskUsage> resultBrokers =
  485. brokerStats.entrySet().stream().map(e ->
  486. Tuples.of(e.getKey(), InternalBrokerDiskUsage.builder()
  487. .segmentSize(e.getValue().getSum())
  488. .segmentCount(e.getValue().getCount())
  489. .build()
  490. )
  491. ).collect(Collectors.toMap(
  492. Tuple2::getT1,
  493. Tuple2::getT2
  494. ));
  495. return InternalSegmentSizeDto.builder()
  496. .clusterMetricsWithSegmentSize(
  497. clusterMetrics.toBuilder()
  498. .segmentSize(summary.getSum())
  499. .segmentCount(summary.getCount())
  500. .internalBrokerDiskUsage(resultBrokers)
  501. .build()
  502. )
  503. .internalTopicWithSegmentSize(resultTopics).build();
  504. })
  505. )
  506. );
  507. }
  508. public List<Metric> getJmxMetric(String clusterName, Node node) {
  509. return clustersStorage.getClusterByName(clusterName)
  510. .filter(c -> c.getJmxPort() != null)
  511. .filter(c -> c.getJmxPort() > 0)
  512. .map(c -> jmxClusterUtil.getJmxMetrics(c.getJmxPort(), node.host()))
  513. .orElse(Collections.emptyList());
  514. }
  515. private Mono<InternalClusterMetrics> fillJmxMetrics(InternalClusterMetrics internalClusterMetrics,
  516. String clusterName, AdminClient ac) {
  517. return fillBrokerMetrics(internalClusterMetrics, clusterName, ac)
  518. .map(this::calculateClusterMetrics);
  519. }
  520. private Mono<InternalClusterMetrics> fillBrokerMetrics(
  521. InternalClusterMetrics internalClusterMetrics, String clusterName, AdminClient ac) {
  522. return ClusterUtil.toMono(ac.describeCluster().nodes())
  523. .flatMapIterable(nodes -> nodes)
  524. .map(broker ->
  525. Map.of(broker.id(), InternalBrokerMetrics.builder()
  526. .metrics(getJmxMetric(clusterName, broker)).build())
  527. )
  528. .collectList()
  529. .map(s -> internalClusterMetrics.toBuilder()
  530. .internalBrokerMetrics(ClusterUtil.toSingleMap(s.stream())).build());
  531. }
  532. private InternalClusterMetrics calculateClusterMetrics(
  533. InternalClusterMetrics internalClusterMetrics) {
  534. final List<Metric> metrics = internalClusterMetrics.getInternalBrokerMetrics().values().stream()
  535. .flatMap(b -> b.getMetrics().stream())
  536. .collect(
  537. Collectors.groupingBy(
  538. Metric::getCanonicalName,
  539. Collectors.reducing(jmxClusterUtil::reduceJmxMetrics)
  540. )
  541. ).values().stream()
  542. .filter(Optional::isPresent)
  543. .map(Optional::get)
  544. .collect(Collectors.toList());
  545. final InternalClusterMetrics.InternalClusterMetricsBuilder metricsBuilder =
  546. internalClusterMetrics.toBuilder().metrics(metrics);
  547. metricsBuilder.bytesInPerSec(findTopicMetrics(
  548. metrics, JmxMetricsName.BytesInPerSec, JmxMetricsValueName.FiveMinuteRate
  549. ));
  550. metricsBuilder.bytesOutPerSec(findTopicMetrics(
  551. metrics, JmxMetricsName.BytesOutPerSec, JmxMetricsValueName.FiveMinuteRate
  552. ));
  553. return metricsBuilder.build();
  554. }
  555. private Map<String, BigDecimal> findTopicMetrics(List<Metric> metrics, JmxMetricsName metricsName,
  556. JmxMetricsValueName valueName) {
  557. return metrics.stream().filter(m -> metricsName.name().equals(m.getName()))
  558. .filter(m -> m.getParams().containsKey("topic"))
  559. .filter(m -> m.getValue().containsKey(valueName.name()))
  560. .map(m -> Tuples.of(
  561. m.getParams().get("topic"),
  562. m.getValue().get(valueName.name())
  563. )).collect(Collectors.groupingBy(
  564. Tuple2::getT1,
  565. Collectors.reducing(BigDecimal.ZERO, Tuple2::getT2, BigDecimal::add)
  566. ));
  567. }
  568. public Map<Integer, InternalPartition> getTopicPartitions(KafkaCluster c, InternalTopic topic) {
  569. var tps = topic.getPartitions().values().stream()
  570. .map(t -> new TopicPartition(topic.getName(), t.getPartition()))
  571. .collect(Collectors.toList());
  572. Map<Integer, InternalPartition> partitions =
  573. topic.getPartitions().values().stream().collect(Collectors.toMap(
  574. InternalPartition::getPartition,
  575. tp -> tp
  576. ));
  577. try (var consumer = createConsumer(c)) {
  578. final Map<TopicPartition, Long> earliest = consumer.beginningOffsets(tps);
  579. final Map<TopicPartition, Long> latest = consumer.endOffsets(tps);
  580. return tps.stream()
  581. .map(tp -> partitions.get(tp.partition()).toBuilder()
  582. .offsetMin(Optional.ofNullable(earliest.get(tp)).orElse(0L))
  583. .offsetMax(Optional.ofNullable(latest.get(tp)).orElse(0L))
  584. .build()
  585. ).collect(Collectors.toMap(
  586. InternalPartition::getPartition,
  587. tp -> tp
  588. ));
  589. } catch (Exception e) {
  590. return Collections.emptyMap();
  591. }
  592. }
  593. public Mono<Void> deleteTopicMessages(KafkaCluster cluster, Map<TopicPartition, Long> offsets) {
  594. var records = offsets.entrySet().stream()
  595. .map(entry -> Map.entry(entry.getKey(), RecordsToDelete.beforeOffset(entry.getValue())))
  596. .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  597. return getOrCreateAdminClient(cluster).map(ExtendedAdminClient::getAdminClient)
  598. .map(ac -> ac.deleteRecords(records)).then();
  599. }
  600. public Mono<RecordMetadata> sendMessage(KafkaCluster cluster, String topic,
  601. CreateTopicMessage msg) {
  602. RecordSerDe serde =
  603. deserializationService.getRecordDeserializerForCluster(cluster);
  604. Properties properties = new Properties();
  605. properties.putAll(cluster.getProperties());
  606. properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
  607. properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
  608. properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
  609. try (KafkaProducer<byte[], byte[]> producer = new KafkaProducer<>(properties)) {
  610. final ProducerRecord<byte[], byte[]> producerRecord = serde.serialize(
  611. topic,
  612. msg.getKey(),
  613. msg.getContent(),
  614. msg.getPartition()
  615. );
  616. CompletableFuture<RecordMetadata> cf = new CompletableFuture<>();
  617. producer.send(producerRecord, (metadata, exception) -> {
  618. if (exception != null) {
  619. cf.completeExceptionally(exception);
  620. } else {
  621. cf.complete(metadata);
  622. }
  623. });
  624. return Mono.fromFuture(cf);
  625. }
  626. }
  627. private Mono<InternalTopic> increaseTopicPartitions(AdminClient adminClient,
  628. String topicName,
  629. Map<String, NewPartitions> newPartitionsMap
  630. ) {
  631. return ClusterUtil.toMono(adminClient.createPartitions(newPartitionsMap).all(), topicName)
  632. .flatMap(topic -> getTopicsData(adminClient, Collections.singleton(topic)).next());
  633. }
  634. public Mono<InternalTopic> increaseTopicPartitions(
  635. KafkaCluster cluster,
  636. String topicName,
  637. PartitionsIncrease partitionsIncrease) {
  638. return getOrCreateAdminClient(cluster)
  639. .flatMap(ac -> {
  640. Integer actualCount = cluster.getTopics().get(topicName).getPartitionCount();
  641. Integer requestedCount = partitionsIncrease.getTotalPartitionsCount();
  642. if (requestedCount < actualCount) {
  643. return Mono.error(
  644. new ValidationException(String.format(
  645. "Topic currently has %s partitions, which is higher than the requested %s.",
  646. actualCount, requestedCount)));
  647. }
  648. if (requestedCount.equals(actualCount)) {
  649. return Mono.error(
  650. new ValidationException(
  651. String.format("Topic already has %s partitions.", actualCount)));
  652. }
  653. Map<String, NewPartitions> newPartitionsMap = Collections.singletonMap(
  654. topicName,
  655. NewPartitions.increaseTo(partitionsIncrease.getTotalPartitionsCount())
  656. );
  657. return increaseTopicPartitions(ac.getAdminClient(), topicName, newPartitionsMap);
  658. });
  659. }
  660. private Mono<InternalTopic> changeReplicationFactor(
  661. AdminClient adminClient,
  662. String topicName,
  663. Map<TopicPartition, Optional<NewPartitionReassignment>> reassignments
  664. ) {
  665. return ClusterUtil.toMono(adminClient
  666. .alterPartitionReassignments(reassignments).all(), topicName)
  667. .flatMap(topic -> getTopicsData(adminClient, Collections.singleton(topic)).next());
  668. }
  669. /**
  670. * Change topic replication factor, works on brokers versions 5.4.x and higher
  671. */
  672. public Mono<InternalTopic> changeReplicationFactor(
  673. KafkaCluster cluster,
  674. String topicName,
  675. ReplicationFactorChange replicationFactorChange) {
  676. return getOrCreateAdminClient(cluster)
  677. .flatMap(ac -> {
  678. Integer actual = cluster.getTopics().get(topicName).getReplicationFactor();
  679. Integer requested = replicationFactorChange.getTotalReplicationFactor();
  680. Integer brokersCount = cluster.getMetrics().getBrokerCount();
  681. if (requested.equals(actual)) {
  682. return Mono.error(
  683. new ValidationException(
  684. String.format("Topic already has replicationFactor %s.", actual)));
  685. }
  686. if (requested > brokersCount) {
  687. return Mono.error(
  688. new ValidationException(
  689. String.format("Requested replication factor %s more than brokers count %s.",
  690. requested, brokersCount)));
  691. }
  692. return changeReplicationFactor(ac.getAdminClient(), topicName,
  693. getPartitionsReassignments(cluster, topicName,
  694. replicationFactorChange));
  695. });
  696. }
  697. private Map<TopicPartition, Optional<NewPartitionReassignment>> getPartitionsReassignments(
  698. KafkaCluster cluster,
  699. String topicName,
  700. ReplicationFactorChange replicationFactorChange) {
  701. // Current assignment map (Partition number -> List of brokers)
  702. Map<Integer, List<Integer>> currentAssignment = getCurrentAssignment(cluster, topicName);
  703. // Brokers map (Broker id -> count)
  704. Map<Integer, Integer> brokersUsage = getBrokersMap(cluster, currentAssignment);
  705. int currentReplicationFactor = cluster.getTopics().get(topicName).getReplicationFactor();
  706. // If we should to increase Replication factor
  707. if (replicationFactorChange.getTotalReplicationFactor() > currentReplicationFactor) {
  708. // For each partition
  709. for (var assignmentList : currentAssignment.values()) {
  710. // Get brokers list sorted by usage
  711. var brokers = brokersUsage.entrySet().stream()
  712. .sorted(Map.Entry.comparingByValue())
  713. .map(Map.Entry::getKey)
  714. .collect(Collectors.toList());
  715. // Iterate brokers and try to add them in assignment
  716. // while (partition replicas count != requested replication factor)
  717. for (Integer broker : brokers) {
  718. if (!assignmentList.contains(broker)) {
  719. assignmentList.add(broker);
  720. brokersUsage.merge(broker, 1, Integer::sum);
  721. }
  722. if (assignmentList.size() == replicationFactorChange.getTotalReplicationFactor()) {
  723. break;
  724. }
  725. }
  726. if (assignmentList.size() != replicationFactorChange.getTotalReplicationFactor()) {
  727. throw new ValidationException("Something went wrong during adding replicas");
  728. }
  729. }
  730. // If we should to decrease Replication factor
  731. } else if (replicationFactorChange.getTotalReplicationFactor() < currentReplicationFactor) {
  732. for (Map.Entry<Integer, List<Integer>> assignmentEntry : currentAssignment.entrySet()) {
  733. var partition = assignmentEntry.getKey();
  734. var brokers = assignmentEntry.getValue();
  735. // Get brokers list sorted by usage in reverse order
  736. var brokersUsageList = brokersUsage.entrySet().stream()
  737. .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
  738. .map(Map.Entry::getKey)
  739. .collect(Collectors.toList());
  740. // Iterate brokers and try to remove them from assignment
  741. // while (partition replicas count != requested replication factor)
  742. for (Integer broker : brokersUsageList) {
  743. // Check is the broker the leader of partition
  744. if (!cluster.getTopics().get(topicName).getPartitions().get(partition).getLeader()
  745. .equals(broker)) {
  746. brokers.remove(broker);
  747. brokersUsage.merge(broker, -1, Integer::sum);
  748. }
  749. if (brokers.size() == replicationFactorChange.getTotalReplicationFactor()) {
  750. break;
  751. }
  752. }
  753. if (brokers.size() != replicationFactorChange.getTotalReplicationFactor()) {
  754. throw new ValidationException("Something went wrong during removing replicas");
  755. }
  756. }
  757. } else {
  758. throw new ValidationException("Replication factor already equals requested");
  759. }
  760. // Return result map
  761. return currentAssignment.entrySet().stream().collect(Collectors.toMap(
  762. e -> new TopicPartition(topicName, e.getKey()),
  763. e -> Optional.of(new NewPartitionReassignment(e.getValue()))
  764. ));
  765. }
  766. private Map<Integer, List<Integer>> getCurrentAssignment(KafkaCluster cluster, String topicName) {
  767. return cluster.getTopics().get(topicName).getPartitions().values().stream()
  768. .collect(Collectors.toMap(
  769. InternalPartition::getPartition,
  770. p -> p.getReplicas().stream()
  771. .map(InternalReplica::getBroker)
  772. .collect(Collectors.toList())
  773. ));
  774. }
  775. private Map<Integer, Integer> getBrokersMap(KafkaCluster cluster,
  776. Map<Integer, List<Integer>> currentAssignment) {
  777. Map<Integer, Integer> result = cluster.getBrokers().stream()
  778. .collect(Collectors.toMap(
  779. c -> c,
  780. c -> 0
  781. ));
  782. currentAssignment.values().forEach(brokers -> brokers
  783. .forEach(broker -> result.put(broker, result.get(broker) + 1)));
  784. return result;
  785. }
  786. }