KafkaService.java 38 KB

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