org.apache.commons.lang3.SystemUtils Scala Examples

The following examples show how to use org.apache.commons.lang3.SystemUtils. 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: StandaloneDockerContainerFactory.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.containerpool.docker

import akka.actor.ActorSystem
import org.apache.commons.lang3.SystemUtils
import org.apache.openwhisk.common.{Logging, TransactionId}
import org.apache.openwhisk.core.{ConfigKeys, WhiskConfig}
import org.apache.openwhisk.core.containerpool.{Container, ContainerFactory, ContainerFactoryProvider}
import org.apache.openwhisk.core.entity.{ByteSize, ExecManifest, InvokerInstanceId}
import pureconfig._
import pureconfig.generic.auto._

import scala.collection.concurrent.TrieMap
import scala.concurrent.{ExecutionContext, Future}

object StandaloneDockerContainerFactoryProvider extends ContainerFactoryProvider {
  override def instance(actorSystem: ActorSystem,
                        logging: Logging,
                        config: WhiskConfig,
                        instanceId: InvokerInstanceId,
                        parameters: Map[String, Set[String]]): ContainerFactory = {
    val client =
      if (SystemUtils.IS_OS_MAC) new DockerForMacClient()(actorSystem.dispatcher)(logging, actorSystem)
      else if (SystemUtils.IS_OS_WINDOWS) new DockerForWindowsClient()(actorSystem.dispatcher)(logging, actorSystem)
      else new DockerClientWithFileAccess()(actorSystem.dispatcher)(logging, actorSystem)

    new StandaloneDockerContainerFactory(instanceId, parameters)(
      actorSystem,
      actorSystem.dispatcher,
      logging,
      client,
      new RuncClient()(actorSystem.dispatcher)(logging, actorSystem))
  }
}

case class StandaloneDockerConfig(pullStandardImages: Boolean)

class StandaloneDockerContainerFactory(instance: InvokerInstanceId, parameters: Map[String, Set[String]])(
  implicit actorSystem: ActorSystem,
  ec: ExecutionContext,
  logging: Logging,
  docker: DockerApiWithFileAccess,
  runc: RuncApi)
    extends DockerContainerFactory(instance, parameters) {
  private val pulledImages = new TrieMap[String, Boolean]()
  private val factoryConfig = loadConfigOrThrow[StandaloneDockerConfig](ConfigKeys.standaloneDockerContainerFactory)

  override def createContainer(tid: TransactionId,
                               name: String,
                               actionImage: ExecManifest.ImageName,
                               userProvidedImage: Boolean,
                               memory: ByteSize,
                               cpuShares: Int)(implicit config: WhiskConfig, logging: Logging): Future[Container] = {

    //For standalone server usage we would also want to pull the OpenWhisk provided image so as to ensure if
    //local setup does not have the image then it pulls it down
    //For standard usage its expected that standard images have already been pulled in.
    val imageName = actionImage.resolveImageName(Some(runtimesRegistryConfig.url))
    val pulled =
      if (!userProvidedImage
          && factoryConfig.pullStandardImages
          && !pulledImages.contains(imageName)
          && actionImage.prefix.contains("openwhisk")) {
        docker.pull(imageName)(tid).map { _ =>
          logging.info(this, s"Pulled OpenWhisk provided image $imageName")
          pulledImages.put(imageName, true)
          true
        }
      } else Future.successful(true)

    pulled.flatMap(_ => super.createContainer(tid, name, actionImage, userProvidedImage, memory, cpuShares))
  }

  override def init(): Unit = {
    logging.info(
      this,
      s"Standalone docker container factory config pullStandardImages: ${factoryConfig.pullStandardImages}")
    super.init()
  }
}

trait WindowsDockerClient {
  self: DockerClient =>

  override protected def executableAlternatives: List[String] = {
    val executable = loadConfig[String]("whisk.docker.executable").toOption
    List("""C:\Program Files\Docker\Docker\resources\bin\docker.exe""") ++ executable
  }
}

class DockerForWindowsClient(dockerHost: Option[String] = None)(executionContext: ExecutionContext)(
  implicit log: Logging,
  as: ActorSystem)
    extends DockerForMacClient(dockerHost)(executionContext)
    with WindowsDockerClient {
  //Due to some Docker + Windows + Go parsing quirks need to add double quotes around whole command
  //See https://github.com/moby/moby/issues/27592#issuecomment-255227097
  override def inspectCommand: String = """"{{(index (index .NetworkSettings.Ports \"8080/tcp\") 0).HostPort}}""""
} 
Example 2
Source File: SignalLogger.scala    From SparkCore   with Apache License 2.0 5 votes vote down vote up
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 3
Source File: UnixSignalManager.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
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 4
Source File: SignalLogger.scala    From iolap   with Apache License 2.0 5 votes vote down vote up
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 5
Source File: SignalLogger.scala    From spark1.52   with Apache License 2.0 5 votes vote down vote up
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 6
Source File: Backend.scala    From Graphviz4S   with MIT License 5 votes vote down vote up
package com.liangdp.graphviz4s

