Search in sources :

Example 16 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project kafka by apache.

the class TransactionsCommand method execute.

static void execute(String[] args, Function<Namespace, Admin> adminSupplier, PrintStream out, Time time) throws Exception {
    List<TransactionsCommand> commands = Arrays.asList(new ListTransactionsCommand(time), new DescribeTransactionsCommand(time), new DescribeProducersCommand(time), new AbortTransactionCommand(time), new FindHangingTransactionsCommand(time));
    ArgumentParser parser = buildBaseParser();
    Subparsers subparsers = parser.addSubparsers().dest("command").title("commands").metavar("COMMAND");
    commands.forEach(command -> command.addSubparser(subparsers));
    final Namespace ns;
    try {
        ns = parser.parseArgs(args);
    } catch (ArgumentParserException e) {
        parser.handleError(e);
        Exit.exit(1);
        return;
    }
    Admin admin = adminSupplier.apply(ns);
    String commandName = ns.getString("command");
    Optional<TransactionsCommand> commandOpt = commands.stream().filter(cmd -> cmd.name().equals(commandName)).findFirst();
    if (!commandOpt.isPresent()) {
        printErrorAndExit("Unexpected command " + commandName);
    }
    TransactionsCommand command = commandOpt.get();
    command.execute(admin, ns, out);
    Exit.exit(0);
}
Also used : DescribeProducersOptions(org.apache.kafka.clients.admin.DescribeProducersOptions) Arrays(java.util.Arrays) ProducerState(org.apache.kafka.clients.admin.ProducerState) Exit(org.apache.kafka.common.utils.Exit) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Function(java.util.function.Function) Arguments.store(net.sourceforge.argparse4j.impl.Arguments.store) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) HashSet(java.util.HashSet) OptionalLong(java.util.OptionalLong) Collections.singleton(java.util.Collections.singleton) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) Namespace(net.sourceforge.argparse4j.inf.Namespace) Map(java.util.Map) ListTopicsOptions(org.apache.kafka.clients.admin.ListTopicsOptions) Admin(org.apache.kafka.clients.admin.Admin) TransactionListing(org.apache.kafka.clients.admin.TransactionListing) TopicDescription(org.apache.kafka.clients.admin.TopicDescription) AbortTransactionSpec(org.apache.kafka.clients.admin.AbortTransactionSpec) TransactionDescription(org.apache.kafka.clients.admin.TransactionDescription) DescribeProducersResult(org.apache.kafka.clients.admin.DescribeProducersResult) Utils(org.apache.kafka.common.utils.Utils) PrintStream(java.io.PrintStream) TopicPartition(org.apache.kafka.common.TopicPartition) TopicPartitionInfo(org.apache.kafka.common.TopicPartitionInfo) Subparsers(net.sourceforge.argparse4j.inf.Subparsers) Logger(org.slf4j.Logger) Properties(java.util.Properties) DescribeTransactionsResult(org.apache.kafka.clients.admin.DescribeTransactionsResult) Time(org.apache.kafka.common.utils.Time) ArgumentParsers(net.sourceforge.argparse4j.ArgumentParsers) AdminClientConfig(org.apache.kafka.clients.admin.AdminClientConfig) Collection(java.util.Collection) Subparser(net.sourceforge.argparse4j.inf.Subparser) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ListTransactionsOptions(org.apache.kafka.clients.admin.ListTransactionsOptions) TransactionalIdNotFoundException(org.apache.kafka.common.errors.TransactionalIdNotFoundException) Optional(java.util.Optional) ArgumentGroup(net.sourceforge.argparse4j.inf.ArgumentGroup) Collections(java.util.Collections) Admin(org.apache.kafka.clients.admin.Admin) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace) Subparsers(net.sourceforge.argparse4j.inf.Subparsers) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException)

Example 17 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project kafka by apache.

the class VerifiableLog4jAppender method createFromArgs.

/**
 * Construct a VerifiableLog4jAppender object from command-line arguments.
 */
