TopicsService.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package com.provectus.kafka.ui.service;
  2. import static java.util.stream.Collectors.toList;
  3. import static java.util.stream.Collectors.toMap;
  4. import com.google.common.annotations.VisibleForTesting;
  5. import com.provectus.kafka.ui.exception.TopicMetadataException;
  6. import com.provectus.kafka.ui.exception.TopicNotFoundException;
  7. import com.provectus.kafka.ui.exception.ValidationException;
  8. import com.provectus.kafka.ui.mapper.ClusterMapper;
  9. import com.provectus.kafka.ui.model.Feature;
  10. import com.provectus.kafka.ui.model.InternalLogDirStats;
  11. import com.provectus.kafka.ui.model.InternalPartition;
  12. import com.provectus.kafka.ui.model.InternalPartitionsOffsets;
  13. import com.provectus.kafka.ui.model.InternalReplica;
  14. import com.provectus.kafka.ui.model.InternalTopic;
  15. import com.provectus.kafka.ui.model.InternalTopicConfig;
  16. import com.provectus.kafka.ui.model.KafkaCluster;
  17. import com.provectus.kafka.ui.model.PartitionsIncreaseDTO;
  18. import com.provectus.kafka.ui.model.PartitionsIncreaseResponseDTO;
  19. import com.provectus.kafka.ui.model.ReplicationFactorChangeDTO;
  20. import com.provectus.kafka.ui.model.ReplicationFactorChangeResponseDTO;
  21. import com.provectus.kafka.ui.model.TopicColumnsToSortDTO;
  22. import com.provectus.kafka.ui.model.TopicConfigDTO;
  23. import com.provectus.kafka.ui.model.TopicCreationDTO;
  24. import com.provectus.kafka.ui.model.TopicDTO;
  25. import com.provectus.kafka.ui.model.TopicDetailsDTO;
  26. import com.provectus.kafka.ui.model.TopicMessageSchemaDTO;
  27. import com.provectus.kafka.ui.model.TopicUpdateDTO;
  28. import com.provectus.kafka.ui.model.TopicsResponseDTO;
  29. import com.provectus.kafka.ui.serde.DeserializationService;
  30. import com.provectus.kafka.ui.util.JmxClusterUtil;
  31. import java.util.Collection;
  32. import java.util.Collections;
  33. import java.util.Comparator;
  34. import java.util.List;
  35. import java.util.Map;
  36. import java.util.Optional;
  37. import java.util.function.Function;
  38. import java.util.function.Predicate;
  39. import lombok.RequiredArgsConstructor;
  40. import lombok.Value;
  41. import org.apache.commons.lang3.StringUtils;
  42. import org.apache.kafka.clients.admin.ConfigEntry;
  43. import org.apache.kafka.clients.admin.NewPartitionReassignment;
  44. import org.apache.kafka.clients.admin.NewPartitions;
  45. import org.apache.kafka.clients.admin.OffsetSpec;
  46. import org.apache.kafka.clients.admin.TopicDescription;
  47. import org.apache.kafka.common.Node;
  48. import org.apache.kafka.common.TopicPartition;
  49. import org.springframework.stereotype.Service;
  50. import reactor.core.publisher.Mono;
  51. @Service
  52. @RequiredArgsConstructor
  53. public class TopicsService {
  54. private static final Integer DEFAULT_PAGE_SIZE = 25;
  55. private final AdminClientService adminClientService;
  56. private final ClusterMapper clusterMapper;
  57. private final DeserializationService deserializationService;
  58. private final MetricsCache metricsCache;
  59. public Mono<TopicsResponseDTO> getTopics(KafkaCluster cluster,
  60. Optional<Integer> pageNum,
  61. Optional<Integer> nullablePerPage,
  62. Optional<Boolean> showInternal,
  63. Optional<String> search,
  64. Optional<TopicColumnsToSortDTO> sortBy) {
  65. return adminClientService.get(cluster).flatMap(ac ->
  66. new Pagination(ac, metricsCache.get(cluster))
  67. .getPage(pageNum, nullablePerPage, showInternal, search, sortBy)
  68. .flatMap(page ->
  69. loadTopics(cluster, page.getTopics())
  70. .map(topics ->
  71. new TopicsResponseDTO()
  72. .topics(topics.stream().map(clusterMapper::toTopic).collect(toList()))
  73. .pageCount(page.getTotalPages()))));
  74. }
  75. private Mono<List<InternalTopic>> loadTopics(KafkaCluster c, List<String> topics) {
  76. if (topics.isEmpty()) {
  77. return Mono.just(List.of());
  78. }
  79. return adminClientService.get(c)
  80. .flatMap(ac ->
  81. ac.describeTopics(topics).zipWith(ac.getTopicsConfig(topics),
  82. (descriptions, configs) -> {
  83. metricsCache.update(c, descriptions, configs);
  84. return getPartitionOffsets(descriptions, ac).map(offsets -> {
  85. var metrics = metricsCache.get(c);
  86. return createList(
  87. topics,
  88. descriptions,
  89. configs,
  90. offsets,
  91. metrics.getJmxMetrics(),
  92. metrics.getLogDirInfo()
  93. );
  94. });
  95. })).flatMap(Function.identity());
  96. }
  97. private Mono<InternalTopic> loadTopic(KafkaCluster c, String topicName) {
  98. return loadTopics(c, List.of(topicName))
  99. .map(lst -> lst.stream().findFirst().orElseThrow(TopicNotFoundException::new));
  100. }
  101. private List<InternalTopic> createList(List<String> orderedNames,
  102. Map<String, TopicDescription> descriptions,
  103. Map<String, List<ConfigEntry>> configs,
  104. InternalPartitionsOffsets partitionsOffsets,
  105. JmxClusterUtil.JmxMetrics jmxMetrics,
  106. InternalLogDirStats logDirInfo) {
  107. return orderedNames.stream()
  108. .filter(descriptions::containsKey)
  109. .map(t -> InternalTopic.from(
  110. descriptions.get(t),
  111. configs.getOrDefault(t, List.of()),
  112. partitionsOffsets,
  113. jmxMetrics,
  114. logDirInfo
  115. ))
  116. .collect(toList());
  117. }
  118. private Mono<InternalPartitionsOffsets> getPartitionOffsets(Map<String, TopicDescription>
  119. descriptions,
  120. ReactiveAdminClient ac) {
  121. var topicPartitions = descriptions.values().stream()
  122. .flatMap(desc ->
  123. desc.partitions().stream().map(p -> new TopicPartition(desc.name(), p.partition())))
  124. .collect(toList());
  125. return ac.listOffsets(topicPartitions, OffsetSpec.earliest())
  126. .zipWith(ac.listOffsets(topicPartitions, OffsetSpec.latest()),
  127. (earliest, latest) ->
  128. topicPartitions.stream()
  129. .filter(tp -> earliest.containsKey(tp) && latest.containsKey(tp))
  130. .map(tp ->
  131. Map.entry(tp,
  132. new InternalPartitionsOffsets.Offsets(
  133. earliest.get(tp), latest.get(tp))))
  134. .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)))
  135. .map(InternalPartitionsOffsets::new);
  136. }
  137. public Mono<TopicDetailsDTO> getTopicDetails(KafkaCluster cluster, String topicName) {
  138. return loadTopic(cluster, topicName).map(clusterMapper::toTopicDetails);
  139. }
  140. public Mono<List<TopicConfigDTO>> getTopicConfigs(KafkaCluster cluster, String topicName) {
  141. return adminClientService.get(cluster)
  142. .flatMap(ac -> ac.getTopicsConfig(List.of(topicName)))
  143. .map(m -> m.values().stream().findFirst().orElseThrow(TopicNotFoundException::new))
  144. .map(lst -> lst.stream()
  145. .map(InternalTopicConfig::from)
  146. .map(clusterMapper::toTopicConfig)
  147. .collect(toList()));
  148. }
  149. private Mono<InternalTopic> createTopic(KafkaCluster c, ReactiveAdminClient adminClient,
  150. Mono<TopicCreationDTO> topicCreation) {
  151. return topicCreation.flatMap(topicData ->
  152. adminClient.createTopic(
  153. topicData.getName(),
  154. topicData.getPartitions(),
  155. topicData.getReplicationFactor().shortValue(),
  156. topicData.getConfigs()
  157. ).thenReturn(topicData)
  158. )
  159. .onErrorResume(t -> Mono.error(new TopicMetadataException(t.getMessage())))
  160. .flatMap(topicData -> loadTopic(c, topicData.getName()));
  161. }
  162. public Mono<TopicDTO> createTopic(KafkaCluster cluster, Mono<TopicCreationDTO> topicCreation) {
  163. return adminClientService.get(cluster)
  164. .flatMap(ac -> createTopic(cluster, ac, topicCreation))
  165. .map(clusterMapper::toTopic);
  166. }
  167. private Mono<InternalTopic> updateTopic(KafkaCluster cluster,
  168. String topicName,
  169. TopicUpdateDTO topicUpdate) {
  170. return adminClientService.get(cluster)
  171. .flatMap(ac ->
  172. ac.updateTopicConfig(topicName, topicUpdate.getConfigs())
  173. .then(loadTopic(cluster, topicName)));
  174. }
  175. public Mono<TopicDTO> updateTopic(KafkaCluster cl, String topicName,
  176. Mono<TopicUpdateDTO> topicUpdate) {
  177. return topicUpdate
  178. .flatMap(t -> updateTopic(cl, topicName, t))
  179. .map(clusterMapper::toTopic);
  180. }
  181. private Mono<InternalTopic> changeReplicationFactor(
  182. KafkaCluster cluster,
  183. ReactiveAdminClient adminClient,
  184. String topicName,
  185. Map<TopicPartition, Optional<NewPartitionReassignment>> reassignments
  186. ) {
  187. return adminClient.alterPartitionReassignments(reassignments)
  188. .then(loadTopic(cluster, topicName));
  189. }
  190. /**
  191. * Change topic replication factor, works on brokers versions 5.4.x and higher
  192. */
  193. public Mono<ReplicationFactorChangeResponseDTO> changeReplicationFactor(
  194. KafkaCluster cluster,
  195. String topicName,
  196. ReplicationFactorChangeDTO replicationFactorChange) {
  197. return loadTopic(cluster, topicName).flatMap(topic -> adminClientService.get(cluster)
  198. .flatMap(ac -> {
  199. Integer actual = topic.getReplicationFactor();
  200. Integer requested = replicationFactorChange.getTotalReplicationFactor();
  201. Integer brokersCount = metricsCache.get(cluster).getClusterDescription()
  202. .getNodes().size();
  203. if (requested.equals(actual)) {
  204. return Mono.error(
  205. new ValidationException(
  206. String.format("Topic already has replicationFactor %s.", actual)));
  207. }
  208. if (requested > brokersCount) {
  209. return Mono.error(
  210. new ValidationException(
  211. String.format("Requested replication factor %s more than brokers count %s.",
  212. requested, brokersCount)));
  213. }
  214. return changeReplicationFactor(cluster, ac, topicName,
  215. getPartitionsReassignments(cluster, topic,
  216. replicationFactorChange));
  217. })
  218. .map(t -> new ReplicationFactorChangeResponseDTO()
  219. .topicName(t.getName())
  220. .totalReplicationFactor(t.getReplicationFactor())));
  221. }
  222. private Map<TopicPartition, Optional<NewPartitionReassignment>> getPartitionsReassignments(
  223. KafkaCluster cluster,
  224. InternalTopic topic,
  225. ReplicationFactorChangeDTO replicationFactorChange) {
  226. // Current assignment map (Partition number -> List of brokers)
  227. Map<Integer, List<Integer>> currentAssignment = getCurrentAssignment(topic);
  228. // Brokers map (Broker id -> count)
  229. Map<Integer, Integer> brokersUsage = getBrokersMap(cluster, currentAssignment);
  230. int currentReplicationFactor = topic.getReplicationFactor();
  231. // If we should to increase Replication factor
  232. if (replicationFactorChange.getTotalReplicationFactor() > currentReplicationFactor) {
  233. // For each partition
  234. for (var assignmentList : currentAssignment.values()) {
  235. // Get brokers list sorted by usage
  236. var brokers = brokersUsage.entrySet().stream()
  237. .sorted(Map.Entry.comparingByValue())
  238. .map(Map.Entry::getKey)
  239. .collect(toList());
  240. // Iterate brokers and try to add them in assignment
  241. // while (partition replicas count != requested replication factor)
  242. for (Integer broker : brokers) {
  243. if (!assignmentList.contains(broker)) {
  244. assignmentList.add(broker);
  245. brokersUsage.merge(broker, 1, Integer::sum);
  246. }
  247. if (assignmentList.size() == replicationFactorChange.getTotalReplicationFactor()) {
  248. break;
  249. }
  250. }
  251. if (assignmentList.size() != replicationFactorChange.getTotalReplicationFactor()) {
  252. throw new ValidationException("Something went wrong during adding replicas");
  253. }
  254. }
  255. // If we should to decrease Replication factor
  256. } else if (replicationFactorChange.getTotalReplicationFactor() < currentReplicationFactor) {
  257. for (Map.Entry<Integer, List<Integer>> assignmentEntry : currentAssignment.entrySet()) {
  258. var partition = assignmentEntry.getKey();
  259. var brokers = assignmentEntry.getValue();
  260. // Get brokers list sorted by usage in reverse order
  261. var brokersUsageList = brokersUsage.entrySet().stream()
  262. .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
  263. .map(Map.Entry::getKey)
  264. .collect(toList());
  265. // Iterate brokers and try to remove them from assignment
  266. // while (partition replicas count != requested replication factor)
  267. for (Integer broker : brokersUsageList) {
  268. // Check is the broker the leader of partition
  269. if (!topic.getPartitions().get(partition).getLeader()
  270. .equals(broker)) {
  271. brokers.remove(broker);
  272. brokersUsage.merge(broker, -1, Integer::sum);
  273. }
  274. if (brokers.size() == replicationFactorChange.getTotalReplicationFactor()) {
  275. break;
  276. }
  277. }
  278. if (brokers.size() != replicationFactorChange.getTotalReplicationFactor()) {
  279. throw new ValidationException("Something went wrong during removing replicas");
  280. }
  281. }
  282. } else {
  283. throw new ValidationException("Replication factor already equals requested");
  284. }
  285. // Return result map
  286. return currentAssignment.entrySet().stream().collect(toMap(
  287. e -> new TopicPartition(topic.getName(), e.getKey()),
  288. e -> Optional.of(new NewPartitionReassignment(e.getValue()))
  289. ));
  290. }
  291. private Map<Integer, List<Integer>> getCurrentAssignment(InternalTopic topic) {
  292. return topic.getPartitions().values().stream()
  293. .collect(toMap(
  294. InternalPartition::getPartition,
  295. p -> p.getReplicas().stream()
  296. .map(InternalReplica::getBroker)
  297. .collect(toList())
  298. ));
  299. }
  300. private Map<Integer, Integer> getBrokersMap(KafkaCluster cluster,
  301. Map<Integer, List<Integer>> currentAssignment) {
  302. Map<Integer, Integer> result = metricsCache.get(cluster).getClusterDescription().getNodes()
  303. .stream()
  304. .map(Node::id)
  305. .collect(toMap(
  306. c -> c,
  307. c -> 0
  308. ));
  309. currentAssignment.values().forEach(brokers -> brokers
  310. .forEach(broker -> result.put(broker, result.get(broker) + 1)));
  311. return result;
  312. }
  313. public Mono<PartitionsIncreaseResponseDTO> increaseTopicPartitions(
  314. KafkaCluster cluster,
  315. String topicName,
  316. PartitionsIncreaseDTO partitionsIncrease) {
  317. return loadTopic(cluster, topicName).flatMap(topic ->
  318. adminClientService.get(cluster).flatMap(ac -> {
  319. Integer actualCount = topic.getPartitionCount();
  320. Integer requestedCount = partitionsIncrease.getTotalPartitionsCount();
  321. if (requestedCount < actualCount) {
  322. return Mono.error(
  323. new ValidationException(String.format(
  324. "Topic currently has %s partitions, which is higher than the requested %s.",
  325. actualCount, requestedCount)));
  326. }
  327. if (requestedCount.equals(actualCount)) {
  328. return Mono.error(
  329. new ValidationException(
  330. String.format("Topic already has %s partitions.", actualCount)));
  331. }
  332. Map<String, NewPartitions> newPartitionsMap = Collections.singletonMap(
  333. topicName,
  334. NewPartitions.increaseTo(partitionsIncrease.getTotalPartitionsCount())
  335. );
  336. return ac.createPartitions(newPartitionsMap)
  337. .then(loadTopic(cluster, topicName));
  338. })
  339. .map(t -> new PartitionsIncreaseResponseDTO()
  340. .topicName(t.getName())
  341. .totalPartitionsCount(t.getPartitionCount())));
  342. }
  343. public Mono<Void> deleteTopic(KafkaCluster cluster, String topicName) {
  344. if (metricsCache.get(cluster).getFeatures().contains(Feature.TOPIC_DELETION)) {
  345. return adminClientService.get(cluster).flatMap(c -> c.deleteTopic(topicName))
  346. .doOnSuccess(t -> metricsCache.onTopicDelete(cluster, topicName));
  347. } else {
  348. return Mono.error(new ValidationException("Topic deletion restricted"));
  349. }
  350. }
  351. public TopicMessageSchemaDTO getTopicSchema(KafkaCluster cluster, String topicName) {
  352. if (!metricsCache.get(cluster).getTopicDescriptions().containsKey(topicName)) {
  353. throw new TopicNotFoundException();
  354. }
  355. return deserializationService
  356. .getRecordDeserializerForCluster(cluster)
  357. .getTopicSchema(topicName);
  358. }
  359. @VisibleForTesting
  360. @Value
  361. static class Pagination {
  362. ReactiveAdminClient adminClient;
  363. MetricsCache.Metrics metrics;
  364. @Value
  365. static class Page {
  366. List<String> topics;
  367. int totalPages;
  368. }
  369. Mono<Page> getPage(
  370. Optional<Integer> pageNum,
  371. Optional<Integer> nullablePerPage,
  372. Optional<Boolean> showInternal,
  373. Optional<String> search,
  374. Optional<TopicColumnsToSortDTO> sortBy) {
  375. return geTopicsForPagination()
  376. .map(paginatingTopics -> {
  377. Predicate<Integer> positiveInt = i -> i > 0;
  378. int perPage = nullablePerPage.filter(positiveInt).orElse(DEFAULT_PAGE_SIZE);
  379. var topicsToSkip = (pageNum.filter(positiveInt).orElse(1) - 1) * perPage;
  380. List<InternalTopic> topics = paginatingTopics.stream()
  381. .filter(topic -> !topic.isInternal()
  382. || showInternal.map(i -> topic.isInternal() == i).orElse(true))
  383. .filter(topic ->
  384. search
  385. .map(s -> StringUtils.containsIgnoreCase(topic.getName(), s))
  386. .orElse(true))
  387. .sorted(getComparatorForTopic(sortBy))
  388. .collect(toList());
  389. var totalPages = (topics.size() / perPage)
  390. + (topics.size() % perPage == 0 ? 0 : 1);
  391. List<String> topicsToRender = topics.stream()
  392. .skip(topicsToSkip)
  393. .limit(perPage)
  394. .map(InternalTopic::getName)
  395. .collect(toList());
  396. return new Page(topicsToRender, totalPages);
  397. });
  398. }
  399. private Comparator<InternalTopic> getComparatorForTopic(
  400. Optional<TopicColumnsToSortDTO> sortBy) {
  401. var defaultComparator = Comparator.comparing(InternalTopic::getName);
  402. if (sortBy.isEmpty()) {
  403. return defaultComparator;
  404. }
  405. switch (sortBy.get()) {
  406. case TOTAL_PARTITIONS:
  407. return Comparator.comparing(InternalTopic::getPartitionCount);
  408. case OUT_OF_SYNC_REPLICAS:
  409. return Comparator.comparing(t -> t.getReplicas() - t.getInSyncReplicas());
  410. case REPLICATION_FACTOR:
  411. return Comparator.comparing(InternalTopic::getReplicationFactor);
  412. case NAME:
  413. default:
  414. return defaultComparator;
  415. }
  416. }
  417. private Mono<List<String>> filterExisting(Collection<String> topics) {
  418. return adminClient.listTopics(true)
  419. .map(existing -> existing.stream().filter(topics::contains).collect(toList()));
  420. }
  421. private Mono<List<InternalTopic>> geTopicsForPagination() {
  422. return filterExisting(metrics.getTopicDescriptions().keySet())
  423. .map(lst -> lst.stream()
  424. .map(topicName ->
  425. InternalTopic.from(
  426. metrics.getTopicDescriptions().get(topicName),
  427. metrics.getTopicConfigs().getOrDefault(topicName, List.of()),
  428. InternalPartitionsOffsets.empty(),
  429. metrics.getJmxMetrics(),
  430. metrics.getLogDirInfo()))
  431. .collect(toList())
  432. );
  433. }
  434. }
  435. }