akka.routing.RoundRobinPool Scala Examples

The following examples show how to use akka.routing.RoundRobinPool. 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: ScalingOutApplication.scala    From Akka-Cookbook   with MIT License 5 votes vote down vote up
package com.packt.chapter7

import akka.actor.{ActorRef, ActorSystem, Props}
import akka.routing.RoundRobinPool

import scala.concurrent.duration._

object ScalingOutWorker extends App {
  val actorSystem = ActorSystem("WorkerActorSystem")
  implicit val dispatcher = actorSystem.dispatcher

  val selection = actorSystem.actorSelection("akka.tcp://[email protected]:2552/user/masterActor")
  selection.resolveOne(3 seconds).onSuccess {
    case masterActor : ActorRef =>
      println("We got the ActorRef for the master actor")
      val pool = RoundRobinPool(10)
      val workerPool = actorSystem.actorOf(Props[WorkerActor].withRouter(pool), "workerActor")
      masterActor ! RegisterWorker(workerPool)
  }
}


object ScalingOutMaster extends App {
  val actorSystem = ActorSystem("MasterActorSystem")
  val masterActor = actorSystem.actorOf(Props[MasterActor], "masterActor")

  (1 to 100).foreach(i => {
    masterActor ! Work(s"$i")
    Thread.sleep(5000) //Simulates sending work to the master actor every 5 seconds
  })

} 
Example 2
Source File: ParallelWork.scala    From hyperspark   with Apache License 2.0 5 votes vote down vote up
package pfsp.parallel;

import it.polimi.hyperh.solution.Solution
import it.polimi.hyperh.solution.EvaluatedSolution
import pfsp.problem.PfsProblem
import scala.util.Random
import akka.actor.Actor
import akka.actor.Props
import akka.event.Logging
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.routing.RoundRobinPool
import pfsp.solution.PfsSolution
import pfsp.solution.PfsEvaluatedSolution

object ParallelWork extends App {
  override def main(args: Array[String]) {
    
    def calculate(p:PfsProblem, evOldSolution:PfsEvaluatedSolution, nrOfWorkers: Int, sizeOfNeighbourhood: Int) {
      // Create an Akka system
      val system = ActorSystem("ParallelSystem")

      // create the result listener, which will print the result and 
      // shutdown the system
      val listener = system.actorOf(Props[Listener], name = "listener")

      // create the master
      val master = system.actorOf(Props(new Master(p, evOldSolution, nrOfWorkers, sizeOfNeighbourhood, listener)),
        name = "master")

      // start the calculation
      master ! Calculate
    }
    val p = PfsProblem.fromResources("inst_ta001.txt")
    val permutationList = Random.shuffle(p.jobs.toList)
    val oldSolution = PfsSolution(permutationList)
    var evOldSolution = p.evaluate(oldSolution).asInstanceOf[PfsEvaluatedSolution]
    calculate(p, evOldSolution, 7, 300)
  }
  case object Calculate
  case class Work(p: PfsProblem, solution: PfsSolution, initEndTimesMatrix: Array[Array[Int]])
  case class SingleResult(evSolution: EvaluatedSolution)
  case class FinalResult(evSolution: EvaluatedSolution, startMillis: Long)
}
class Worker extends Actor {
  import ParallelWork._
  def receive = {
    case Work(p, solution, initEndTimesMatrix) =>
      val evSolution = p.evaluatePartialSolution(solution.permutation)
      sender ! SingleResult(evSolution)
  }
}
class Listener extends Actor {
  import ParallelWork._
  override def receive = {
    case FinalResult(evSolution, duration) =>
      println("bestSolution: " + evSolution + " millis: " + duration)
      context.system.shutdown()
  }
}
class Master(p: PfsProblem,
             evOldSolution: PfsEvaluatedSolution,
             nrOfWorkers: Int,
             sizeOfNeighbourhood: Int,
             listener: ActorRef) extends Actor {
  import ParallelWork._
  var nrOfResults: Int = 0
  val startMillis: Long = System.currentTimeMillis
  val initEndTimesMatrix = p.jobsInitialTimes()
  var bestSolution: EvaluatedSolution = evOldSolution
  val workerRouter = context.actorOf(
    Props[Worker].withRouter(RoundRobinPool(nrOfWorkers)), name = "workerRouter")

  override def receive = {
    case Calculate =>
      for (i <- 0 until sizeOfNeighbourhood)
        workerRouter ! Work(p, PfsSolution(Random.shuffle(p.jobs.toList)), initEndTimesMatrix)
    case SingleResult(evNewSolution) =>
      nrOfResults += 1
      bestSolution = List(evNewSolution, bestSolution).min
      if (nrOfResults == sizeOfNeighbourhood) {
        // Send the result to the listener
        listener ! FinalResult(bestSolution, System.currentTimeMillis - startMillis)
        // Stops this actor and all its supervised children
        context.stop(self)
      }
  }
} 
Example 3
Source File: NERService.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package transform.ner

