Search in sources :

Example 6 with SignalHandler

use of sun.misc.SignalHandler in project orientdb by orientechnologies.

the class OConsoleDatabaseApp method main.

public static void main(final String[] args) {
    int result = 0;
    try {
        boolean tty = false;
        try {
            if (setTerminalToCBreak())
                tty = true;
            Runtime.getRuntime().addShutdownHook(new Thread() {

                @Override
                public void run() {
                    restoreTerminal();
                }
            });
        } catch (Exception ignored) {
        }
        new OSignalHandler().installDefaultSignals(new SignalHandler() {

            public void handle(Signal signal) {
                restoreTerminal();
            }
        });
        final OConsoleDatabaseApp console = new OConsoleDatabaseApp(args);
        if (tty)
            console.setReader(new TTYConsoleReader());
        result = console.run();
    } finally {
        restoreTerminal();
    }
    Orient.instance().shutdown();
    System.exit(result);
}
Also used : Signal(sun.misc.Signal) TTYConsoleReader(com.orientechnologies.common.console.TTYConsoleReader) OSignalHandler(com.orientechnologies.orient.core.OSignalHandler) SignalHandler(sun.misc.SignalHandler) OSystemException(com.orientechnologies.common.exception.OSystemException) OConfigurationException(com.orientechnologies.orient.core.exception.OConfigurationException) ORetryQueryException(com.orientechnologies.orient.core.exception.ORetryQueryException) OIOException(com.orientechnologies.common.io.OIOException) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) OSignalHandler(com.orientechnologies.orient.core.OSignalHandler)

Example 7 with SignalHandler

use of sun.misc.SignalHandler in project apex-core by apache.

the class ApexCli method preImpersonationInit.

public void preImpersonationInit(String[] args) throws IOException {
    Signal.handle(new Signal("INT"), new SignalHandler() {

        @Override
        public void handle(Signal sig) {
            System.out.println("^C");
            if (commandThread != null) {
                commandThread.interrupt();
                mainThread.interrupt();
            } else {
                System.out.print(prompt);
                System.out.flush();
            }
        }
    });
    consolePresent = (System.console() != null);
    Options options = new Options();
    options.addOption("e", true, "Commands are read from the argument");
    options.addOption("v", false, "Verbose mode level 1");
    options.addOption("vv", false, "Verbose mode level 2");
    options.addOption("vvv", false, "Verbose mode level 3");
    options.addOption("vvvv", false, "Verbose mode level 4");
    options.addOption("r", false, "JSON Raw mode");
    options.addOption("p", true, "JSONP padding function");
    options.addOption("h", false, "Print this help");
    options.addOption("f", true, "Use the specified prompt at all time");
    options.addOption("kp", true, "Use the specified kerberos principal");
    options.addOption("kt", true, "Use the specified kerberos keytab");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            verboseLevel = 1;
        }
        if (cmd.hasOption("vv")) {
            verboseLevel = 2;
        }
        if (cmd.hasOption("vvv")) {
            verboseLevel = 3;
        }
        if (cmd.hasOption("vvvv")) {
            verboseLevel = 4;
        }
        if (cmd.hasOption("r")) {
            raw = true;
        }
        if (cmd.hasOption("e")) {
            commandsToExecute = cmd.getOptionValues("e");
            consolePresent = false;
        }
        if (cmd.hasOption("p")) {
            jsonp = cmd.getOptionValue("p");
        }
        if (cmd.hasOption("f")) {
            forcePrompt = cmd.getOptionValue("f");
        }
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(ApexCli.class.getSimpleName(), options);
            System.exit(0);
        }
        if (cmd.hasOption("kp")) {
            kerberosPrincipal = cmd.getOptionValue("kp");
        }
        if (cmd.hasOption("kt")) {
            kerberosKeyTab = cmd.getOptionValue("kt");
        }
    } catch (ParseException ex) {
        System.err.println("Invalid argument: " + ex);
        System.exit(1);
    }
    if (kerberosPrincipal == null && kerberosKeyTab != null) {
        System.err.println("Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option.");
        System.exit(1);
    }
    if (kerberosPrincipal != null && kerberosKeyTab == null) {
        System.err.println("Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option.");
        System.exit(1);
    }
    Level logLevel;
    switch(verboseLevel) {
        case 0:
            logLevel = Level.OFF;
            break;
        case 1:
            logLevel = Level.ERROR;
            break;
        case 2:
            logLevel = Level.WARN;
            break;
        case 3:
            logLevel = Level.INFO;
            break;
        default:
            logLevel = Level.DEBUG;
            break;
    }
    for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[] { org.apache.log4j.Logger.getRootLogger(), org.apache.log4j.Logger.getLogger(ApexCli.class) }) {
        /*
      * Override logLevel specified by user, the same logLevel would be inherited by all
      * appenders related to logger.
      */
        logger.setLevel(logLevel);
        @SuppressWarnings("unchecked") Enumeration<Appender> allAppenders = logger.getAllAppenders();
        while (allAppenders.hasMoreElements()) {
            Appender appender = allAppenders.nextElement();
            if (appender instanceof ConsoleAppender) {
                ((ConsoleAppender) appender).setThreshold(logLevel);
            }
        }
    }
    if (commandsToExecute != null) {
        for (String command : commandsToExecute) {
            LOG.debug("Command to be executed: {}", command);
        }
    }
    if (kerberosPrincipal != null && kerberosKeyTab != null) {
        StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab);
    } else {
        Configuration config = new YarnConfiguration();
        StramClientUtils.addDTLocalResources(config);
        StramUserLogin.attemptAuthentication(config);
    }
}
Also used : ConsoleAppender(org.apache.log4j.ConsoleAppender) Appender(org.apache.log4j.Appender) ConsoleAppender(org.apache.log4j.ConsoleAppender) Options(org.apache.commons.cli.Options) Configuration(org.apache.hadoop.conf.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) DTConfiguration(com.datatorrent.stram.client.DTConfiguration) LogicalPlanConfiguration(com.datatorrent.stram.plan.logical.LogicalPlanConfiguration) Logger(org.slf4j.Logger) HelpFormatter(org.apache.commons.cli.HelpFormatter) BasicParser(org.apache.commons.cli.BasicParser) Signal(sun.misc.Signal) CommandLine(org.apache.commons.cli.CommandLine) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) SignalHandler(sun.misc.SignalHandler) Level(org.apache.log4j.Level) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException)

