ClusterService.java 17 KB

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