import akka.actor.ActorSystem
import akka.routing.RoundRobinPool
import javax.inject.{Inject, Singleton}
import org.pelagios.recogito.sdk.PluginEnvironment
import org.pelagios.recogito.sdk.ner.Entity
import play.api.{Configuration, Logger}
import scala.collection.JavaConverters._
import services.annotation.AnnotationService
import services.entity.builtin.EntityService
import services.task.{TaskService, TaskType}
import storage.uploads.Uploads
import transform.WorkerService

@Singleton
class NERService @Inject() (
  annotationService: AnnotationService,
  entityService: EntityService,
  taskService: TaskService,
  uploads: Uploads,
  config: Configuration,
  system: ActorSystem
) extends WorkerService(
  system, uploads,
  NERActor.props(taskService, annotationService, entityService, config), 3  
)

object NERService extends HasTeiNER {

  val TASK_TYPE = TaskType("NER")

  private def getEnvironment(config: Configuration) = {
    // Not the nicest way to handle this - suggestions welcome!
    val userDir = if (System.getProperty("user.dir").contains("/target/universal/stage"))
      System.getProperty("user.dir").replace("/target/universal/stage", "")
    else 
      System.getProperty("user.dir")

    val pluginsDir = s"${userDir}/plugins"

    val asMap = config.entrySet
      .filter(_._1.startsWith("plugins"))
      .toSeq
      .map { case(key, value) =>
        (key -> value.unwrapped.toString)
      }.toMap.asJava

    new PluginEnvironment(pluginsDir, asMap)
  }
  
  
  private[ner] def parseText(text: String, engine: Option[String], config: Configuration): Seq[Entity] = {
    val ner = engine match {
      case Some(identifier) => NERPluginManager.getEngine(identifier).get
      case None => NERPluginManager.getDefaultEngine
    }

    Logger.info(s"Running NER with engine ${ner.getName}")

    val entities = ner.parse(text, getEnvironment(config))
    entities.asScala
  }
     
} 
Example 4
Source File: GeoresolutionService.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package transform.georesolution

import akka.actor.ActorSystem
import akka.routing.RoundRobinPool
import javax.inject.{Inject, Singleton}
import services.annotation.AnnotationService
import services.entity.builtin.EntityService
import services.generated.tables.records.{DocumentRecord, DocumentFilepartRecord}
import services.task.{TaskService, TaskType}
import storage.uploads.Uploads
import transform.{WorkerActor, WorkerService}

@Singleton
class GeoresolutionService @Inject() (
  annotationService: AnnotationService,
  entityService: EntityService,
  taskService: TaskService,
  uploads: Uploads,
  system: ActorSystem
) extends WorkerService (
  system, uploads,
  GeoresolutionActor.props(taskService, annotationService, entityService), 4
)

object GeoresolutionService {
  
  val TASK_TYPE = TaskType("GEORESOLUTION")

} 
Example 5
Source File: TEIParserService.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package transform.tei

