ClusterService.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package com.provectus.kafka.ui.service;
  2. import com.provectus.kafka.ui.exception.ClusterNotFoundException;
  3. import com.provectus.kafka.ui.exception.IllegalEntityStateException;
  4. import com.provectus.kafka.ui.exception.NotFoundException;
  5. import com.provectus.kafka.ui.exception.TopicNotFoundException;
  6. import com.provectus.kafka.ui.mapper.ClusterMapper;
  7. import com.provectus.kafka.ui.model.Broker;
  8. import com.provectus.kafka.ui.model.BrokerMetrics;
  9. import com.provectus.kafka.ui.model.Cluster;
  10. import com.provectus.kafka.ui.model.ClusterMetrics;
  11. import com.provectus.kafka.ui.model.ClusterStats;
  12. import com.provectus.kafka.ui.model.ConsumerGroup;
  13. import com.provectus.kafka.ui.model.ConsumerGroupDetails;
  14. import com.provectus.kafka.ui.model.ConsumerPosition;
  15. import com.provectus.kafka.ui.model.CreateTopicMessage;
  16. import com.provectus.kafka.ui.model.ExtendedAdminClient;
  17. import com.provectus.kafka.ui.model.InternalTopic;
  18. import com.provectus.kafka.ui.model.KafkaCluster;
  19. import com.provectus.kafka.ui.model.Topic;
  20. import com.provectus.kafka.ui.model.TopicColumnsToSort;
  21. import com.provectus.kafka.ui.model.TopicConfig;
  22. import com.provectus.kafka.ui.model.TopicConsumerGroups;
  23. import com.provectus.kafka.ui.model.TopicCreation;
  24. import com.provectus.kafka.ui.model.TopicDetails;
  25. import com.provectus.kafka.ui.model.TopicMessage;
  26. import com.provectus.kafka.ui.model.TopicMessageSchema;
  27. import com.provectus.kafka.ui.model.TopicUpdate;
  28. import com.provectus.kafka.ui.model.TopicsResponse;
  29. import com.provectus.kafka.ui.serde.DeserializationService;
  30. import com.provectus.kafka.ui.util.ClusterUtil;
  31. import java.util.Collections;
  32. import java.util.Comparator;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Optional;
  36. import java.util.function.Predicate;
  37. import java.util.stream.Collectors;
  38. import java.util.stream.Stream;
  39. import lombok.RequiredArgsConstructor;
  40. import lombok.SneakyThrows;
  41. import lombok.extern.log4j.Log4j2;
  42. import org.apache.commons.lang3.StringUtils;
  43. import org.apache.kafka.clients.admin.DeleteConsumerGroupsResult;
  44. import org.apache.kafka.common.TopicPartition;
  45. import org.apache.kafka.common.errors.GroupIdNotFoundException;
  46. import org.apache.kafka.common.errors.GroupNotEmptyException;
  47. import org.jetbrains.annotations.NotNull;
  48. import org.springframework.stereotype.Service;
  49. import reactor.core.publisher.Flux;
  50. import reactor.core.publisher.Mono;
  51. import reactor.util.function.Tuples;
  52. @Service
  53. @RequiredArgsConstructor
  54. @Log4j2
  55. public class ClusterService {
  56. private static final Integer DEFAULT_PAGE_SIZE = 25;
  57. private final ClustersStorage clustersStorage;
  58. private final ClusterMapper clusterMapper;
  59. private final KafkaService kafkaService;
  60. private final ConsumingService consumingService;
  61. private final DeserializationService deserializationService;
  62. public List<Cluster> getClusters() {
  63. return clustersStorage.getKafkaClusters()
  64. .stream()
  65. .map(clusterMapper::toCluster)
  66. .collect(Collectors.toList());
  67. }
  68. public Mono<BrokerMetrics> getBrokerMetrics(String name, Integer id) {
  69. return Mono.justOrEmpty(clustersStorage.getClusterByName(name)
  70. .map(c -> c.getMetrics().getInternalBrokerMetrics())
  71. .map(m -> m.get(id))
  72. .map(clusterMapper::toBrokerMetrics));
  73. }
  74. public Mono<ClusterStats> getClusterStats(String name) {
  75. return Mono.justOrEmpty(
  76. clustersStorage.getClusterByName(name)
  77. .map(KafkaCluster::getMetrics)
  78. .map(clusterMapper::toClusterStats)
  79. );
  80. }
  81. public Mono<ClusterMetrics> getClusterMetrics(String name) {
  82. return Mono.justOrEmpty(
  83. clustersStorage.getClusterByName(name)
  84. .map(KafkaCluster::getMetrics)
  85. .map(clusterMapper::toClusterMetrics)
  86. );
  87. }
  88. public TopicsResponse getTopics(String name, Optional<Integer> page,
  89. Optional<Integer> nullablePerPage,
  90. Optional<Boolean> showInternal,
  91. Optional<String> search,
  92. Optional<TopicColumnsToSort> sortBy) {
  93. Predicate<Integer> positiveInt = i -> i > 0;
  94. int perPage = nullablePerPage.filter(positiveInt).orElse(DEFAULT_PAGE_SIZE);
  95. var topicsToSkip = (page.filter(positiveInt).orElse(1) - 1) * perPage;
  96. var cluster = clustersStorage.getClusterByName(name)
  97. .orElseThrow(ClusterNotFoundException::new);
  98. List<Topic> topics = cluster.getTopics().values().stream()
  99. .filter(topic -> !topic.isInternal()
  100. || showInternal
  101. .map(i -> topic.isInternal() == i)
  102. .orElse(true))
  103. .filter(topic ->
  104. search
  105. .map(s -> StringUtils.containsIgnoreCase(topic.getName(), s))
  106. .orElse(true))
  107. .sorted(getComparatorForTopic(sortBy))
  108. .map(clusterMapper::toTopic)
  109. .collect(Collectors.toList());
  110. var totalPages = (topics.size() / perPage)
  111. + (topics.size() % perPage == 0 ? 0 : 1);
  112. return new TopicsResponse()
  113. .pageCount(totalPages)
  114. .topics(
  115. topics.stream()
  116. .skip(topicsToSkip)
  117. .limit(perPage)
  118. .collect(Collectors.toList())
  119. );
  120. }
  121. private Comparator<InternalTopic> getComparatorForTopic(Optional<TopicColumnsToSort> sortBy) {
  122. var defaultComparator = Comparator.comparing(InternalTopic::getName);
  123. if (sortBy.isEmpty()) {
  124. return defaultComparator;
  125. }
  126. switch (sortBy.get()) {
  127. case TOTAL_PARTITIONS:
  128. return Comparator.comparing(InternalTopic::getPartitionCount);
  129. case OUT_OF_SYNC_REPLICAS:
  130. return Comparator.comparing(t -> t.getReplicas() - t.getInSyncReplicas());
  131. case NAME:
  132. default:
  133. return defaultComparator;
  134. }
  135. }
  136. public Optional<TopicDetails> getTopicDetails(String name, String topicName) {
  137. return clustersStorage.getClusterByName(name)
  138. .flatMap(c ->
  139. Optional.ofNullable(
  140. c.getTopics().get(topicName)
  141. ).map(
  142. t -> t.toBuilder().partitions(
  143. kafkaService.getTopicPartitions(c, t)
  144. ).build()
  145. ).map(t -> clusterMapper.toTopicDetails(t, c.getMetrics()))
  146. );
  147. }
  148. public Optional<List<TopicConfig>> getTopicConfigs(String name, String topicName) {
  149. return clustersStorage.getClusterByName(name)
  150. .map(KafkaCluster::getTopics)
  151. .map(t -> t.get(topicName))
  152. .map(t -> t.getTopicConfigs().stream().map(clusterMapper::toTopicConfig)
  153. .collect(Collectors.toList()));
  154. }
  155. public Mono<Topic> createTopic(String clusterName, Mono<TopicCreation> topicCreation) {
  156. return clustersStorage.getClusterByName(clusterName).map(cluster ->
  157. kafkaService.createTopic(cluster, topicCreation)
  158. .doOnNext(t -> updateCluster(t, clusterName, cluster))
  159. .map(clusterMapper::toTopic)
  160. ).orElse(Mono.empty());
  161. }
  162. @SneakyThrows
  163. public Mono<ConsumerGroupDetails> getConsumerGroupDetail(String clusterName,
  164. String consumerGroupId) {
  165. var cluster = clustersStorage.getClusterByName(clusterName).orElseThrow(Throwable::new);
  166. return kafkaService.getOrCreateAdminClient(cluster).map(ac ->
  167. ac.getAdminClient().describeConsumerGroups(Collections.singletonList(consumerGroupId)).all()
  168. ).flatMap(groups ->
  169. kafkaService.groupMetadata(cluster, consumerGroupId)
  170. .flatMap(offsets -> {
  171. Map<TopicPartition, Long> endOffsets =
  172. kafkaService.topicPartitionsEndOffsets(cluster, offsets.keySet());
  173. return ClusterUtil.toMono(groups).map(s ->
  174. Tuples.of(
  175. s.get(consumerGroupId),
  176. s.get(consumerGroupId).members().stream()
  177. .flatMap(c ->
  178. Stream.of(
  179. ClusterUtil.convertToConsumerTopicPartitionDetails(
  180. c, offsets, endOffsets, consumerGroupId
  181. )
  182. )
  183. )
  184. .collect(Collectors.toList()).stream()
  185. .flatMap(t ->
  186. t.stream().flatMap(Stream::of)
  187. ).collect(Collectors.toList())
  188. )
  189. );
  190. }).map(c -> ClusterUtil.convertToConsumerGroupDetails(c.getT1(), c.getT2()))
  191. );
  192. }
  193. public Mono<List<ConsumerGroup>> getConsumerGroups(String clusterName) {
  194. return Mono.justOrEmpty(clustersStorage.getClusterByName(clusterName))
  195. .switchIfEmpty(Mono.error(ClusterNotFoundException::new))
  196. .flatMap(kafkaService::getConsumerGroups);
  197. }
  198. public Mono<TopicConsumerGroups> getTopicConsumerGroupDetail(
  199. String clusterName, String topicName) {
  200. return Mono.justOrEmpty(clustersStorage.getClusterByName(clusterName))
  201. .switchIfEmpty(Mono.error(ClusterNotFoundException::new))
  202. .flatMap(c -> kafkaService.getTopicConsumerGroups(c, topicName));
  203. }
  204. public Flux<Broker> getBrokers(String clusterName) {
  205. return kafkaService
  206. .getOrCreateAdminClient(clustersStorage.getClusterByName(clusterName).orElseThrow())
  207. .flatMap(client -> ClusterUtil.toMono(client.getAdminClient().describeCluster().nodes())
  208. .map(n -> n.stream().map(node -> {
  209. Broker broker = new Broker();
  210. broker.setId(node.id());
  211. broker.setHost(node.host());
  212. return broker;
  213. }).collect(Collectors.toList())))
  214. .flatMapMany(Flux::fromIterable);
  215. }
  216. @SneakyThrows
  217. public Mono<Topic> updateTopic(String clusterName, String topicName,
  218. Mono<TopicUpdate> topicUpdate) {
  219. return clustersStorage.getClusterByName(clusterName).map(cl ->
  220. topicUpdate
  221. .flatMap(t -> kafkaService.updateTopic(cl, topicName, t))
  222. .doOnNext(t -> updateCluster(t, clusterName, cl))
  223. .map(clusterMapper::toTopic)
  224. ).orElse(Mono.empty());
  225. }
  226. public Mono<Void> deleteTopic(String clusterName, String topicName) {
  227. var cluster = clustersStorage.getClusterByName(clusterName)
  228. .orElseThrow(ClusterNotFoundException::new);
  229. var topic = getTopicDetails(clusterName, topicName)
  230. .orElseThrow(TopicNotFoundException::new);
  231. return kafkaService.deleteTopic(cluster, topic.getName())
  232. .doOnNext(t -> updateCluster(topicName, clusterName, cluster));
  233. }
  234. private KafkaCluster updateCluster(InternalTopic topic, String clusterName,
  235. KafkaCluster cluster) {
  236. final KafkaCluster updatedCluster = kafkaService.getUpdatedCluster(cluster, topic);
  237. clustersStorage.setKafkaCluster(clusterName, updatedCluster);
  238. return updatedCluster;
  239. }
  240. private KafkaCluster updateCluster(String topicToDelete, String clusterName,
  241. KafkaCluster cluster) {
  242. final KafkaCluster updatedCluster = kafkaService.getUpdatedCluster(cluster, topicToDelete);
  243. clustersStorage.setKafkaCluster(clusterName, updatedCluster);
  244. return updatedCluster;
  245. }
  246. public Flux<TopicMessage> getMessages(String clusterName, String topicName,
  247. ConsumerPosition consumerPosition, String query,
  248. Integer limit) {
  249. return clustersStorage.getClusterByName(clusterName)
  250. .map(c -> consumingService.loadMessages(c, topicName, consumerPosition, query, limit))
  251. .orElse(Flux.empty());
  252. }
  253. public Mono<Void> deleteTopicMessages(String clusterName, String topicName,
  254. List<Integer> partitions) {
  255. var cluster = clustersStorage.getClusterByName(clusterName)
  256. .orElseThrow(ClusterNotFoundException::new);
  257. if (!cluster.getTopics().containsKey(topicName)) {
  258. throw new TopicNotFoundException();
  259. }
  260. return consumingService.offsetsForDeletion(cluster, topicName, partitions)
  261. .flatMap(offsets -> kafkaService.deleteTopicMessages(cluster, offsets));
  262. }
  263. public Mono<Void> deleteConsumerGroupById(String clusterName,
  264. String groupId) {
  265. return clustersStorage.getClusterByName(clusterName)
  266. .map(cluster -> kafkaService.getOrCreateAdminClient(cluster)
  267. .map(ExtendedAdminClient::getAdminClient)
  268. .map(adminClient -> adminClient.deleteConsumerGroups(List.of(groupId)))
  269. .map(DeleteConsumerGroupsResult::all)
  270. .flatMap(ClusterUtil::toMono)
  271. .onErrorResume(this::reThrowCustomException)
  272. )
  273. .orElse(Mono.empty());
  274. }
  275. public TopicMessageSchema getTopicSchema(String clusterName, String topicName) {
  276. var cluster = clustersStorage.getClusterByName(clusterName)
  277. .orElseThrow(ClusterNotFoundException::new);
  278. if (!cluster.getTopics().containsKey(topicName)) {
  279. throw new TopicNotFoundException();
  280. }
  281. return deserializationService
  282. .getRecordDeserializerForCluster(cluster)
  283. .getTopicSchema(topicName);
  284. }
  285. public Mono<Void> sendMessage(String clusterName, String topicName, CreateTopicMessage msg) {
  286. var cluster = clustersStorage.getClusterByName(clusterName)
  287. .orElseThrow(ClusterNotFoundException::new);
  288. if (!cluster.getTopics().containsKey(topicName)) {
  289. throw new TopicNotFoundException();
  290. }
  291. return kafkaService.sendMessage(cluster, topicName, msg).then();
  292. }
  293. @NotNull
  294. private Mono<Void> reThrowCustomException(Throwable e) {
  295. if (e instanceof GroupIdNotFoundException) {
  296. return Mono.error(new NotFoundException("The group id does not exist"));
  297. } else if (e instanceof GroupNotEmptyException) {
  298. return Mono.error(new IllegalEntityStateException("The group is not empty"));
  299. } else {
  300. return Mono.error(e);
  301. }
  302. }
  303. }