KafkaService.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package com.provectus.kafka.ui.kafka;
  2. import com.provectus.kafka.ui.cluster.model.*;
  3. import com.provectus.kafka.ui.cluster.util.ClusterUtil;
  4. import com.provectus.kafka.ui.model.ConsumerGroup;
  5. import com.provectus.kafka.ui.model.ServerStatus;
  6. import com.provectus.kafka.ui.model.Topic;
  7. import com.provectus.kafka.ui.model.TopicFormData;
  8. import com.provectus.kafka.ui.zookeeper.ZookeeperService;
  9. import lombok.RequiredArgsConstructor;
  10. import lombok.SneakyThrows;
  11. import lombok.extern.log4j.Log4j2;
  12. import org.apache.kafka.clients.admin.*;
  13. import org.apache.kafka.common.KafkaFuture;
  14. import org.apache.kafka.common.Node;
  15. import org.apache.kafka.common.config.ConfigResource;
  16. import org.springframework.beans.factory.annotation.Value;
  17. import org.springframework.stereotype.Service;
  18. import reactor.core.publisher.Mono;
  19. import reactor.util.function.Tuple2;
  20. import reactor.util.function.Tuples;
  21. import java.util.Collections;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Properties;
  25. import java.util.concurrent.ConcurrentHashMap;
  26. import java.util.stream.Collectors;
  27. import java.util.stream.Stream;
  28. @Service
  29. @RequiredArgsConstructor
  30. @Log4j2
  31. public class KafkaService {
  32. @Value("${kafka.admin-client-timeout}")
  33. private int clientTimeout;
  34. private static final ListTopicsOptions LIST_TOPICS_OPTIONS = new ListTopicsOptions().listInternal(true);
  35. private final ZookeeperService zookeeperService;
  36. private final Map<String, ExtendedAdminClient> adminClientCache = new ConcurrentHashMap<>();
  37. @SneakyThrows
  38. public Mono<KafkaCluster> getUpdatedCluster(KafkaCluster cluster) {
  39. return getOrCreateAdminClient(cluster).flatMap(
  40. ac -> getClusterMetrics(ac.getAdminClient()).flatMap( clusterMetrics ->
  41. getTopicsData(ac.getAdminClient()).flatMap( topics ->
  42. loadTopicsConfig(ac.getAdminClient(), topics.stream().map(InternalTopic::getName).collect(Collectors.toList()))
  43. .map( configs -> mergeWithConfigs(topics, configs) )
  44. ).map( topics -> buildFromData(cluster, clusterMetrics, topics))
  45. )
  46. ).onErrorResume(
  47. e -> Mono.just(cluster.toBuilder()
  48. .status(ServerStatus.OFFLINE)
  49. .lastKafkaException(e)
  50. .build())
  51. );
  52. }
  53. private KafkaCluster buildFromData(KafkaCluster currentCluster, InternalClusterMetrics brokersMetrics, Map<String, InternalTopic> topics) {
  54. InternalClusterMetrics.InternalClusterMetricsBuilder metricsBuilder = brokersMetrics.toBuilder();
  55. InternalClusterMetrics topicsMetrics = collectTopicsMetrics(topics);
  56. ServerStatus zookeeperStatus = ServerStatus.OFFLINE;
  57. Throwable zookeeperException = null;
  58. try {
  59. zookeeperStatus = zookeeperService.isZookeeperOnline(currentCluster) ? ServerStatus.ONLINE : ServerStatus.OFFLINE;
  60. } catch (Throwable e) {
  61. zookeeperException = e;
  62. }
  63. InternalClusterMetrics clusterMetrics = metricsBuilder
  64. .activeControllers(brokersMetrics.getActiveControllers())
  65. .topicCount(topicsMetrics.getTopicCount())
  66. .brokerCount(brokersMetrics.getBrokerCount())
  67. .underReplicatedPartitionCount(topicsMetrics.getUnderReplicatedPartitionCount())
  68. .inSyncReplicasCount(topicsMetrics.getInSyncReplicasCount())
  69. .outOfSyncReplicasCount(topicsMetrics.getOutOfSyncReplicasCount())
  70. .onlinePartitionCount(topicsMetrics.getOnlinePartitionCount())
  71. .offlinePartitionCount(topicsMetrics.getOfflinePartitionCount())
  72. .zooKeeperStatus(ClusterUtil.convertToIntServerStatus(zookeeperStatus))
  73. .build();
  74. return currentCluster.toBuilder()
  75. .status(ServerStatus.ONLINE)
  76. .zookeeperStatus(zookeeperStatus)
  77. .lastZookeeperException(zookeeperException)
  78. .lastKafkaException(null)
  79. .metrics(clusterMetrics)
  80. .topics(topics)
  81. .build();
  82. }
  83. private InternalClusterMetrics collectTopicsMetrics(Map<String,InternalTopic> topics) {
  84. int underReplicatedPartitions = 0;
  85. int inSyncReplicasCount = 0;
  86. int outOfSyncReplicasCount = 0;
  87. int onlinePartitionCount = 0;
  88. int offlinePartitionCount = 0;
  89. for (InternalTopic topic : topics.values()) {
  90. underReplicatedPartitions += topic.getUnderReplicatedPartitions();
  91. inSyncReplicasCount += topic.getInSyncReplicas();
  92. outOfSyncReplicasCount += (topic.getReplicas() - topic.getInSyncReplicas());
  93. onlinePartitionCount += topic.getPartitions().stream().mapToInt(s -> s.getLeader() == null ? 0 : 1).sum();
  94. offlinePartitionCount += topic.getPartitions().stream().mapToInt(s -> s.getLeader() != null ? 0 : 1).sum();
  95. }
  96. return InternalClusterMetrics.builder()
  97. .underReplicatedPartitionCount(underReplicatedPartitions)
  98. .inSyncReplicasCount(inSyncReplicasCount)
  99. .outOfSyncReplicasCount(outOfSyncReplicasCount)
  100. .onlinePartitionCount(onlinePartitionCount)
  101. .offlinePartitionCount(offlinePartitionCount)
  102. .topicCount(topics.size())
  103. .build();
  104. }
  105. private Map<String, InternalTopic> mergeWithConfigs(List<InternalTopic> topics, Map<String, List<InternalTopicConfig>> configs) {
  106. return topics.stream().map(
  107. t -> t.toBuilder().topicConfigs(configs.get(t.getName())).build()
  108. ).collect(Collectors.toMap(
  109. InternalTopic::getName,
  110. e -> e
  111. ));
  112. }
  113. @SneakyThrows
  114. private Mono<List<InternalTopic>> getTopicsData(AdminClient adminClient) {
  115. return ClusterUtil.toMono(adminClient.listTopics(LIST_TOPICS_OPTIONS).names())
  116. .flatMap(topics -> ClusterUtil.toMono(adminClient.describeTopics(topics).all()))
  117. .map( m -> m.values().stream().map(ClusterUtil::mapToInternalTopic).collect(Collectors.toList()));
  118. }
  119. private Mono<InternalClusterMetrics> getClusterMetrics(AdminClient client) {
  120. return ClusterUtil.toMono(client.describeCluster().nodes())
  121. .flatMap(brokers ->
  122. ClusterUtil.toMono(client.describeCluster().controller()).map(
  123. c -> {
  124. InternalClusterMetrics.InternalClusterMetricsBuilder builder = InternalClusterMetrics.builder();
  125. builder.brokerCount(brokers.size()).activeControllers(c != null ? 1 : 0);
  126. // TODO: fill bytes in/out metrics
  127. List<Integer> brokerIds = brokers.stream().map(Node::id).collect(Collectors.toList());
  128. return builder.build();
  129. }
  130. )
  131. );
  132. }
  133. public Mono<InternalTopic> createTopic(KafkaCluster cluster, Mono<TopicFormData> topicFormData) {
  134. return getOrCreateAdminClient(cluster).flatMap(ac -> createTopic(ac.getAdminClient(), topicFormData));
  135. }
  136. @SneakyThrows
  137. public Mono<InternalTopic> createTopic(AdminClient adminClient, Mono<TopicFormData> topicFormData) {
  138. return topicFormData.flatMap(
  139. topicData -> {
  140. NewTopic newTopic = new NewTopic(topicData.getName(), topicData.getPartitions(), topicData.getReplicationFactor().shortValue());
  141. newTopic.configs(topicData.getConfigs());
  142. return createTopic(adminClient, newTopic).map( v -> topicData);
  143. }).flatMap(topicData -> {
  144. var tdw = adminClient.describeTopics(Collections.singletonList(topicData.getName()));
  145. return getTopicDescription(tdw.values().get(topicData.getName()), topicData.getName());
  146. })
  147. .switchIfEmpty(Mono.error(new RuntimeException("Can't find created topic")))
  148. .map(ClusterUtil::mapToInternalTopic)
  149. .flatMap( t ->
  150. loadTopicsConfig(adminClient, Collections.singletonList(t.getName()))
  151. .map( c -> mergeWithConfigs(Collections.singletonList(t), c))
  152. .map( m -> m.values().iterator().next())
  153. );
  154. }
  155. @SneakyThrows
  156. private Mono<String> getClusterId(AdminClient adminClient) {
  157. return ClusterUtil.toMono(adminClient.describeCluster().clusterId());
  158. }
  159. public Mono<ExtendedAdminClient> getOrCreateAdminClient(KafkaCluster cluster) {
  160. return Mono.justOrEmpty(adminClientCache.get(cluster.getName()))
  161. .switchIfEmpty(createAdminClient(cluster))
  162. .map(e -> adminClientCache.computeIfAbsent(cluster.getName(), key -> e));
  163. }
  164. public Mono<ExtendedAdminClient> createAdminClient(KafkaCluster kafkaCluster) {
  165. Properties properties = new Properties();
  166. properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaCluster.getBootstrapServers());
  167. properties.put(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, clientTimeout);
  168. AdminClient adminClient = AdminClient.create(properties);
  169. return ExtendedAdminClient.extendedAdminClient(adminClient);
  170. }
  171. private Mono<TopicDescription> getTopicDescription(KafkaFuture<TopicDescription> entry, String topicName) {
  172. return ClusterUtil.toMono(entry)
  173. .onErrorResume(e -> {
  174. log.error("Can't get topic with name: " + topicName);
  175. return Mono.empty();
  176. });
  177. }
  178. @SneakyThrows
  179. private Mono<Map<String, List<InternalTopicConfig>>> loadTopicsConfig(AdminClient adminClient, List<String> topicNames) {
  180. List<ConfigResource> resources = topicNames.stream()
  181. .map(topicName -> new ConfigResource(ConfigResource.Type.TOPIC, topicName))
  182. .collect(Collectors.toList());
  183. return ClusterUtil.toMono(adminClient.describeConfigs(resources).all())
  184. .map(configs ->
  185. configs.entrySet().stream().map(
  186. c -> Tuples.of(
  187. c.getKey().name(),
  188. c.getValue().entries().stream().map(ClusterUtil::mapToInternalTopicConfig).collect(Collectors.toList())
  189. )
  190. ).collect(Collectors.toMap(
  191. Tuple2::getT1,
  192. Tuple2::getT2
  193. ))
  194. );
  195. }
  196. public Mono<List<ConsumerGroup>> getConsumerGroups(KafkaCluster cluster) {
  197. return getOrCreateAdminClient(cluster).flatMap(ac -> ClusterUtil.toMono(ac.getAdminClient().listConsumerGroups().all())
  198. .flatMap(s -> ClusterUtil.toMono(ac.getAdminClient()
  199. .describeConsumerGroups(s.stream().map(ConsumerGroupListing::groupId).collect(Collectors.toList())).all()))
  200. .map(s -> s.values().stream()
  201. .map(c -> ClusterUtil.convertToConsumerGroup(c, cluster)).collect(Collectors.toList())));
  202. }
  203. @SneakyThrows
  204. private Mono<String> createTopic(AdminClient adminClient, NewTopic newTopic) {
  205. return ClusterUtil.toMono(adminClient.createTopics(Collections.singletonList(newTopic)).all(), newTopic.name());
  206. }
  207. @SneakyThrows
  208. public Mono<Topic> updateTopic(KafkaCluster cluster, String topicName, TopicFormData topicFormData) {
  209. ConfigResource topicCR = new ConfigResource(ConfigResource.Type.TOPIC, topicName);
  210. return getOrCreateAdminClient(cluster)
  211. .flatMap(ac -> {
  212. if (ac.getSupportedFeatures().contains(ExtendedAdminClient.SupportedFeature.INCREMENTAL_ALTER_CONFIGS)) {
  213. return incrementalAlterConfig(topicFormData, topicCR, ac)
  214. .flatMap(c -> getUpdatedTopic(ac, topicName));
  215. } else {
  216. return alterConfig(topicFormData, topicCR, ac)
  217. .flatMap(c -> getUpdatedTopic(ac, topicName));
  218. }
  219. });
  220. }
  221. private Mono<Topic> getUpdatedTopic (ExtendedAdminClient ac, String topicName) {
  222. return getTopicsData(ac.getAdminClient())
  223. .map(s -> s.stream()
  224. .filter(t -> t.getName().equals(topicName)).findFirst().orElseThrow())
  225. .map(ClusterUtil::convertToTopic);
  226. }
  227. private Mono<String> incrementalAlterConfig(TopicFormData topicFormData, ConfigResource topicCR, ExtendedAdminClient ac) {
  228. List<AlterConfigOp> listOp = topicFormData.getConfigs().entrySet().stream()
  229. .flatMap(cfg -> Stream.of(new AlterConfigOp(new ConfigEntry(cfg.getKey(), cfg.getValue()), AlterConfigOp.OpType.SET))).collect(Collectors.toList());
  230. return ClusterUtil.toMono(ac.getAdminClient().incrementalAlterConfigs(Collections.singletonMap(topicCR, listOp)).all(), topicCR.name());
  231. }
  232. private Mono<String> alterConfig(TopicFormData topicFormData, ConfigResource topicCR, ExtendedAdminClient ac) {
  233. List<ConfigEntry> configEntries = topicFormData.getConfigs().entrySet().stream()
  234. .flatMap(cfg -> Stream.of(new ConfigEntry(cfg.getKey(), cfg.getValue()))).collect(Collectors.toList());
  235. Config config = new Config(configEntries);
  236. Map<ConfigResource, Config> map = Collections.singletonMap(topicCR, config);
  237. return ClusterUtil.toMono(ac.getAdminClient().alterConfigs(map).all(), topicCR.name());
  238. }
  239. }