import akka.actor.ActorSystem
import akka.routing.RoundRobinPool
import java.io.{File, PrintWriter}
import javax.inject.{Inject, Singleton}
import org.joox.JOOX._
import org.w3c.dom.ranges.DocumentRange
import scala.collection.JavaConversions._
import services.annotation.{Annotation, AnnotationService}
import services.generated.tables.records.{DocumentRecord, DocumentFilepartRecord}
import services.task.{TaskService, TaskType}
import storage.uploads.Uploads
import transform.{WorkerActor, WorkerService}

@Singleton
class TEIParserService @Inject() (
  uploads: Uploads,
  annotationService: AnnotationService,
  taskService: TaskService, 
  system: ActorSystem
) extends WorkerService(
  system, uploads,
  TEIParserActor.props(taskService, annotationService), 10
)

object TEIParserService {

  val TASK_TYPE = TaskType("TEI_PARSING")
  
  private[tei] def extractEntities(
    part: DocumentFilepartRecord,
    file: File,
    replaceOriginalFile: Boolean = true
  ): Seq[Annotation] = {    
    val teiXML = $(file).document()
    val ranges = teiXML.asInstanceOf[DocumentRange]

    val places = $(teiXML).find("placeName").get
    val people = $(teiXML).find("persName").get
    val spans  = $(teiXML).find("span").get

    val annotations = (places ++ people ++ spans).map(TEITag.convert(part, _, ranges))

    if (replaceOriginalFile)
      new PrintWriter(file.getAbsolutePath)  {
        write($(teiXML).toString)
        close
      }

    annotations
  }
} 
Example 6
Source File: WorkerService.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package transform

import akka.actor.{ActorSystem, Props}
import java.util.UUID
import services.generated.tables.records.{DocumentRecord, DocumentFilepartRecord}
import storage.uploads.Uploads
import akka.routing.RoundRobinPool

class WorkerService(
  system: ActorSystem,
  uploads: Uploads,
  actorProps: Props,
  workerInstances: Int
) {
  
  val routerProps = actorProps
    .withRouter(RoundRobinPool(nrOfInstances = workerInstances))
    .withDispatcher("contexts.background-workers")
  
  val router = system.actorOf(routerProps)
  
  
  def spawnJob(
    document: DocumentRecord, 
    parts: Seq[DocumentFilepartRecord]) = spawn(document, parts, None)

} 
Example 7
Source File: TilingService.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package transform.tiling

import akka.actor.ActorSystem
import akka.routing.RoundRobinPool
import java.io.File
import javax.inject.{Inject, Singleton}
import scala.language.postfixOps
import services.generated.tables.records.{DocumentRecord, DocumentFilepartRecord}
import services.task.{TaskService, TaskType}
import storage.uploads.Uploads
import sys.process._
import transform.{WorkerActor, WorkerService}

@Singleton
class TilingService @Inject() (
  uploads: Uploads,
  taskService: TaskService, 
  system: ActorSystem
) extends WorkerService(
  system, uploads,
  TilingActor.props(taskService), 4
)      

object TilingService {

  val TASK_TYPE = TaskType("IMAGE_TILING")
  
  private[tiling] def createZoomify(file: File, destFolder: File) = {
    
    val result =  s"vips dzsave $file $destFolder --layout zoomify" !
    
    if (result != 0)
      throw new Exception("Image tiling failed for " + file.getAbsolutePath + " to " + destFolder.getAbsolutePath)
  }
  
} 
Example 8
Source File: Master.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.actors

import java.time.LocalDateTime
import java.util.concurrent.TimeUnit

import akka.actor.{Props, Cancellable, Actor}
import akka.routing.RoundRobinPool
import com.ivan.nikolov.scheduler.actors.messages.{Work, Schedule, Done}
import com.ivan.nikolov.scheduler.config.job.{Daily, Hourly}
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration.Duration
import scala.collection.mutable.ListBuffer
import scala.concurrent.ExecutionContext.Implicits.global

class Master(numWorkers: Int, actorFactory: ActorFactory) extends Actor with LazyLogging {
  val cancelables = ListBuffer[Cancellable]()
  
  val router = context.actorOf(
    Props(actorFactory.createWorkerActor()).withRouter(RoundRobinPool(numWorkers)),
    "scheduler-master-worker-router"
  )
  
