chia7712 commented on code in PR #17626:
URL: https://github.com/apache/kafka/pull/17626#discussion_r1824571208


##########
tools/src/test/java/org/apache/kafka/tools/GroupsCommandTest.java:
##########
@@ -0,0 +1,381 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.tools;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.AdminClientTestUtils;
+import org.apache.kafka.clients.admin.GroupListing;
+import org.apache.kafka.clients.admin.ListGroupsResult;
+import org.apache.kafka.common.GroupType;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Exit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class GroupsCommandTest {

Review Comment:
   Do you plan to add integration tests for this new tool? If not, I can file a 
JIRA to add more tests as a follow-up.



##########
tools/src/main/java/org/apache/kafka/tools/GroupsCommand.java:
##########
@@ -0,0 +1,295 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.tools;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.GroupListing;
+import org.apache.kafka.common.GroupType;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.server.util.CommandDefaultOptions;
+import org.apache.kafka.server.util.CommandLineUtils;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import joptsimple.ArgumentAcceptingOptionSpec;
+import joptsimple.OptionSpec;
+import joptsimple.OptionSpecBuilder;
+
+public class GroupsCommand {
+    private static final Logger LOG = 
LoggerFactory.getLogger(GroupsCommand.class);
+
+    public static void main(String... args) {
+        Exit.exit(mainNoExit(args));
+    }
+
+    static int mainNoExit(String... args) {
+        try {
+            execute(args);
+            return 0;
+        } catch (Throwable e) {
+            System.err.println(e.getMessage());
+            System.err.println(Utils.stackTrace(e));
+            return 1;
+        }
+    }
+
+    static void execute(String... args) throws Exception {
+        GroupsCommandOptions opts = new GroupsCommandOptions(args);
+
+        Properties config = opts.commandConfig();
+        config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, 
opts.bootstrapServer());
+
+        int exitCode = 0;
+        try (GroupsService service = new GroupsService(config)) {
+            if (opts.hasListOption()) {
+                service.listGroups(opts);
+            }
+        } catch (ExecutionException e) {
+            Throwable cause = e.getCause();
+            if (cause != null) {
+                printException(cause);
+            } else {
+                printException(e);
+            }
+            exitCode = 1;
+        } catch (Throwable t) {
+            printException(t);
+            exitCode = 1;
+        } finally {
+            Exit.exit(exitCode);
+        }
+    }
+
+    public static class GroupsService implements AutoCloseable {
+        private final Admin adminClient;
+
+        public GroupsService(Properties config) {
+            this.adminClient = Admin.create(config);
+        }
+
+        // Visible for testing
+        GroupsService(Admin adminClient) {
+            this.adminClient = adminClient;
+        }
+
+        public void listGroups(GroupsCommandOptions opts) throws Exception {
+            Collection<GroupListing> resources = adminClient.listGroups()
+                    .all().get(30, TimeUnit.SECONDS);
+            printGroupDetails(resources, opts.groupType(), opts.protocol(), 
opts.hasConsumerOption(), opts.hasShareOption());
+        }
+
+        private void printGroupDetails(Collection<GroupListing> groups,
+                                       Optional<GroupType> groupTypeFilter,
+                                       Optional<String> protocolFilter,
+                                       boolean consumerGroupFilter,
+                                       boolean shareGroupFilter) {
+            List<List<String>> lineItems = new ArrayList<>();
+            int maxLen = 20;
+            for (GroupListing group : groups) {
+                if (combinedFilter(group, groupTypeFilter, protocolFilter, 
consumerGroupFilter, shareGroupFilter)) {
+                    List<String> lineItem = new ArrayList<>();
+                    lineItem.add(group.groupId());
+                    
lineItem.add(group.type().map(GroupType::toString).orElse(""));
+                    lineItem.add(group.protocol());
+                    for (String item : lineItem) {
+                        if (item != null) {
+                            maxLen = Math.max(maxLen, item.length());
+                        }
+                    }
+                    lineItems.add(lineItem);
+                }
+            }
+
+            String fmt = "%" + (-maxLen) + "s";
+            String header = fmt + " " + fmt + " " + fmt;
+            System.out.printf(header, "GROUP", "TYPE", "PROTOCOL");
+            System.out.println();
+            for (List<String> item : lineItems) {
+                for (String atom : item) {
+                    System.out.printf(fmt + " ", atom);
+                }
+                System.out.println();
+            }
+        }
+
+        private boolean combinedFilter(GroupListing group,
+                                       Optional<GroupType> groupTypeFilter,
+                                       Optional<String> protocolFilter,
+                                       boolean consumerGroupFilter,
+                                       boolean shareGroupFilter) {
+            boolean pass = true;
+            Optional<GroupType> groupType = group.type();
+            String protocol = group.protocol();
+
+            if (groupTypeFilter.isPresent()) {
+                pass = protocolFilter.map(s -> protocol.equals(s) && 
groupType.filter(gt -> gt == groupTypeFilter.get()).isPresent())
+                        .orElseGet(() -> groupType.filter(gt -> gt == 
groupTypeFilter.get()).isPresent());
+            } else if (protocolFilter.isPresent()) {
+                pass = protocol.equals(protocolFilter.get());
+            } else if (consumerGroupFilter) {
+                pass = protocol.equals("consumer") || protocol.isEmpty() || 
groupType.filter(gt -> gt == GroupType.CONSUMER).isPresent();
+            } else if (shareGroupFilter) {
+                pass = groupType.filter(gt -> gt == 
GroupType.SHARE).isPresent();
+            }
+            return pass;
+        }
+
+        @Override
+        public void close() throws Exception {
+            adminClient.close();
+        }
+    }
+
+    private static void printException(Throwable e) {
+        System.out.println("Error while executing groups command : " + 
e.getMessage());
+        LOG.error(Utils.stackTrace(e));
+    }
+
+    public static final class GroupsCommandOptions extends 
CommandDefaultOptions {
+        private final ArgumentAcceptingOptionSpec<String> bootstrapServerOpt;
+
+        private final ArgumentAcceptingOptionSpec<String> commandConfigOpt;
+
+        private final OptionSpecBuilder listOpt;
+
+        private final ArgumentAcceptingOptionSpec<String> groupTypeOpt;
+
+        private final ArgumentAcceptingOptionSpec<String> protocolOpt;
+
+        private final OptionSpecBuilder consumerOpt;
+
+        private final OptionSpecBuilder shareOpt;
+
+        public GroupsCommandOptions(String[] args) {
+            super(args);
+            bootstrapServerOpt = parser.accepts("bootstrap-server", "REQUIRED: 
The Kafka server to connect to.")
+                    .withRequiredArg()
+                    .describedAs("server to connect to")
+                    .required()
+                    .ofType(String.class);
+            commandConfigOpt = parser.accepts("command-config", "Property file 
containing configs to be passed to Admin Client.")
+                    .withRequiredArg()
+                    .describedAs("command config property file")
+                    .ofType(String.class);
+
+            listOpt = parser.accepts("list", "List the groups.");
+
+            groupTypeOpt = parser.accepts("group-type", "Filter the groups 
based on group type. "
+                            + "Valid types are: 'classic', 'consumer' and 
'share'.")
+                    .withRequiredArg()
+                    .describedAs("type")
+                    .ofType(String.class);
+
+            protocolOpt = parser.accepts("protocol", "Filter the groups based 
on protocol type.")
+                    .withRequiredArg()
+                    .describedAs("protocol")
+                    .ofType(String.class);
+
+            consumerOpt = parser.accepts("consumer", "Filter the groups to 
show all kinds of consumer groups, including classic and simple consumer 
groups. "

Review Comment:
   Are the groups used by connectors intentionally excluded by this option?



##########
tools/src/main/java/org/apache/kafka/tools/GroupsCommand.java:
##########
@@ -0,0 +1,295 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.tools;
+
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.GroupListing;
+import org.apache.kafka.common.GroupType;
+import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.server.util.CommandDefaultOptions;
+import org.apache.kafka.server.util.CommandLineUtils;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import joptsimple.ArgumentAcceptingOptionSpec;
+import joptsimple.OptionSpec;
+import joptsimple.OptionSpecBuilder;
+
+public class GroupsCommand {
+    private static final Logger LOG = 
LoggerFactory.getLogger(GroupsCommand.class);
+
+    public static void main(String... args) {
+        Exit.exit(mainNoExit(args));
+    }
+
+    static int mainNoExit(String... args) {
+        try {
+            execute(args);
+            return 0;
+        } catch (Throwable e) {
+            System.err.println(e.getMessage());
+            System.err.println(Utils.stackTrace(e));
+            return 1;
+        }
+    }
+
+    static void execute(String... args) throws Exception {
+        GroupsCommandOptions opts = new GroupsCommandOptions(args);
+
+        Properties config = opts.commandConfig();
+        config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, 
opts.bootstrapServer());
+
+        int exitCode = 0;
+        try (GroupsService service = new GroupsService(config)) {
+            if (opts.hasListOption()) {
+                service.listGroups(opts);
+            }
+        } catch (ExecutionException e) {
+            Throwable cause = e.getCause();
+            if (cause != null) {
+                printException(cause);
+            } else {
+                printException(e);
+            }
+            exitCode = 1;
+        } catch (Throwable t) {
+            printException(t);
+            exitCode = 1;
+        } finally {
+            Exit.exit(exitCode);
+        }
+    }
+
+    public static class GroupsService implements AutoCloseable {
+        private final Admin adminClient;
+
+        public GroupsService(Properties config) {
+            this.adminClient = Admin.create(config);
+        }
+
+        // Visible for testing
+        GroupsService(Admin adminClient) {
+            this.adminClient = adminClient;
+        }
+
+        public void listGroups(GroupsCommandOptions opts) throws Exception {
+            Collection<GroupListing> resources = adminClient.listGroups()
+                    .all().get(30, TimeUnit.SECONDS);
+            printGroupDetails(resources, opts.groupType(), opts.protocol(), 
opts.hasConsumerOption(), opts.hasShareOption());
+        }
+
+        private void printGroupDetails(Collection<GroupListing> groups,
+                                       Optional<GroupType> groupTypeFilter,
+                                       Optional<String> protocolFilter,
+                                       boolean consumerGroupFilter,
+                                       boolean shareGroupFilter) {
+            List<List<String>> lineItems = new ArrayList<>();
+            int maxLen = 20;
+            for (GroupListing group : groups) {
+                if (combinedFilter(group, groupTypeFilter, protocolFilter, 
consumerGroupFilter, shareGroupFilter)) {
+                    List<String> lineItem = new ArrayList<>();
+                    lineItem.add(group.groupId());
+                    
lineItem.add(group.type().map(GroupType::toString).orElse(""));
+                    lineItem.add(group.protocol());
+                    for (String item : lineItem) {
+                        if (item != null) {
+                            maxLen = Math.max(maxLen, item.length());
+                        }
+                    }
+                    lineItems.add(lineItem);
+                }
+            }
+
+            String fmt = "%" + (-maxLen) + "s";
+            String header = fmt + " " + fmt + " " + fmt;
+            System.out.printf(header, "GROUP", "TYPE", "PROTOCOL");
+            System.out.println();
+            for (List<String> item : lineItems) {
+                for (String atom : item) {
+                    System.out.printf(fmt + " ", atom);
+                }
+                System.out.println();
+            }
+        }
+
+        private boolean combinedFilter(GroupListing group,
+                                       Optional<GroupType> groupTypeFilter,
+                                       Optional<String> protocolFilter,
+                                       boolean consumerGroupFilter,
+                                       boolean shareGroupFilter) {
+            boolean pass = true;
+            Optional<GroupType> groupType = group.type();
+            String protocol = group.protocol();
+
+            if (groupTypeFilter.isPresent()) {
+                pass = protocolFilter.map(s -> protocol.equals(s) && 
groupType.filter(gt -> gt == groupTypeFilter.get()).isPresent())

Review Comment:
   ```java
                   pass = groupType.filter(gt -> gt == 
groupTypeFilter.get()).isPresent()
                           && protocolFilter.map(protocol::equals).orElse(true);
   ```
   this style can eliminate the duplicate code 



##########
clients/src/main/java/org/apache/kafka/clients/admin/GroupListing.java:
##########
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.clients.admin;
+
+import org.apache.kafka.common.GroupType;
+
+import java.util.Objects;
+import java.util.Optional;
+
+/**
+ * A listing of a group in the cluster.
+ */
+public class GroupListing {
+    private final String groupId;
+    private final Optional<GroupType> type;
+    private final String protocol;
+
+    /**
+     * Create an instance with the specified parameters.
+     *
+     * @param groupId Group Id
+     * @param type Group type
+     * @param protocol Protocol
+     */
+    public GroupListing(String groupId, Optional<GroupType> type, String 
protocol) {
+        this.groupId = groupId;
+        this.type = Objects.requireNonNull(type);
+        this.protocol = protocol;
+    }
+
+    /**
+     * The group Id.
+     *
+     * @return Group Id
+     */
+    public String groupId() {
+        return groupId;
+    }
+
+    /**
+     * The type of the group.
+     *
+     * @return An Optional containing the type, if available
+     */
+    public Optional<GroupType> type() {
+        return type;
+    }
+
+    /**
+     * The protocol of the group.
+     *
+     * @return The protocol
+     */
+    public String protocol() {
+        return protocol;
+    }
+
+    /**
+     * If the group is a simple consumer group or not.
+     */
+    public boolean isSimpleConsumerGroup() {
+        return type.filter(gt -> gt == GroupType.CLASSIC).isPresent() && 
protocol.isEmpty();
+    }
+
+    @Override
+    public String toString() {
+        return "(" +
+            "groupId='" + groupId + '\'' +
+            ", type=" + type +

Review Comment:
   `", type=" + type.map(GroupType::toString).orElse("none")`  WDYT?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscr...@kafka.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to