ConsumerGroupService.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package com.provectus.kafka.ui.service;
  2. import com.google.common.collect.Streams;
  3. import com.google.common.collect.Table;
  4. import com.provectus.kafka.ui.model.ConsumerGroupOrderingDTO;
  5. import com.provectus.kafka.ui.model.InternalConsumerGroup;
  6. import com.provectus.kafka.ui.model.InternalTopicConsumerGroup;
  7. import com.provectus.kafka.ui.model.KafkaCluster;
  8. import com.provectus.kafka.ui.model.SortOrderDTO;
  9. import com.provectus.kafka.ui.service.rbac.AccessControlService;
  10. import com.provectus.kafka.ui.util.SslPropertiesUtil;
  11. import java.util.ArrayList;
  12. import java.util.Collection;
  13. import java.util.Comparator;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Properties;
  18. import java.util.function.ToIntFunction;
  19. import java.util.stream.Collectors;
  20. import java.util.stream.Stream;
  21. import javax.annotation.Nullable;
  22. import lombok.RequiredArgsConstructor;
  23. import org.apache.commons.lang3.StringUtils;
  24. import org.apache.kafka.clients.admin.ConsumerGroupDescription;
  25. import org.apache.kafka.clients.admin.ConsumerGroupListing;
  26. import org.apache.kafka.clients.admin.OffsetSpec;
  27. import org.apache.kafka.clients.consumer.ConsumerConfig;
  28. import org.apache.kafka.clients.consumer.KafkaConsumer;
  29. import org.apache.kafka.common.ConsumerGroupState;
  30. import org.apache.kafka.common.TopicPartition;
  31. import org.apache.kafka.common.serialization.BytesDeserializer;
  32. import org.apache.kafka.common.utils.Bytes;
  33. import org.springframework.stereotype.Service;
  34. import reactor.core.publisher.Mono;
  35. @Service
  36. @RequiredArgsConstructor
  37. public class ConsumerGroupService {
  38. private final AdminClientService adminClientService;
  39. private final AccessControlService accessControlService;
  40. private Mono<List<InternalConsumerGroup>> getConsumerGroups(
  41. ReactiveAdminClient ac,
  42. List<ConsumerGroupDescription> descriptions) {
  43. var groupNames = descriptions.stream().map(ConsumerGroupDescription::groupId).toList();
  44. // 1. getting committed offsets for all groups
  45. return ac.listConsumerGroupOffsets(groupNames, null)
  46. .flatMap((Table<String, TopicPartition, Long> committedOffsets) -> {
  47. // 2. getting end offsets for partitions with committed offsets
  48. return ac.listOffsets(committedOffsets.columnKeySet(), OffsetSpec.latest(), false)
  49. .map(endOffsets ->
  50. descriptions.stream()
  51. .map(desc -> {
  52. var groupOffsets = committedOffsets.row(desc.groupId());
  53. var endOffsetsForGroup = new HashMap<>(endOffsets);
  54. endOffsetsForGroup.keySet().retainAll(groupOffsets.keySet());
  55. // 3. gathering description & offsets
  56. return InternalConsumerGroup.create(desc, groupOffsets, endOffsetsForGroup);
  57. })
  58. .collect(Collectors.toList()));
  59. });
  60. }
  61. public Mono<List<InternalTopicConsumerGroup>> getConsumerGroupsForTopic(KafkaCluster cluster,
  62. String topic) {
  63. return adminClientService.get(cluster)
  64. // 1. getting topic's end offsets
  65. .flatMap(ac -> ac.listTopicOffsets(topic, OffsetSpec.latest(), false)
  66. .flatMap(endOffsets -> {
  67. var tps = new ArrayList<>(endOffsets.keySet());
  68. // 2. getting all consumer groups
  69. return describeConsumerGroups(ac)
  70. .flatMap((List<ConsumerGroupDescription> groups) -> {
  71. // 3. trying to find committed offsets for topic
  72. var groupNames = groups.stream().map(ConsumerGroupDescription::groupId).toList();
  73. return ac.listConsumerGroupOffsets(groupNames, tps).map(offsets ->
  74. groups.stream()
  75. // 4. keeping only groups that relates to topic
  76. .filter(g -> isConsumerGroupRelatesToTopic(topic, g, offsets.containsRow(g.groupId())))
  77. .map(g ->
  78. // 5. constructing results
  79. InternalTopicConsumerGroup.create(topic, g, offsets.row(g.groupId()), endOffsets))
  80. .toList()
  81. );
  82. }
  83. );
  84. }));
  85. }
  86. private boolean isConsumerGroupRelatesToTopic(String topic,
  87. ConsumerGroupDescription description,
  88. boolean hasCommittedOffsets) {
  89. boolean hasActiveMembersForTopic = description.members()
  90. .stream()
  91. .anyMatch(m -> m.assignment().topicPartitions().stream().anyMatch(tp -> tp.topic().equals(topic)));
  92. return hasActiveMembersForTopic || hasCommittedOffsets;
  93. }
  94. public record ConsumerGroupsPage(List<InternalConsumerGroup> consumerGroups, int totalPages) {
  95. }
  96. public Mono<ConsumerGroupsPage> getConsumerGroupsPage(
  97. KafkaCluster cluster,
  98. int pageNum,
  99. int perPage,
  100. @Nullable String search,
  101. ConsumerGroupOrderingDTO orderBy,
  102. SortOrderDTO sortOrderDto) {
  103. return adminClientService.get(cluster).flatMap(ac ->
  104. ac.listConsumerGroups()
  105. .map(listing -> search == null
  106. ? listing
  107. : listing.stream()
  108. .filter(g -> StringUtils.containsIgnoreCase(g.groupId(), search))
  109. .toList()
  110. )
  111. .flatMapIterable(lst -> lst)
  112. .filterWhen(cg -> accessControlService.isConsumerGroupAccessible(cg.groupId(), cluster.getName()))
  113. .collectList()
  114. .flatMap(allGroups ->
  115. loadSortedDescriptions(ac, allGroups, pageNum, perPage, orderBy, sortOrderDto)
  116. .flatMap(descriptions -> getConsumerGroups(ac, descriptions)
  117. .map(page -> new ConsumerGroupsPage(
  118. page,
  119. (allGroups.size() / perPage) + (allGroups.size() % perPage == 0 ? 0 : 1))))));
  120. }
  121. private Mono<List<ConsumerGroupDescription>> loadSortedDescriptions(ReactiveAdminClient ac,
  122. List<ConsumerGroupListing> groups,
  123. int pageNum,
  124. int perPage,
  125. ConsumerGroupOrderingDTO orderBy,
  126. SortOrderDTO sortOrderDto) {
  127. return switch (orderBy) {
  128. case NAME -> {
  129. Comparator<ConsumerGroupListing> comparator = Comparator.comparing(ConsumerGroupListing::groupId);
  130. yield loadDescriptionsByListings(ac, groups, comparator, pageNum, perPage, sortOrderDto);
  131. }
  132. case STATE -> {
  133. ToIntFunction<ConsumerGroupListing> statesPriorities =
  134. cg -> switch (cg.state().orElse(ConsumerGroupState.UNKNOWN)) {
  135. case STABLE -> 0;
  136. case COMPLETING_REBALANCE -> 1;
  137. case PREPARING_REBALANCE -> 2;
  138. case EMPTY -> 3;
  139. case DEAD -> 4;
  140. case UNKNOWN -> 5;
  141. };
  142. var comparator = Comparator.comparingInt(statesPriorities);
  143. yield loadDescriptionsByListings(ac, groups, comparator, pageNum, perPage, sortOrderDto);
  144. }
  145. case MEMBERS -> {
  146. var comparator = Comparator.<ConsumerGroupDescription>comparingInt(cg -> cg.members().size());
  147. var groupNames = groups.stream().map(ConsumerGroupListing::groupId).toList();
  148. yield ac.describeConsumerGroups(groupNames)
  149. .map(descriptions ->
  150. sortAndPaginate(descriptions.values(), comparator, pageNum, perPage, sortOrderDto).toList());
  151. }
  152. case MESSAGES_BEHIND -> {
  153. record GroupWithDescr(InternalConsumerGroup icg, ConsumerGroupDescription cgd) { }
  154. Comparator<GroupWithDescr> comparator = Comparator.comparingLong(gwd ->
  155. gwd.icg.getMessagesBehind() == null ? 0L : gwd.icg.getMessagesBehind());
  156. var groupNames = groups.stream().map(ConsumerGroupListing::groupId).toList();
  157. yield ac.describeConsumerGroups(groupNames)
  158. .flatMap(descriptionsMap -> {
  159. List<ConsumerGroupDescription> descriptions = descriptionsMap.values().stream().toList();
  160. return getConsumerGroups(ac, descriptions)
  161. .map(icg -> Streams.zip(icg.stream(), descriptions.stream(), GroupWithDescr::new).toList())
  162. .map(gwd -> sortAndPaginate(gwd, comparator, pageNum, perPage, sortOrderDto)
  163. .map(GroupWithDescr::cgd).toList());
  164. }
  165. );
  166. }
  167. };
  168. }
  169. private Mono<List<ConsumerGroupDescription>> loadDescriptionsByListings(ReactiveAdminClient ac,
  170. List<ConsumerGroupListing> listings,
  171. Comparator<ConsumerGroupListing> comparator,
  172. int pageNum,
  173. int perPage,
  174. SortOrderDTO sortOrderDto) {
  175. List<String> sortedGroups = sortAndPaginate(listings, comparator, pageNum, perPage, sortOrderDto)
  176. .map(ConsumerGroupListing::groupId)
  177. .toList();
  178. return ac.describeConsumerGroups(sortedGroups)
  179. .map(descrMap -> sortedGroups.stream().map(descrMap::get).toList());
  180. }
  181. private <T> Stream<T> sortAndPaginate(Collection<T> collection,
  182. Comparator<T> comparator,
  183. int pageNum,
  184. int perPage,
  185. SortOrderDTO sortOrderDto) {
  186. return collection.stream()
  187. .sorted(sortOrderDto == SortOrderDTO.ASC ? comparator : comparator.reversed())
  188. .skip((long) (pageNum - 1) * perPage)
  189. .limit(perPage);
  190. }
  191. private Mono<List<ConsumerGroupDescription>> describeConsumerGroups(ReactiveAdminClient ac) {
  192. return ac.listConsumerGroupNames()
  193. .flatMap(ac::describeConsumerGroups)
  194. .map(cgs -> new ArrayList<>(cgs.values()));
  195. }
  196. public Mono<InternalConsumerGroup> getConsumerGroupDetail(KafkaCluster cluster,
  197. String consumerGroupId) {
  198. return adminClientService.get(cluster)
  199. .flatMap(ac -> ac.describeConsumerGroups(List.of(consumerGroupId))
  200. .filter(m -> m.containsKey(consumerGroupId))
  201. .map(r -> r.get(consumerGroupId))
  202. .flatMap(descr ->
  203. getConsumerGroups(ac, List.of(descr))
  204. .filter(groups -> !groups.isEmpty())
  205. .map(groups -> groups.get(0))));
  206. }
  207. public Mono<Void> deleteConsumerGroupById(KafkaCluster cluster,
  208. String groupId) {
  209. return adminClientService.get(cluster)
  210. .flatMap(adminClient -> adminClient.deleteConsumerGroups(List.of(groupId)));
  211. }
  212. public KafkaConsumer<Bytes, Bytes> createConsumer(KafkaCluster cluster) {
  213. return createConsumer(cluster, Map.of());
  214. }
  215. public KafkaConsumer<Bytes, Bytes> createConsumer(KafkaCluster cluster,
  216. Map<String, Object> properties) {
  217. Properties props = new Properties();
  218. SslPropertiesUtil.addKafkaSslProperties(cluster.getOriginalProperties().getSsl(), props);
  219. props.putAll(cluster.getProperties());
  220. props.put(ConsumerConfig.CLIENT_ID_CONFIG, "kafka-ui-consumer-" + System.currentTimeMillis());
  221. props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
  222. props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
  223. props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
  224. props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
  225. props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
  226. props.put(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG, "false");
  227. props.putAll(properties);
  228. return new KafkaConsumer<>(props);
  229. }
  230. }