KafkaService.java 38 KB

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