ClusterService.java 16 KB

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