  override def receive: Receive = {
    case Done(name, command, jobType, success) =>
      if (success) {
        logger.info("Successfully completed {} ({}).", name, command)
      } else {
        logger.error("Failure! Command {} ({}) returned a non-zero result code.", name, command)
      }
    case Schedule(configs) => 
      configs.foreach {
        case config =>
          val cancellable = this.context.system.scheduler.schedule(
            config.timeOptions.getInitialDelay(LocalDateTime.now(), config.frequency),
            config.frequency match {
              case Hourly => Duration.create(1, TimeUnit.HOURS)
              case Daily => Duration.create(1, TimeUnit.DAYS)
            },
            router,
            Work(config.name, config.command, config.jobType)
          )
          cancellable +: cancelables
          logger.info("Scheduled: {}", config)
      }
  }
  
  override def postStop(): Unit = {
    cancelables.foreach(_.cancel())
  }
} 
Example 9
Source File: Master.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.actors

import java.time.LocalDateTime
import java.util.concurrent.TimeUnit

import akka.actor.{Props, Cancellable, Actor}
import akka.routing.RoundRobinPool
import com.ivan.nikolov.scheduler.actors.messages.{Work, Schedule, Done}
import com.ivan.nikolov.scheduler.config.job.{Daily, Hourly}
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration.Duration
import scala.collection.mutable.ListBuffer
import scala.concurrent.ExecutionContext.Implicits.global

class Master(numWorkers: Int, actorFactory: ActorFactory) extends Actor with LazyLogging {
  val cancelables = ListBuffer[Cancellable]()
  
  val router = context.actorOf(
    Props(actorFactory.createWorkerActor()).withRouter(RoundRobinPool(numWorkers)),
    "scheduler-master-worker-router"
  )
  
  override def receive: Receive = {
    case Done(name, command, jobType, success) =>
      if (success) {
        logger.info("Successfully completed {} ({}).", name, command)
      } else {
        logger.error("Failure! Command {} ({}) returned a non-zero result code.", name, command)
      }
    case Schedule(configs) => 
      configs.foreach {
        case config =>
          val cancellable = this.context.system.scheduler.schedule(
            config.timeOptions.getInitialDelay(LocalDateTime.now(), config.frequency),
            config.frequency match {
              case Hourly => Duration.create(1, TimeUnit.HOURS)
              case Daily => Duration.create(1, TimeUnit.DAYS)
            },
            router,
            Work(config.name, config.command, config.jobType)
          )
          cancellable +: cancelables
          logger.info("Scheduled: {}", config)
      }
  }
  
  override def postStop(): Unit = {
    cancelables.foreach(_.cancel())
  }
} 
Example 10
Source File: AkkaUtil.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.utils

import akka.actor.{ActorRef, ActorContext, Props}
import akka.routing.{FromConfig, RoundRobinPool}
import org.slf4j.LoggerFactory


  def initActorFromConfig(props:Props, actorName:String, defNumRoutees:Int=3)(implicit context:ActorContext) : ActorRef = {
    val config = context.system.settings.config
    val deployPath = s"akka.actor.deployment.${context.self.path.toStringWithoutAddress}/$actorName"
    if (!config.hasPath(deployPath)) {
      // message primarily for debugging so that you can see immediately if your actor found the config
      externalLogger.debug(s"Could not find deployment config for path [$deployPath], deploying default round robin with $defNumRoutees routees")
      context.actorOf(RoundRobinPool(defNumRoutees).props(props), actorName)
    } else {
      context.actorOf(FromConfig.props(props), actorName)
    }
  }
} 
Example 11
Source File: CountDownLatchApp.scala    From Akka-Cookbook   with MIT License 5 votes vote down vote up
package com.packt.chapter10

import akka.actor.{ActorSystem, Props}
import akka.routing.RoundRobinPool

object CountDownLatchApp extends App {
  implicit val actorSystem = ActorSystem()
  import actorSystem._
  val routeesToSetUp = 2
  val countDownLatch = CountDownLatch(routeesToSetUp)

