sun.misc.SignalHandler Scala Examples
The following examples show how to use sun.misc.SignalHandler.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: SignalLogger.scala From iolap with Apache License 2.0 | 5 votes |
package org.apache.spark.util import org.apache.commons.lang3.SystemUtils import org.slf4j.Logger import sun.misc.{Signal, SignalHandler} def register(log: Logger): Unit = synchronized { if (SystemUtils.IS_OS_UNIX) { require(!registered, "Can't re-install the signal handlers") registered = true val signals = Seq("TERM", "HUP", "INT") for (signal <- signals) { try { new SignalLoggerHandler(signal, log) } catch { case e: Exception => log.warn("Failed to register signal handler " + signal, e) } } log.info("Registered signal handlers for [" + signals.mkString(", ") + "]") } } } private sealed class SignalLoggerHandler(name: String, log: Logger) extends SignalHandler { val prevHandler = Signal.handle(new Signal(name), this) override def handle(signal: Signal): Unit = { log.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName()) prevHandler.handle(signal) } }
Example 2
Source File: posix_interrupt.scala From libisabelle with Apache License 2.0 | 5 votes |
package isabelle import sun.misc.{Signal, SignalHandler} object POSIX_Interrupt { def handler[A](h: => Unit)(e: => A): A = { val SIGINT = new Signal("INT") val new_handler = new SignalHandler { def handle(s: Signal) { h } } val old_handler = Signal.handle(SIGINT, new_handler) try { e } finally { Signal.handle(SIGINT, old_handler) } } def exception[A](e: => A): A = { val thread = Thread.currentThread handler { thread.interrupt } { e } } }
Example 3
Source File: posix_interrupt.scala From libisabelle with Apache License 2.0 | 5 votes |
package isabelle import sun.misc.{Signal, SignalHandler} object POSIX_Interrupt { def handler[A](h: => Unit)(e: => A): A = { val SIGINT = new Signal("INT") val new_handler = new SignalHandler { def handle(s: Signal) { h } } val old_handler = Signal.handle(SIGINT, new_handler) try { e } finally { Signal.handle(SIGINT, old_handler) } } def exception[A](e: => A): A = { val thread = Thread.currentThread handler { thread.interrupt } { e } } }
Example 4
Source File: posix_interrupt.scala From libisabelle with Apache License 2.0 | 5 votes |
package isabelle import sun.misc.{Signal, SignalHandler} object POSIX_Interrupt { def handler[A](h: => Unit)(e: => A): A = { val SIGINT = new Signal("INT") val new_handler = new SignalHandler { def handle(s: Signal) { h } } val old_handler = Signal.handle(SIGINT, new_handler) try { e } finally { Signal.handle(SIGINT, old_handler) } } def exception[A](e: => A): A = { val thread = Thread.currentThread handler { thread.interrupt } { e } } }
Example 5
Source File: CommandInterruptSignalHandler.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.exec.shell import com.flaminem.flamy.exec.utils.ThreadPrintStream import sun.misc.{Signal, SignalHandler} var continue = true while (continue) { Thread.sleep(1) this.synchronized { if (command.isDefined) { command.get.interrupt() } else { continue = false } } } interruptionLevel = 0 } override def handle(signal: Signal): Unit = { interruptionLevel match { case 0 => interruptionLevel += 1 interrupt() case 1 => interruptionLevel += 1 ThreadPrintStream.out.println("Interrupting again will kill the JVM") case 2 => System.exit(1) } } }
Example 6
Source File: InterruptManager.scala From inox with Apache License 2.0 | 5 votes |
package inox package utils import scala.collection.JavaConverters._ import java.util.concurrent.atomic.{AtomicLong, AtomicBoolean} import sun.misc.{Signal, SignalHandler} import java.util.WeakHashMap class InterruptManager(reporter: Reporter) extends Interruptible { private[this] val interruptibles = new WeakHashMap[Interruptible, Boolean]() private[this] val sigINT = new Signal("INT") private[this] val lastTimestamp = new AtomicLong(0L) private val exitWindow = 1000L private[this] val handler = new SignalHandler { def handle(sig: Signal) { def now(): Long = System.currentTimeMillis() reporter.info("") if (now() - lastTimestamp.get < exitWindow) { reporter.warning("Aborting...") System.exit(1) } else { reporter.warning("Interrupted...") lastTimestamp.set(now()) interrupt() } } } val interrupted: AtomicBoolean = new AtomicBoolean(false) @inline def isInterrupted = interrupted.get def interrupt() = synchronized { if (!isInterrupted) { interrupted.set(true) val it = interruptibles.keySet.iterator for (i <- it.asScala.toList) i.interrupt() } else { reporter.warning("Already interrupted!") } } def reset() = synchronized { if (isInterrupted) { interrupted.set(false) } else { reporter.warning("Not interrupted!") } } def registerForInterrupts(i: Interruptible) = synchronized { if (isInterrupted) i.interrupt() interruptibles.put(i, true) } // We should not need this because keys should automatically be removed // from the WeakHashMap when gc'ed. // But let's have it anyway! def unregisterForInterrupts(i: Interruptible) = synchronized { interruptibles.remove(i) } def registerSignalHandler() = Signal.handle(sigINT, handler) }
Example 7
Source File: SignalLogger.scala From BigDatalog with Apache License 2.0 | 5 votes |
package org.apache.spark.util import org.apache.commons.lang3.SystemUtils import org.slf4j.Logger import sun.misc.{Signal, SignalHandler} def register(log: Logger): Unit = synchronized { if (SystemUtils.IS_OS_UNIX) { require(!registered, "Can't re-install the signal handlers") registered = true val signals = Seq("TERM", "HUP", "INT") for (signal <- signals) { try { new SignalLoggerHandler(signal, log) } catch { case e: Exception => log.warn("Failed to register signal handler " + signal, e) } } log.info("Registered signal handlers for [" + signals.mkString(", ") + "]") } } } private sealed class SignalLoggerHandler(name: String, log: Logger) extends SignalHandler { val prevHandler = Signal.handle(new Signal(name), this) override def handle(signal: Signal): Unit = { log.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName()) prevHandler.handle(signal) } }
Example 8
Source File: InterruptKeyMonitor.scala From shellbase with Apache License 2.0 | 5 votes |
package com.sumologic.shellbase.interrupts import com.sumologic.shellbase.interrupts.InterruptKeyMonitor.InterruptKeyHandler import sun.misc.{Signal, SignalHandler} class InterruptKeyMonitor { private val interruptKeyHandler = new InterruptKeyHandler() def init(): Unit = { Signal.handle(new Signal("INT"), interruptKeyHandler) } def shutdown(): Unit = {} def startMonitoring(interruptCallback: => Unit): Unit = { interruptKeyHandler.setCallback(interruptCallback) } def stopMonitoring(): Unit = { interruptKeyHandler.clearCallbacks() } def isMonitoring: Boolean = { interruptKeyHandler.hasACallback() } } object InterruptKeyMonitor { class InterruptKeyHandler extends SignalHandler { type CallbackFn = () => Unit private var callbackOpt: Option[CallbackFn] = None private var lastInterrupt = 0L def setCallback(interruptCallback: => Unit): Unit = { callbackOpt = Some(() => interruptCallback) } def clearCallbacks(): Unit = { callbackOpt = None } def hasACallback(): Boolean = callbackOpt.isDefined def now = System.currentTimeMillis() override def handle(sig: Signal) { if (callbackOpt.isDefined) { if (now - lastInterrupt < 1000) { println("Killing the shell...") System.exit(1) } else { println("\nPress Ctrl-C again to exit.") lastInterrupt = now callbackOpt.foreach(_.apply()) } } } } }
Example 9
Source File: SignalLogger.scala From spark1.52 with Apache License 2.0 | 5 votes |
package org.apache.spark.util import org.apache.commons.lang3.SystemUtils import org.slf4j.Logger import sun.misc.{Signal, SignalHandler} def register(log: Logger): Unit = synchronized { if (SystemUtils.IS_OS_UNIX) { require(!registered, "Can't re-install the signal handlers") registered = true val signals = Seq("TERM", "HUP", "INT") for (signal <- signals) { try { new SignalLoggerHandler(signal, log) } catch { case e: Exception => log.warn("Failed to register signal handler " + signal, e) } } log.info("Registered signal handlers for [" + signals.mkString(", ") + "]") } } } private sealed class SignalLoggerHandler(name: String, log: Logger) extends SignalHandler { val prevHandler = Signal.handle(new Signal(name), this) override def handle(signal: Signal): Unit = { log.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName()) prevHandler.handle(signal) } }
Example 10
Source File: ShutdownUtils.scala From Linkis with Apache License 2.0 | 5 votes |
package com.webank.wedatasphere.linkis.common.utils import sun.misc.{Signal, SignalHandler} import scala.collection.mutable.ArrayBuffer object ShutdownUtils { private val shutdownRunners = ArrayBuffer[ShutdownRunner]() def addShutdownHook(runnable: Runnable): Unit = addShutdownHook(Int.MaxValue, runnable) def addShutdownHook(order: Int, runnable: Runnable): Unit = shutdownRunners synchronized shutdownRunners += new DefaultShutdownRunner(order, runnable) def addShutdownHook(hook: => Unit): Unit = addShutdownHook(Int.MaxValue, hook) def addShutdownHook(order: Int, hook: => Unit): Unit = shutdownRunners synchronized shutdownRunners += new FunctionShutdownRunner(order, hook) def addShutdownHook(shutdownRunner: ShutdownRunner): Unit = shutdownRunners synchronized shutdownRunners += shutdownRunner private val signals = Array("TERM", "HUP", "INT").map(new Signal(_)) private val signalHandler = new SignalHandler { override def handle(signal: Signal): Unit = { val hooks = shutdownRunners.sortBy(_.order).toArray.map{ case m: DefaultShutdownRunner => Utils.defaultScheduler.execute(m) m case m => val runnable = new DefaultShutdownRunner(m.order, m) Utils.defaultScheduler.execute(runnable) runnable } val startTime = System.currentTimeMillis ShutdownUtils synchronized { while(System.currentTimeMillis - startTime < 30000 && hooks.exists(!_.isCompleted)) ShutdownUtils.wait(3000) } System.exit(0) } } signals.foreach(Signal.handle(_, signalHandler)) } trait ShutdownRunner extends Runnable { val order: Int } class DefaultShutdownRunner(override val order: Int, runnable: Runnable) extends ShutdownRunner { private var completed = false override def run(): Unit = Utils.tryFinally(runnable.run()){ completed = true ShutdownUtils synchronized ShutdownUtils.notify() } def isCompleted = completed } class FunctionShutdownRunner(override val order: Int, hook: => Unit) extends ShutdownRunner { override def run(): Unit = hook }
Example 11
Source File: package.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.tools.data.utils // scalastyle:off import sun.misc.{Signal, SignalHandler} // scalastyle:on package object ops { def addSigInfoHook(handler: => Unit): Unit = { Signal.handle( new Signal("INFO"), new SignalHandler { override def handle(signal: Signal): Unit = handler } ) } def getVersionFromManifest(): String = { getClass.getPackage.getSpecificationVersion } }
Example 12
Source File: PauseHandler.scala From subsearch with GNU General Public License v2.0 | 5 votes |
package com.gilazaria.subsearch.core.subdomainscanner import com.gilazaria.subsearch.core.subdomainscanner.DispatcherMessage.{PauseScanning, ResumeScanning} import com.gilazaria.subsearch.output.Logger import com.gilazaria.subsearch.utils.TimeUtils import akka.actor.ActorRef import akka.pattern.ask import scala.concurrent.ExecutionContext.Implicits.global import sun.misc.{Signal, SignalHandler} import scala.concurrent.Await object PauseHandler { def create(dispatcher: ActorRef, logger: Logger): PauseHandler = new PauseHandler(List("INT"), dispatcher, logger) case class InterruptException(msg: String) extends Exception(msg) case class ContinueException(msg: String) extends Exception(msg) } class PauseHandler(signalNames: List[String], dispatcher: ActorRef, logger: Logger) extends SignalHandler { import PauseHandler.{InterruptException, ContinueException} private val signalMap = signalNames.map(name => (name, Signal.handle(new Signal(name), this))).toMap private var pausingCalled: Boolean = false override def handle(signal: Signal) = { if (pausingCalled) forceExit() else pausingCalled = true implicit val timeout = TimeUtils.akkaAskTimeout Await.result(dispatcher ? PauseScanning, TimeUtils.awaitDuration) try { while (true) { logger.logPauseOptions() val option: String = System.console.readLine().toLowerCase if (option == "e") throw new InterruptException("Exited the program.") else if (option == "c") throw new ContinueException("Continuing the scan.") else logger.logInvalidPauseOption() } } catch { case InterruptException(msg) => exit() case ContinueException(msg) => resume() } } private def forceExit() = { logger.logScanForceCancelled() System.exit(0) } private def exit() = { logger.logScanCancelled() logger.completedLoggingFuture.andThen { case _ => System.exit(0) } } private def resume() = { dispatcher ! ResumeScanning pausingCalled = false } }
Example 13
Source File: SignalRefreshedTemplateSourceSpec.scala From cluster-broccoli with Apache License 2.0 | 5 votes |
package de.frosner.broccoli.templates import de.frosner.broccoli.signal.SignalManager import org.mockito.Mockito.{times, verify} import org.mockito.{ArgumentCaptor, Matchers} import org.specs2.mock.Mockito import org.specs2.mutable.Specification import sun.misc.{Signal, SignalHandler} class SignalRefreshedTemplateSourceSpec extends Specification with Mockito { "Receiving a SIGUSR2 signal" should { "update the cache" in { val signalManager = mock[SignalManager] val testTemplateSource = mock[CachedTemplateSource] val signalRefreshedTemplateSource = new SignalRefreshedTemplateSource(testTemplateSource, signalManager) val handler = ArgumentCaptor.forClass(classOf[SignalHandler]) there was one(signalManager).register(Matchers.eq(new Signal("USR2")), handler.capture()) there was no(testTemplateSource).refresh() there was no(testTemplateSource).loadTemplates() signalRefreshedTemplateSource.loadTemplates() there was no(testTemplateSource).refresh() there was one(testTemplateSource).loadTemplates() verify(testTemplateSource, times(1)).loadTemplates() handler.getValue.handle(new Signal("USR2")) there was one(testTemplateSource).refresh() there was one(testTemplateSource).loadTemplates() } } }
Example 14
Source File: UnixSignalManagerSpec.scala From cluster-broccoli with Apache License 2.0 | 5 votes |
package de.frosner.broccoli.signal import org.specs2.mock.Mockito import org.specs2.mutable.Specification import sun.misc.{Signal, SignalHandler} class UnixSignalManagerSpec extends Specification with Mockito { "Registering new signal" should { "fail if the signal is reserved by the JVM" in { val manager = new UnixSignalManager() manager.register(new Signal("USR1"), mock[SignalHandler]) must throwA( new IllegalArgumentException("Signal already used by VM or OS: SIGUSR1")) } "fail if the signal is already registered" in { val manager = new UnixSignalManager() val handler = mock[SignalHandler] manager.register(new Signal("USR2"), handler) manager.register(new Signal("USR2"), handler) must throwA( new IllegalArgumentException(s"Signal ${new Signal("USR2")} is already registered")) } } }
Example 15
Source File: UnixSignalManagerIntegrationSpec.scala From cluster-broccoli with Apache License 2.0 | 5 votes |
package de.frosner.broccoli.signal import org.specs2.mock.Mockito import org.specs2.mutable.Specification import sun.misc.{Signal, SignalHandler} class UnixSignalManagerIntegrationSpec extends Specification with Mockito { "Registering new signal" should { "trigger the handler when the signal is raised" in { val manager = new UnixSignalManager() val signal = new Signal("USR2") val handler = mock[SignalHandler] manager.register(signal, handler) Signal.raise(signal) Thread.sleep(1000) there was one(handler).handle(signal) } } }
Example 16
Source File: UnixSignalManager.scala From cluster-broccoli with Apache License 2.0 | 5 votes |
package de.frosner.broccoli.signal import javax.inject.Singleton import org.apache.commons.lang3.SystemUtils import sun.misc.{Signal, SignalHandler} import scala.collection.mutable @Singleton class UnixSignalManager extends SignalManager { private val signals = mutable.HashMap.empty[Signal, SignalHandler] def register(signal: Signal, handler: SignalHandler): Unit = if (SystemUtils.IS_OS_UNIX) { if (signals.contains(signal)) { throw new IllegalArgumentException(s"Signal $signal is already registered") } Signal.handle(signal, handler) signals.put(signal, handler) } else { throw new UnsupportedOperationException("Signal handling is only supported on UNIX") } def unregister(signal: Signal): Unit = if (signals.contains(signal)) { Signal.handle(signal, new SignalHandler { override def handle(signal: Signal): Unit = {} }) signals.remove(signal) } }
Example 17
Source File: ReportPlugin.scala From AppCrawler with Apache License 2.0 | 5 votes |
package com.testerhome.appcrawler.plugin import java.io import com.testerhome.appcrawler.{Report, URIElement} import com.testerhome.appcrawler._ import org.scalatest.FunSuite import org.scalatest.tools.Runner import sun.misc.{Signal, SignalHandler} import scala.collection.mutable.ListBuffer import scala.reflect.io.File class ReportPlugin extends Plugin with Report { var lastSize=0 override def start(): Unit ={ reportPath=new java.io.File(getCrawler().conf.resultDir).getCanonicalPath log.info(s"reportPath=${reportPath}") val tmpDir=new io.File(s"${reportPath}/tmp/") if(tmpDir.exists()==false){ log.info(s"create ${reportPath}/tmp/ directory") tmpDir.mkdir() } } override def stop(): Unit ={ generateReport() } override def afterElementAction(element: URIElement): Unit ={ val count=getCrawler().store.clickedElementsList.length log.info(s"clickedElementsList size = ${count}") val curSize=getCrawler().store.clickedElementsList.size if(curSize-lastSize > curSize/10+20 ){ log.info(s"${curSize}-${lastSize} > ${curSize}/10+10 ") log.info("generate test report ") generateReport() } } def generateReport(): Unit ={ Report.saveTestCase(getCrawler().store, getCrawler().conf.resultDir) Report.store=getCrawler().store Report.runTestCase() lastSize=getCrawler().store.clickedElementsList.size } }
Example 18
Source File: SignalLogger.scala From SparkCore with Apache License 2.0 | 5 votes |
package org.apache.spark.util import org.apache.commons.lang3.SystemUtils import org.slf4j.Logger import sun.misc.{Signal, SignalHandler} def register(log: Logger): Unit = synchronized { if (SystemUtils.IS_OS_UNIX) { require(!registered, "Can't re-install the signal handlers") registered = true val signals = Seq("TERM", "HUP", "INT") for (signal <- signals) { try { new SignalLoggerHandler(signal, log) } catch { case e: Exception => log.warn("Failed to register signal handler " + signal, e) } } log.info("Registered signal handlers for [" + signals.mkString(", ") + "]") } } } private sealed class SignalLoggerHandler(name: String, log: Logger) extends SignalHandler { val prevHandler = Signal.handle(new Signal(name), this) override def handle(signal: Signal): Unit = { log.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName()) prevHandler.handle(signal) } }