ConsumerGroupService.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. private record GroupWithDescr(InternalConsumerGroup icg, ConsumerGroupDescription cgd) {
  97. }
  98. public Mono<ConsumerGroupsPage> getConsumerGroupsPage(
  99. KafkaCluster cluster,
  100. int pageNum,
  101. int perPage,
  102. @Nullable String search,
  103. ConsumerGroupOrderingDTO orderBy,
  104. SortOrderDTO sortOrderDto) {
  105. return adminClientService.get(cluster).flatMap(ac ->
  106. ac.listConsumerGroups()
  107. .map(listing -> search == null
  108. ? listing
  109. : listing.stream()
  110. .filter(g -> StringUtils.containsIgnoreCase(g.groupId(), search))
  111. .toList()
  112. )
  113. .flatMapIterable(lst -> lst)
  114. .filterWhen(cg -> accessControlService.isConsumerGroupAccessible(cg.groupId(), cluster.getName()))
  115. .collectList()
  116. .flatMap(allGroups ->
  117. loadSortedDescriptions(ac, allGroups, pageNum, perPage, orderBy, sortOrderDto)
  118. .flatMap(descriptions -> getConsumerGroups(ac, descriptions)
  119. .map(page -> new ConsumerGroupsPage(
  120. page,
  121. (allGroups.size() / perPage) + (allGroups.size() % perPage == 0 ? 0 : 1))))));
  122. }
  123. private Mono<List<ConsumerGroupDescription>> loadSortedDescriptions(ReactiveAdminClient ac,
  124. List<ConsumerGroupListing> groups,
  125. int pageNum,
  126. int perPage,
  127. ConsumerGroupOrderingDTO orderBy,
  128. SortOrderDTO sortOrderDto) {
  129. return switch (orderBy) {
  130. case NAME -> {
  131. Comparator<ConsumerGroupListing> comparator = Comparator.comparing(ConsumerGroupListing::groupId);
  132. yield loadDescriptionsByListings(ac, groups, comparator, pageNum, perPage, sortOrderDto);
  133. }
  134. case STATE -> {
  135. ToIntFunction<ConsumerGroupListing> statesPriorities =
  136. cg -> switch (cg.state().orElse(ConsumerGroupState.UNKNOWN)) {
  137. case STABLE -> 0;
  138. case COMPLETING_REBALANCE -> 1;
  139. case PREPARING_REBALANCE -> 2;
  140. case EMPTY -> 3;
  141. case DEAD -> 4;
  142. case UNKNOWN -> 5;
  143. };
  144. var comparator = Comparator.comparingInt(statesPriorities);
  145. yield loadDescriptionsByListings(ac, groups, comparator, pageNum, perPage, sortOrderDto);
  146. }
  147. case MEMBERS -> {
  148. var comparator = Comparator.<ConsumerGroupDescription>comparingInt(cg -> cg.members().size());
  149. var groupNames = groups.stream().map(ConsumerGroupListing::groupId).toList();
  150. yield ac.describeConsumerGroups(groupNames)
  151. .map(descriptions ->
  152. sortAndPaginate(descriptions.values(), comparator, pageNum, perPage, sortOrderDto).toList());
  153. }
  154. case MESSAGES_BEHIND -> {
  155. Comparator<GroupWithDescr> comparator = Comparator.comparingLong(gwd ->
  156. gwd.icg.getConsumerLag() == null ? 0L : gwd.icg.getConsumerLag());
  157. yield loadDescriptionsByInternalConsumerGroups(ac, groups, comparator, pageNum, perPage, sortOrderDto);
  158. }
  159. case TOPIC_NUM -> {
  160. Comparator<GroupWithDescr> comparator = Comparator.comparingInt(gwd -> gwd.icg.getTopicNum());
  161. yield loadDescriptionsByInternalConsumerGroups(ac, groups, comparator, pageNum, perPage, sortOrderDto);
  162. }
  163. };
  164. }
  165. private Mono<List<ConsumerGroupDescription>> loadDescriptionsByListings(ReactiveAdminClient ac,
  166. List<ConsumerGroupListing> listings,
  167. Comparator<ConsumerGroupListing> comparator,
  168. int pageNum,
  169. int perPage,
  170. SortOrderDTO sortOrderDto) {
  171. List<String> sortedGroups = sortAndPaginate(listings, comparator, pageNum, perPage, sortOrderDto)
  172. .map(ConsumerGroupListing::groupId)
  173. .toList();
  174. return ac.describeConsumerGroups(sortedGroups)
  175. .map(descrMap -> sortedGroups.stream().map(descrMap::get).toList());
  176. }
  177. private <T> Stream<T> sortAndPaginate(Collection<T> collection,
  178. Comparator<T> comparator,
  179. int pageNum,
  180. int perPage,
  181. SortOrderDTO sortOrderDto) {
  182. return collection.stream()
  183. .sorted(sortOrderDto == SortOrderDTO.ASC ? comparator : comparator.reversed())
  184. .skip((long) (pageNum - 1) * perPage)
  185. .limit(perPage);
  186. }
  187. private Mono<List<ConsumerGroupDescription>> describeConsumerGroups(ReactiveAdminClient ac) {
  188. return ac.listConsumerGroupNames()
  189. .flatMap(ac::describeConsumerGroups)
  190. .map(cgs -> new ArrayList<>(cgs.values()));
  191. }
  192. private Mono<List<ConsumerGroupDescription>> loadDescriptionsByInternalConsumerGroups(ReactiveAdminClient ac,
  193. List<ConsumerGroupListing> groups,
  194. Comparator<GroupWithDescr> comparator,
  195. int pageNum,
  196. int perPage,
  197. SortOrderDTO sortOrderDto) {
  198. var groupNames = groups.stream().map(ConsumerGroupListing::groupId).toList();
  199. return ac.describeConsumerGroups(groupNames)
  200. .flatMap(descriptionsMap -> {
  201. List<ConsumerGroupDescription> descriptions = descriptionsMap.values().stream().toList();
  202. return getConsumerGroups(ac, descriptions)
  203. .map(icg -> Streams.zip(icg.stream(), descriptions.stream(), GroupWithDescr::new).toList())
  204. .map(gwd -> sortAndPaginate(gwd, comparator, pageNum, perPage, sortOrderDto)
  205. .map(GroupWithDescr::cgd).toList());
  206. }
  207. );
  208. }
  209. public Mono<InternalConsumerGroup> getConsumerGroupDetail(KafkaCluster cluster,
  210. String consumerGroupId) {
  211. return adminClientService.get(cluster)
  212. .flatMap(ac -> ac.describeConsumerGroups(List.of(consumerGroupId))
  213. .filter(m -> m.containsKey(consumerGroupId))
  214. .map(r -> r.get(consumerGroupId))
  215. .flatMap(descr ->
  216. getConsumerGroups(ac, List.of(descr))
  217. .filter(groups -> !groups.isEmpty())
  218. .map(groups -> groups.get(0))));
  219. }
  220. public Mono<Void> deleteConsumerGroupById(KafkaCluster cluster,
  221. String groupId) {
  222. return adminClientService.get(cluster)
  223. .flatMap(adminClient -> adminClient.deleteConsumerGroups(List.of(groupId)));
  224. }
  225. public KafkaConsumer<Bytes, Bytes> createConsumer(KafkaCluster cluster) {
  226. return createConsumer(cluster, Map.of());
  227. }
  228. public KafkaConsumer<Bytes, Bytes> createConsumer(KafkaCluster cluster,
  229. Map<String, Object> properties) {
  230. Properties props = new Properties();
  231. SslPropertiesUtil.addKafkaSslProperties(cluster.getOriginalProperties().getSsl(), props);
  232. props.putAll(cluster.getProperties());
  233. props.put(ConsumerConfig.CLIENT_ID_CONFIG, "kafka-ui-consumer-" + System.currentTimeMillis());
  234. props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers());
  235. props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
  236. props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
  237. props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
  238. props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
  239. props.put(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG, "false");
  240. props.putAll(properties);
  241. return new KafkaConsumer<>(props);
  242. }
  243. }