Example 8 with SignalHandler

use of sun.misc.SignalHandler 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)

Example 9 with SignalHandler

use of sun.misc.SignalHandler in project hive by apache.

the class CliDriver method processLine.

/**
 * Processes a line of semicolon separated commands
 *
 * @param line
 *          The commands to process
 * @param allowInterrupting
 *          When true the function will handle SIG_INT (Ctrl+C) by interrupting the processing and
 *          returning -1
 * @return 0 if ok
 */
public int processLine(String line, boolean allowInterrupting) {
    SignalHandler oldSignal = null;
    Signal interruptSignal = null;
    if (allowInterrupting) {
        // Remember all threads that were running at the time we started line processing.
        // Hook up the custom Ctrl+C handler while processing this line
        interruptSignal = new Signal("INT");
        oldSignal = Signal.handle(interruptSignal, new SignalHandler() {

            private boolean interruptRequested;

            @Override
            public void handle(Signal signal) {
                boolean initialRequest = !interruptRequested;
                interruptRequested = true;
                // Kill the VM on second ctrl+c
                if (!initialRequest) {
                    console.printInfo("Exiting the JVM");
                    System.exit(127);
                }
                // Interrupt the CLI thread to stop the current statement and return
                // to prompt
                console.printInfo("Interrupting... Be patient, this might take some time.");
                console.printInfo("Press Ctrl+C again to kill JVM");
                // First, kill any running MR jobs
                HadoopJobExecHelper.killRunningJobs();
                TezJobExecHelper.killRunningJobs();
                HiveInterruptUtils.interrupt();
            }
        });
    }
    try {
        int lastRet = 0, ret = 0;
        // we can not use "split" function directly as ";" may be quoted
        List<String> commands = splitSemiColon(line);
        String command = "";
        for (String oneCmd : commands) {
            if (StringUtils.endsWith(oneCmd, "\\")) {
                command += StringUtils.chop(oneCmd) + ";";
                continue;
            } else {
                command += oneCmd;
            }
            if (StringUtils.isBlank(command)) {
                continue;
            }
            ret = processCmd(command);
            command = "";
            lastRet = ret;
            boolean ignoreErrors = HiveConf.getBoolVar(conf, HiveConf.ConfVars.CLIIGNOREERRORS);
            if (ret != 0 && !ignoreErrors) {
                return ret;
            }
        }
        return lastRet;
    } finally {
        // Once we are done processing the line, restore the old handler
        if (oldSignal != null && interruptSignal != null) {
            Signal.handle(interruptSignal, oldSignal);
        }
    }
}
Also used : Signal(sun.misc.Signal) SignalHandler(sun.misc.SignalHandler)

Example 10 with SignalHandler

use of sun.misc.SignalHandler in project bazel by bazelbuild.

the class SignalHandlersTest method testOneHandlerCanHandleSignal.

@Test
public void testOneHandlerCanHandleSignal() {
    SignalHandler handler = Mockito.mock(SignalHandler.class);
    signalHandlers.installHandler(TERM_SIGNAL, handler);
    fakeSignalInstaller.sendSignal();
    Mockito.verify(handler).handle(Mockito.eq(TERM_SIGNAL));
}
Also used : SignalHandler(sun.misc.SignalHandler) Test(org.junit.Test)

Aggregations

SignalHandler (sun.misc.SignalHandler)13 Signal (sun.misc.Signal)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Test (org.junit.Test)2 DTConfiguration (com.datatorrent.stram.client.DTConfiguration)1 LogicalPlanConfiguration (com.datatorrent.stram.plan.logical.LogicalPlanConfiguration)1 TTYConsoleReader (com.orientechnologies.common.console.TTYConsoleReader)1 OSystemException (com.orientechnologies.common.exception.OSystemException)1 OIOException (com.orientechnologies.common.io.OIOException)1 OSignalHandler (com.orientechnologies.orient.core.OSignalHandler)1 OConfigurationException (com.orientechnologies.orient.core.exception.OConfigurationException)1 ODatabaseException (com.orientechnologies.orient.core.exception.ODatabaseException)1 ORetryQueryException (com.orientechnologies.orient.core.exception.ORetryQueryException)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 ArgumentParserException (net.sourceforge.argparse4j.inf.ArgumentParserException)1 BasicParser (org.apache.commons.cli.BasicParser)1 CommandLine (org.apache.commons.cli.CommandLine)1 CommandLineParser (org.apache.commons.cli.CommandLineParser)1 HelpFormatter (org.apache.commons.cli.HelpFormatter)1 Options (org.apache.commons.cli.Options)1