  actorSystem.actorOf(Props(classOf[CountDownLatchWorker], countDownLatch)
    .withRouter(RoundRobinPool(routeesToSetUp)), "workers")

  //Future based solution
  countDownLatch.result.onSuccess { case _ => log.info("Future completed successfully") }

  //Await based solution
  countDownLatch.await()
  actorSystem.terminate()
} 
Example 12
Source File: ThroughputTest.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.performance.throughput

import akka.testkit.TestProbe
import akka.actor.{Props, ActorSystem}
import org.scalatest.{WordSpecLike, BeforeAndAfterAll, MustMatchers}
import akka.routing.RoundRobinPool
import com.typesafe.config.ConfigFactory
import aia.performance.{ProcessCPURequest, SystemMessage, ProcessRequest}
import concurrent.duration._

class ThroughputTest extends WordSpecLike
  with BeforeAndAfterAll
  with MustMatchers {

  val configuration = ConfigFactory.load("performance/through")
  implicit val system = ActorSystem("ThroughputTest", configuration)

  "System" must {
    "fails to perform" in {
      val nrMessages = 99
      val nrWorkers = 3
      val statDuration = 2000 millis //((nrMessages * 10)+1000)/4 millis

      val end = TestProbe()
      val workers = system.actorOf(
        RoundRobinPool(nrWorkers).props(Props(new ProcessRequest(1 second, end.ref)).withDispatcher("my-dispatcher")),
        "Workers")

      val startTime = System.currentTimeMillis()
      for (i <- 0 until nrMessages) {
        workers ! new SystemMessage(startTime, 0, "")
      }
      val msg = end.receiveN(n = nrMessages, max = 9000 seconds).asInstanceOf[Seq[SystemMessage]]
      val endTime = System.currentTimeMillis()
      val total = endTime - startTime
      println("total process time %d Average=%d".format(total, total / nrMessages))
      val grouped = msg.groupBy(_.id)
      grouped.map {
        case (key, listMsg) => (key, listMsg.foldLeft(0L) { (m, x) => math.max(m, x.duration) })
      }.foreach(println(_))

      Thread.sleep(1000)

      system.stop(workers)
      
    }
  }
} 
Example 13
Source File: ThroughputCPUTest.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.performance.throughput

import akka.testkit.TestProbe
import akka.actor.{Props, ActorSystem}
import org.scalatest.{WordSpecLike, BeforeAndAfterAll, MustMatchers}
import akka.routing.RoundRobinPool
import com.typesafe.config.ConfigFactory
import aia.performance.{ProcessCPURequest, SystemMessage, ProcessRequest}
import concurrent.duration._


class ThroughputCPUTest extends WordSpecLike
  with BeforeAndAfterAll
  with MustMatchers {

  val configuration = ConfigFactory.load("performance/through")
  implicit val system = ActorSystem("ThroughputTest", configuration)

  "System" must {
    "fails to with cpu" in {
      val nrWorkers = 40
      val nrMessages = nrWorkers * 40

      val end = TestProbe()
      val workers = system.actorOf(
        RoundRobinPool(nrWorkers).props(
          Props(new ProcessCPURequest(250 millis, end.ref)).withDispatcher("my-dispatcher")),
        "Workers-cpu")

      val startTime = System.currentTimeMillis()
      for (i <- 0 until nrMessages) {
        workers ! new SystemMessage(startTime, 0, "")
      }
      val msg = end.receiveN(n = nrMessages, max = 9000 seconds).asInstanceOf[Seq[SystemMessage]]
      val endTime = System.currentTimeMillis()
      val total = endTime - startTime
      println("total process time %d Average=%d".format(total, total / nrMessages))
      val grouped = msg.groupBy(_.id)
      grouped.map {
        case (key, listMsg) => (key, listMsg.foldLeft(0L) { (m, x) => math.max(m, x.duration) })
      }.foreach(println(_))

      Thread.sleep(1000)

      system.stop(workers)
      
    }
  }
} 
Example 14
Source File: SchemaManagerRouter.scala    From schedoscope   with Apache License 2.0 5 votes vote down vote up
package org.schedoscope.scheduler.actors