public static VerifiableLog4jAppender createFromArgs(String[] args) {
    ArgumentParser parser = argParser();
    VerifiableLog4jAppender producer = null;
    try {
        Namespace res = parser.parseArgs(args);
        int maxMessages = res.getInt("maxMessages");
        String topic = res.getString("topic");
        String configFile = res.getString("appender.config");
        Properties props = new Properties();
        props.setProperty("log4j.rootLogger", "INFO, KAFKA");
        props.setProperty("log4j.appender.KAFKA", "org.apache.kafka.log4jappender.KafkaLog4jAppender");
        props.setProperty("log4j.appender.KAFKA.layout", "org.apache.log4j.PatternLayout");
        props.setProperty("log4j.appender.KAFKA.layout.ConversionPattern", "%-5p: %c - %m%n");
        props.setProperty("log4j.appender.KAFKA.BrokerList", res.getString("brokerList"));
        props.setProperty("log4j.appender.KAFKA.Topic", topic);
        props.setProperty("log4j.appender.KAFKA.RequiredNumAcks", res.getString("acks"));
        props.setProperty("log4j.appender.KAFKA.SyncSend", "true");
        final String securityProtocol = res.getString("securityProtocol");
        if (securityProtocol != null && !securityProtocol.equals(SecurityProtocol.PLAINTEXT.toString())) {
            props.setProperty("log4j.appender.KAFKA.SecurityProtocol", securityProtocol);
        }
        if (securityProtocol != null && securityProtocol.contains("SSL")) {
            props.setProperty("log4j.appender.KAFKA.SslTruststoreLocation", res.getString("sslTruststoreLocation"));
            props.setProperty("log4j.appender.KAFKA.SslTruststorePassword", res.getString("sslTruststorePassword"));
        }
        if (securityProtocol != null && securityProtocol.contains("SASL")) {
            props.setProperty("log4j.appender.KAFKA.SaslKerberosServiceName", res.getString("saslKerberosServiceName"));
            props.setProperty("log4j.appender.KAFKA.clientJaasConfPath", res.getString("clientJaasConfPath"));
            props.setProperty("log4j.appender.KAFKA.kerb5ConfPath", res.getString("kerb5ConfPath"));
        }
        props.setProperty("log4j.logger.kafka.log4j", "INFO, KAFKA");
        // Changing log level from INFO to WARN as a temporary workaround for KAFKA-6415. This is to
        // avoid deadlock in system tests when producer network thread appends to log while updating metadata.
        props.setProperty("log4j.logger.org.apache.kafka.clients.Metadata", "WARN, KAFKA");
        if (configFile != null) {
            try {
                props.putAll(loadProps(configFile));
            } catch (IOException e) {
                throw new ArgumentParserException(e.getMessage(), parser);
            }
        }
        producer = new VerifiableLog4jAppender(props, maxMessages);
    } catch (ArgumentParserException e) {
        if (args.length == 0) {
            parser.printHelp();
            Exit.exit(0);
        } else {
            parser.handleError(e);
            Exit.exit(1);
        }
    }
    return producer;
}
Also used : IOException(java.io.IOException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) Properties(java.util.Properties) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Namespace(net.sourceforge.argparse4j.inf.Namespace)

Example 18 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project kafka by apache.

the class ProducerPerformanceTest method testUnexpectedArg.

@Test
public void testUnexpectedArg() {
    String[] args = new String[] { "--test", "test", "--topic", "Hello-Kafka", "--num-records", "5", "--throughput", "100", "--record-size", "100", "--producer-props", "bootstrap.servers=localhost:9000" };
    ArgumentParser parser = ProducerPerformance.argParser();
    ArgumentParserException thrown = assertThrows(ArgumentParserException.class, () -> parser.parseArgs(args));
    assertEquals("unrecognized arguments: '--test'", thrown.getMessage());
}
Also used : ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) ArgumentParser(net.sourceforge.argparse4j.inf.ArgumentParser) Test(org.junit.jupiter.api.Test)

Example 19 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project kafka by apache.

the class OAuthCompatibilityTool method main.