import org.apache.commons.lang3.SystemUtils


  @throws(classOf[RuntimeException])
  def view(filePath: String): Unit = {
    val command = s"$viewFileCommand $filePath"
    import sys.process._
    try {
      command !
    } catch {
      case _: Throwable =>
        val errorMsg = s"failed to execute $command"
        throw new RuntimeException(errorMsg)
    }
  }
} 
Example 7
Source File: SignalLogger.scala    From BigDatalog   with Apache License 2.0 5 votes vote down vote up
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: SystemContext.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.conf

import org.apache.commons.lang3.SystemUtils


    def isMultiOpenSuported: Boolean

  }

  object OSFamily {
    object Windows extends OSFamily {
      override val openCommand: String = "start"
      override val isMultiOpenSuported: Boolean = false
    }

    object Mac extends OSFamily {
      override val openCommand: String = "open"
      override val isMultiOpenSuported: Boolean = true
    }

    object Linux extends OSFamily {
      override val openCommand: String = "xdg-open"
      override val isMultiOpenSuported: Boolean = false
    }

    object Other extends OSFamily {
      override val openCommand: String = "xdg-open"
      override val isMultiOpenSuported: Boolean = false
    }
  }

  def osFamily: OSFamily = {
    true match {
      case _ if SystemUtils.IS_OS_WINDOWS => OSFamily.Windows
      case _ if SystemUtils.IS_OS_MAC => OSFamily.Mac
      case _ if SystemUtils.IS_OS_LINUX => OSFamily.Linux
      case _ if SystemUtils.IS_OS_UNIX => OSFamily.Other
    }
  }

  val userName: String = System.getProperty("user.name")

  val userHome: String = System.getProperty("user.home")

} 
Example 9
Source File: Tar.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.setup

import java.net.URL
import java.nio.file._
import java.nio.file.attribute.PosixFilePermissions

import scala.util.Try

import org.apache.commons.compress.archivers.tar.{TarArchiveEntry, TarArchiveInputStream}
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.lang3.SystemUtils


object Tar {

  val execPermissions = PosixFilePermissions.fromString("rwxr-xr-x")

  def download(url: URL): Try[TarArchiveInputStream] =
    Try(new TarArchiveInputStream(new GzipCompressorInputStream(url.openStream())))

  def extractTo(path: Path, tar: TarArchiveInputStream): Try[Path] = Try {
    def next() = Option(tar.getNextTarEntry())

    @annotation.tailrec
    def go(entry: Option[TarArchiveEntry], paths: List[Path]): List[Path] = entry match {
      case None =>
        paths.reverse
      case Some(entry) =>
        val name = entry.getName
        val subpath = path.resolve(name).normalize

        if (subpath.startsWith(path) && !Files.exists(subpath, LinkOption.NOFOLLOW_LINKS)) {
          Files.createDirectories(subpath.getParent)
          if (entry.isDirectory)
            Files.createDirectory(subpath)
          else if (entry.isSymbolicLink)
            Files.createSymbolicLink(subpath, Paths.get(entry.getLinkName))
          else if (entry.isLink)
            Files.createLink(subpath, path.resolve(Paths.get(entry.getLinkName)))
          else if (entry.isFile) {
            Files.copy(tar, subpath)
            if (!SystemUtils.IS_OS_WINDOWS && (entry.getMode % 2 == 1))
              Files.setPosixFilePermissions(subpath, execPermissions)
          }
          else
            sys.error("unknown tar file entry")
        }
        else
          sys.error("malicious tar file or file already exists")

        val p = if (entry.isDirectory) List(subpath) else Nil

        go(next(), p ::: paths)
    }

    go(next(), Nil).foldLeft(List.empty[Path]) { (roots, path) =>
      if (roots.exists(path.startsWith))
        roots
      else
        path :: roots
    } match {
      case List(root) => root
      case _ => sys.error("untarring created more than one root directory")
    }
  }

} 
Example 10
Source File: SassCompiler.scala    From sbt-sass   with Apache License 2.0 5 votes vote down vote up
package org.madoushi.sbt.sass

import java.io.File

import org.apache.commons.lang3.SystemUtils

import scala.sys.process._

object SassCompiler {
  // The actual `sass` command depending on the operating system.
  lazy val command =
    if(SystemUtils.IS_OS_WINDOWS)
      Seq("cmd", "/c", "sass.bat")
    else
      Seq("sass")

  
  private def runCommand(cmd: ProcessBuilder) = {
    val stdout = Vector.newBuilder[String]
    val stderr = Vector.newBuilder[String]

    val captureOutput = ProcessLogger(
      line => stdout += line,
      line => stderr += line
    )

    val proc = cmd.run(captureOutput)
    if (proc.exitValue() != 0) {
      throw new SassCompilerException(stderr.result())
    }
    stdout.result()
  }
}