import akka.actor.SupervisorStrategy._
import akka.actor.{Actor, ActorInitializationException, ActorRef, OneForOneStrategy, Props}
import akka.event.Logging
import akka.routing.RoundRobinPool
import org.schedoscope.conf.SchedoscopeSettings
import org.schedoscope.scheduler.messages._
import org.schedoscope.scheduler.utils.BackOffSupervision
import org.schedoscope.schema.RetryableSchemaManagerException

import scala.concurrent.duration._


  override val supervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = -1) {
      case _: RetryableSchemaManagerException => Restart
      case _: ActorInitializationException => Restart
      case _ => Escalate
    }

  override def preStart {
    metadataLoggerActor = actorOf(
      MetadataLoggerActor.props(settings.jdbcUrl, settings.metastoreUri, settings.kerberosPrincipal),
      "metadata-logger")
    partitionCreatorActor = actorOf(
      PartitionCreatorActor.props(settings.jdbcUrl, settings.metastoreUri, settings.kerberosPrincipal, self)
        .withRouter(new RoundRobinPool(settings.metastoreConcurrency)),
      "partition-creator")
  }

  def scheduleTick(managedActor: ActorRef, backOffTime: FiniteDuration) {
    system.scheduler.scheduleOnce(backOffTime, managedActor, "tick")
  }

  def manageActorLifecycle(metaActor: ActorRef) {
    val slot = settings.backOffSlotTime millis
    val delay = settings.backOffMinimumDelay millis

    val backOffTime = metastoreActorsBackOffSupervision.manageActorLifecycle(
      managedActor = metaActor,
      backOffSlotTime = slot,
      backOffMinimumDelay = delay)

    scheduleTick(metaActor, backOffTime)
  }


  def receive = {

    case "tick" => manageActorLifecycle(sender)

    case m: CheckOrCreateTables => partitionCreatorActor forward m

    case a: AddPartitions => partitionCreatorActor forward a

    case s: SetViewVersion => metadataLoggerActor forward s

    case l: LogTransformationTimestamp => metadataLoggerActor forward l

    case g: GetMetaDataForMaterialize => partitionCreatorActor forward g

  }
}

object SchemaManagerRouter {
  def props(settings: SchedoscopeSettings) = (Props(classOf[SchemaManagerRouter], settings)).withDispatcher("akka.actor.schema-manager-dispatcher")
} 
Example 15
Source File: ReplicaCoordinatorActor.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.actors

import akka.actor.{Actor, Props}
import akka.routing.{DefaultResizer, RoundRobinPool}
import justin.db.actors.protocol.{ReadData, WriteData}
import justin.db.replica.read.ReplicaReadCoordinator
import justin.db.replica.write.ReplicaWriteCoordinator

import scala.concurrent.ExecutionContext

class ReplicaCoordinatorActor(readCoordinator: ReplicaReadCoordinator, writeCoordinator: ReplicaWriteCoordinator) extends Actor {

  private implicit val ec: ExecutionContext = context.dispatcher

  override def receive: Receive = {
    case rd: ReadData  => readCoordinator.apply(rd.cmd, rd.clusterMembers).foreach(rd.sender ! _)
    case wd: WriteData => writeCoordinator.apply(wd.cmd, wd.clusterMembers).foreach(wd.sender ! _)
  }
}

object ReplicaCoordinatorActor {

  def props(readCoordinator: ReplicaReadCoordinator, writeCoordinator: ReplicaWriteCoordinator): Props = {
    Props(new ReplicaCoordinatorActor(readCoordinator, writeCoordinator))
  }
}

object RoundRobinCoordinatorRouter {
  def routerName: String = "CoordinatorRouter"

  private val pool = RoundRobinPool(
    nrOfInstances = 5,
    resizer = Some(DefaultResizer(lowerBound = 2, upperBound = 15))
  )

  def props(readCoordinator: ReplicaReadCoordinator, writeCoordinator: ReplicaWriteCoordinator): Props = {
    pool.props(ReplicaCoordinatorActor.props(readCoordinator, writeCoordinator))
  }
} 
Example 16
Source File: TypedCommandManager.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.command.typed