public static void main(String[] args) {
    ArgsHandler argsHandler = new ArgsHandler();
    Namespace namespace;
    try {
        namespace = argsHandler.parseArgs(args);
    } catch (ArgumentParserException e) {
        Exit.exit(1);
        return;
    }
    ConfigHandler configHandler = new ConfigHandler(namespace);
    Map<String, ?> configs = configHandler.getConfigs();
    Map<String, Object> jaasConfigs = configHandler.getJaasOptions();
    try {
        String accessToken;
        {
            // Client side...
            try (AccessTokenRetriever atr = AccessTokenRetrieverFactory.create(configs, jaasConfigs)) {
                atr.init();
                AccessTokenValidator atv = AccessTokenValidatorFactory.create(configs);
                System.out.println("PASSED 1/5: client configuration");
                accessToken = atr.retrieve();
                System.out.println("PASSED 2/5: client JWT retrieval");
                atv.validate(accessToken);
                System.out.println("PASSED 3/5: client JWT validation");
            }
        }
        {
            // Broker side...
            try (CloseableVerificationKeyResolver vkr = VerificationKeyResolverFactory.create(configs, jaasConfigs)) {
                vkr.init();
                AccessTokenValidator atv = AccessTokenValidatorFactory.create(configs, vkr);
                System.out.println("PASSED 4/5: broker configuration");
                atv.validate(accessToken);
                System.out.println("PASSED 5/5: broker JWT validation");
            }
        }
        System.out.println("SUCCESS");
        Exit.exit(0);
    } catch (Throwable t) {
        System.out.println("FAILED:");
        t.printStackTrace();
        if (t instanceof ConfigException) {
            System.out.printf("%n");
            argsHandler.parser.printHelp();
        }
        Exit.exit(1);
    }
}
Also used : ConfigException(org.apache.kafka.common.config.ConfigException) Namespace(net.sourceforge.argparse4j.inf.Namespace) AccessTokenValidator(org.apache.kafka.common.security.oauthbearer.secured.AccessTokenValidator) AccessTokenRetriever(org.apache.kafka.common.security.oauthbearer.secured.AccessTokenRetriever) CloseableVerificationKeyResolver(org.apache.kafka.common.security.oauthbearer.secured.CloseableVerificationKeyResolver) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException)

Example 20 with ArgumentParserException

use of net.sourceforge.argparse4j.inf.ArgumentParserException in project helios by spotify.

the class AgentMain method main.

public static void main(final String... args) {
    final AgentMain main;
    final AtomicBoolean exitSignalTriggered = new AtomicBoolean(false);
    final AtomicReference<SignalHandler> existingExitHandler = new AtomicReference<SignalHandler>(null);
    final SignalHandler handler = new SignalHandler() {

        @Override
        public void handle(Signal signal) {
            if (exitSignalTriggered.get()) {
                System.err.println("Exiting with extreme prejudice due to " + signal);
                // Really exit
                Runtime.getRuntime().halt(0);
            } else {
                System.err.println("Attempting gentle exit on " + signal);
                exitSignalTriggered.set(true);
                existingExitHandler.get().handle(signal);
            }
        }
    };
    existingExitHandler.set(Signal.handle(new Signal("INT"), handler));
    Signal.handle(new Signal("TERM"), handler);
    try {
        main = new AgentMain(args);
    } catch (ArgumentParserException e) {
        e.printStackTrace();
        System.exit(1);
        // never get here, but this lets java know for sure we won't continue
        return;
    }
    try {
        main.startAsync().awaitRunning();
        main.awaitTerminated();
    } catch (Throwable e) {
        try {
            main.shutDown();
        } catch (Exception e1) {
            System.err.println("Error shutting down");
            e1.printStackTrace();
            System.err.println("Originating exception follows");
        }
        e.printStackTrace();
        System.exit(1);
    }
    // Ensure we exit even if there's lingering non-daemon threads
    System.exit(0);
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Signal(sun.misc.Signal) SignalHandler(sun.misc.SignalHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException)

Aggregations

ArgumentParserException (net.sourceforge.argparse4j.inf.ArgumentParserException)42 Namespace (net.sourceforge.argparse4j.inf.Namespace)34 ArgumentParser (net.sourceforge.argparse4j.inf.ArgumentParser)30 Properties (java.util.Properties)13 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)6 MutuallyExclusiveGroup (net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup)6 ArgumentGroup (net.sourceforge.argparse4j.inf.ArgumentGroup)4 Platform (org.apache.kafka.trogdor.common.Platform)4 JsonRestServer (org.apache.kafka.trogdor.rest.JsonRestServer)4 AnnotatorService (edu.illinois.cs.cogcomp.annotation.AnnotatorService)3 File (java.io.File)3 Path (java.nio.file.Path)3 List (java.util.List)3 Random (java.util.Random)3 HelpScreenException (net.sourceforge.argparse4j.internal.HelpScreenException)3 KafkaProducer (org.apache.kafka.clients.producer.KafkaProducer)3 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 HashSet (java.util.HashSet)2