OmniaGM commented on code in PR #13204:
URL: https://github.com/apache/kafka/pull/13204#discussion_r1288887595


##########
tools/src/main/java/org/apache/kafka/tools/LeaderElectionCommand.java:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 com.fasterxml.jackson.databind.JsonMappingException;
+import joptsimple.AbstractOptionSpec;
+import joptsimple.ArgumentAcceptingOptionSpec;
+import joptsimple.OptionSpecBuilder;
+import joptsimple.util.EnumConverter;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.common.ElectionType;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.ClusterAuthorizationException;
+import org.apache.kafka.common.errors.ElectionNotNeededException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.server.common.AdminCommandFailedException;
+import org.apache.kafka.server.common.AdminOperationException;
+import org.apache.kafka.server.util.CommandDefaultOptions;
+import org.apache.kafka.server.util.CommandLineUtils;
+import org.apache.kafka.server.util.Json;
+import org.apache.kafka.server.util.json.DecodeJson;
+import org.apache.kafka.server.util.json.JsonObject;
+import org.apache.kafka.server.util.json.JsonValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+
+public class LeaderElectionCommand {
+    private static final Logger LOG = 
LoggerFactory.getLogger(LeaderElectionCommand.class);
+    private static final DecodeJson.DecodeString STRING = new 
DecodeJson.DecodeString();
+    private static final DecodeJson.DecodeInteger INT = new 
DecodeJson.DecodeInteger();
+
+    public static void main(String... args) {
+        try {
+            run(Duration.ofMillis(30000), args);
+        } catch (TerseException e) {
+            System.err.println(e.getMessage());
+        } catch (Exception e) {
+            System.err.println(e.getMessage());
+            System.err.println(Utils.stackTrace(e));
+        }
+    }
+
+    static void run(Duration timeoutMs, String... args) throws Exception {
+        LeaderElectionCommandOptions commandOptions = new 
LeaderElectionCommandOptions(args);
+
+        commandOptions.maybePrintHelpOrVersion();
+
+        commandOptions.validate();
+        ElectionType electionType = commandOptions.getElectionType();
+        Optional<Set<TopicPartition>> jsonFileTopicPartitions =
+            Optional.ofNullable(commandOptions.getPathToJsonFile())
+                .map(path -> parseReplicaElectionData(path));
+
+        Optional<String> topicOption = 
Optional.ofNullable(commandOptions.getTopic());
+        Optional<Integer> partitionOption = 
Optional.ofNullable(commandOptions.getPartition());
+        final Optional<Set<TopicPartition>> singleTopicPartition =
+            (topicOption.isPresent() && partitionOption.isPresent()) ?
+                Optional.of(Collections.singleton(new 
TopicPartition(topicOption.get(), partitionOption.get()))) :
+                Optional.empty();
+
+        /* Note: No need to look at --all-topic-partitions as we want this to 
be null if it is use.
+         * The validate function should be checking that this option is 
required if the --topic and --path-to-json-file
+         * are not specified.
+         */
+        Optional<Set<TopicPartition>> topicPartitions = 
jsonFileTopicPartitions.map(Optional::of).orElse(singleTopicPartition);
+
+        Properties props = new Properties();
+        if (commandOptions.hasAdminClientConfig()) {
+            
props.putAll(Utils.loadProps(commandOptions.getAdminClientConfig()));
+        }
+        props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, 
commandOptions.getBootstrapServer());
+        props.setProperty(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, 
Long.toString(timeoutMs.toMillis()));
+        props.setProperty(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, 
Long.toString(timeoutMs.toMillis() / 2));
+
+        try (Admin adminClient = Admin.create(props)) {
+            electLeaders(adminClient, electionType, topicPartitions);
+        }
+    }
+
+    private static void electLeaders(Admin client, ElectionType electionType, 
Optional<Set<TopicPartition>> partitions) {
+        LOG.debug(String.format("Calling AdminClient.electLeaders(%s, %s)", 
electionType, partitions.orElse(null)));
+        Map<TopicPartition, Optional<Throwable>> electionResults;
+        try {
+            electionResults = client.electLeaders(electionType, 
partitions.orElse(null)).partitions().get();
+        } catch (ExecutionException e) {
+            if (e.getCause() instanceof TimeoutException) {
+                String message = "Timeout waiting for election results";
+                System.err.println(message);

Review Comment:
   Switched to standard out. I think it is still wrong to print it as standard 
out



##########
tools/src/main/java/org/apache/kafka/tools/LeaderElectionCommand.java:
##########
@@ -0,0 +1,378 @@
+/*
+ * 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 com.fasterxml.jackson.databind.JsonMappingException;
+import joptsimple.AbstractOptionSpec;
+import joptsimple.ArgumentAcceptingOptionSpec;
+import joptsimple.OptionSpecBuilder;
+import joptsimple.util.EnumConverter;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.common.ElectionType;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.ClusterAuthorizationException;
+import org.apache.kafka.common.errors.ElectionNotNeededException;
+import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.server.common.AdminCommandFailedException;
+import org.apache.kafka.server.common.AdminOperationException;
+import org.apache.kafka.server.util.CommandDefaultOptions;
+import org.apache.kafka.server.util.CommandLineUtils;
+import org.apache.kafka.server.util.Json;
+import org.apache.kafka.server.util.json.DecodeJson;
+import org.apache.kafka.server.util.json.JsonObject;
+import org.apache.kafka.server.util.json.JsonValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+
+public class LeaderElectionCommand {
+    private static final Logger LOG = 
LoggerFactory.getLogger(LeaderElectionCommand.class);
+    private static final DecodeJson.DecodeString STRING = new 
DecodeJson.DecodeString();
+    private static final DecodeJson.DecodeInteger INT = new 
DecodeJson.DecodeInteger();
+
+    public static void main(String... args) {
+        try {
+            run(Duration.ofMillis(30000), args);
+        } catch (TerseException e) {
+            System.err.println(e.getMessage());
+        } catch (Exception e) {
+            System.err.println(e.getMessage());
+            System.err.println(Utils.stackTrace(e));
+        }
+    }
+
+    static void run(Duration timeoutMs, String... args) throws Exception {
+        LeaderElectionCommandOptions commandOptions = new 
LeaderElectionCommandOptions(args);
+
+        commandOptions.maybePrintHelpOrVersion();
+
+        commandOptions.validate();
+        ElectionType electionType = commandOptions.getElectionType();
+        Optional<Set<TopicPartition>> jsonFileTopicPartitions =
+            Optional.ofNullable(commandOptions.getPathToJsonFile())
+                .map(path -> parseReplicaElectionData(path));
+
+        Optional<String> topicOption = 
Optional.ofNullable(commandOptions.getTopic());
+        Optional<Integer> partitionOption = 
Optional.ofNullable(commandOptions.getPartition());
+        final Optional<Set<TopicPartition>> singleTopicPartition =
+            (topicOption.isPresent() && partitionOption.isPresent()) ?
+                Optional.of(Collections.singleton(new 
TopicPartition(topicOption.get(), partitionOption.get()))) :
+                Optional.empty();
+
+        /* Note: No need to look at --all-topic-partitions as we want this to 
be null if it is use.
+         * The validate function should be checking that this option is 
required if the --topic and --path-to-json-file
+         * are not specified.
+         */
+        Optional<Set<TopicPartition>> topicPartitions = 
jsonFileTopicPartitions.map(Optional::of).orElse(singleTopicPartition);
+
+        Properties props = new Properties();
+        if (commandOptions.hasAdminClientConfig()) {
+            
props.putAll(Utils.loadProps(commandOptions.getAdminClientConfig()));
+        }
+        props.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, 
commandOptions.getBootstrapServer());
+        props.setProperty(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, 
Long.toString(timeoutMs.toMillis()));
+        props.setProperty(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, 
Long.toString(timeoutMs.toMillis() / 2));
+
+        try (Admin adminClient = Admin.create(props)) {
+            electLeaders(adminClient, electionType, topicPartitions);
+        }
+    }
+
+    private static void electLeaders(Admin client, ElectionType electionType, 
Optional<Set<TopicPartition>> partitions) {
+        LOG.debug(String.format("Calling AdminClient.electLeaders(%s, %s)", 
electionType, partitions.orElse(null)));
+        Map<TopicPartition, Optional<Throwable>> electionResults;
+        try {
+            electionResults = client.electLeaders(electionType, 
partitions.orElse(null)).partitions().get();
+        } catch (ExecutionException e) {
+            if (e.getCause() instanceof TimeoutException) {
+                String message = "Timeout waiting for election results";
+                System.err.println(message);
+                throw new AdminCommandFailedException(message, e.getCause());
+            } else if (e.getCause() instanceof ClusterAuthorizationException) {
+                String message = "Not authorized to perform leader election";
+                System.err.println(message);
+                throw new AdminCommandFailedException(message, 
e.getCause().getCause());
+            } else {
+                throw new RuntimeException(e);
+            }
+        } catch (InterruptedException e) {
+            System.err.println("Error while making request");

Review Comment:
   Switched to standard out. I think it is still wrong to print it as standard 
out



-- 
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