import akka.actor.{Actor, ActorRef, Props}
import akka.routing.{FromConfig, RoundRobinPool}
import com.webtrends.harness.HarnessConstants
import com.webtrends.harness.health.{ActorHealth, ComponentState, HealthComponent}
import com.webtrends.harness.logging.LoggingAdapter

import scala.collection.mutable
import scala.concurrent.Future
import scala.util.Try

case class RegisterCommand[T<:TypedCommand[_,_]](name:String, props: Props, checkHealth: Boolean)

class TypedCommandManager extends Actor with ActorHealth with LoggingAdapter {

  val healthCheckChildren = mutable.ArrayBuffer.empty[ActorRef]

  val config = context.system.settings.config.getConfig("akka.actor.deployment")

  override def receive: Receive = health orElse {
    case RegisterCommand(name, props, checkHealth) => sender ! registerCommand(name, props, checkHealth)
  }

  def registerCommand[T<:TypedCommand[_,_]](name: String, actorProps: Props, checkHealth: Boolean): ActorRef = {
    TypedCommandManager.commands.get(name) match {
      case Some(commandRef) =>
        log.warn(s"Command $name has already been added, not re-adding it.")
        commandRef
      case None =>
        val props = if (config.hasPath(s"akka.actor.deployment.${HarnessConstants.TypedCommandFullName}/$name")) {
          FromConfig.props(actorProps)
        } else {
          val nrRoutees = Try { config.getInt(HarnessConstants.KeyCommandsNrRoutees) }.getOrElse(5)
          RoundRobinPool(nrRoutees).props(actorProps)
        }
        val commandRef = context.actorOf(props, name)
        TypedCommandManager.commands(name) = commandRef
        if (checkHealth) {
          healthCheckChildren += commandRef
        }
        commandRef
    }
  }

  override def getHealthChildren: Iterable[ActorRef] = {
    healthCheckChildren
  }

  override def getHealth: Future[HealthComponent] = {
    Future.successful(
      HealthComponent(self.path.toString, ComponentState.NORMAL,
        s"Managing ${TypedCommandManager.commands.size} typed commands")
    )
  }
}

object TypedCommandManager {
  private[typed] val commands = mutable.Map[String, ActorRef]()
  def props = Props[TypedCommandManager]
} 
Example 17
Source File: PolicyManager.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.policy

import akka.pattern.{ask, pipe}
import akka.actor.{ActorRef, Props}
import akka.routing.{RoundRobinPool, FromConfig}
import com.webtrends.harness.HarnessConstants
import com.webtrends.harness.app.{PrepareForShutdown, HActor}
import com.webtrends.harness.app.HarnessActor.SystemReady
import org.slf4j.LoggerFactory

import scala.collection.mutable
import scala.concurrent.{Future, Promise}
import scala.util.{Success, Failure}

case class GetPolicies()



class PolicyManager extends PrepareForShutdown {

  import context.dispatcher

  override def receive = super.receive orElse {
    case GetPolicies => pipe(getPolicies) to sender

    case SystemReady => // ignore
  }

  protected def getPolicies : Future[Map[String, Policy]] = {
    Future { PolicyManager.getPolicies.get }
  }

}

object PolicyManager {
  private val externalLogger = LoggerFactory.getLogger(this.getClass)

  // map that stores the name of the command with the actor it references
  val policyMap = mutable.Map[String, Policy]()

  def props = Props[PolicyManager]

  def addPolicy[T<:Policy](name:String, ref:T) = {
    ref.addCommands
    externalLogger.debug(s"Policy $name inserted into Policy Manager map.")
    policyMap += (name -> ref)
  }

  protected def removePolicy(name:String) : Boolean = {
    policyMap.get(name) match {
      case Some(n) =>
        externalLogger.debug(s"Policy $name removed from Policy Manager map.")
        policyMap -= name
        true
      case None => false
    }
  }

  def getPolicy(name:String) : Option[Policy] = policyMap.get(name)

  def getPolicies : Option[Map[String, Policy]] = Some(policyMap.toMap)
}