akka.actor._ Scala Examples

The following examples show how to use akka.actor._. 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: IngestionHandlerGateway.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.services

import akka.actor.SupervisorStrategy.Stop
import akka.actor.{OneForOneStrategy, _}
import akka.util.Timeout
import hydra.core.protocol.{InitiateHttpRequest, InitiateRequest}

import scala.concurrent.duration._


class IngestionHandlerGateway(registryPath: String)
    extends Actor
    with ActorLogging {

  private lazy val registry =
    context.actorSelection(registryPath).resolveOne()(Timeout(10.seconds))

  private implicit val ec = context.dispatcher

  override def receive = {
    case InitiateRequest(request, timeout, requestorOpt) =>
      val requestor = requestorOpt getOrElse sender
      ingest(
        registryRef =>
          DefaultIngestionHandler
            .props(request, registryRef, requestor, timeout),
        requestor
      )

    case InitiateHttpRequest(request, timeout, ctx) =>
      val requestor = sender
      ingest(
        registryRef =>
          HttpIngestionHandler.props(request, timeout, ctx, registryRef),
        requestor
      )
  }

  private def ingest(props: ActorRef => Props, requestor: ActorRef) = {
    registry
      .map(registryRef => context.actorOf(props(registryRef)))
      .recover { case e: Exception => requestor ! e }
  }

  override val supervisorStrategy =
    OneForOneStrategy() {
      case _ => Stop //stop ingestion IngestionRequestHandler always
    }
}

object IngestionHandlerGateway {

  val GroupName = "ingestion-handlers"

  def props(registryPath: String) =
    Props(classOf[IngestionHandlerGateway], registryPath)

} 
Example 2
Source File: ConfigActor.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
package com.stratio.sparta.serving.api.actor

import akka.actor.{Actor, _}
import akka.event.slf4j.SLF4JLogging
import com.stratio.sparta.serving.api.actor.ConfigActor._
import com.stratio.sparta.serving.api.constants.HttpConstant
import com.stratio.sparta.serving.core.config.SpartaConfig
import com.stratio.sparta.serving.core.constants.AppConstant
import com.stratio.sparta.serving.core.models.SpartaSerializer
import com.stratio.sparta.serving.core.models.frontend.FrontendConfiguration
import com.typesafe.config.Config
import spray.httpx.Json4sJacksonSupport

import scala.util.Try

class ConfigActor extends Actor with SLF4JLogging with Json4sJacksonSupport with SpartaSerializer {

  val apiPath = HttpConstant.ConfigPath

  val oauthConfig: Option[Config] = SpartaConfig.getOauth2Config
  val enabledSecurity: Boolean = Try(oauthConfig.get.getString("enable").toBoolean).getOrElse(false)
  val cookieName: String = Try(oauthConfig.get.getString("cookieName")).getOrElse(AppConstant.DefaultOauth2CookieName)

  override def receive: Receive = {
    case FindAll => findFrontendConfig()
    case _ => log.info("Unrecognized message in ConfigActor")
  }

  def findFrontendConfig(): Unit = {
    sender ! ConfigResponse(retrieveStringConfig())
  }

  def retrieveStringConfig(): FrontendConfiguration = {
    enabledSecurity match {
      case true => FrontendConfiguration(
        Try(SpartaConfig.getFrontendConfig.get
          .getInt("timeout")).getOrElse(AppConstant.DefaultFrontEndTimeout), Option(cookieName))
      case false => FrontendConfiguration(Try(SpartaConfig.getFrontendConfig.get
        .getInt("timeout")).getOrElse(AppConstant.DefaultFrontEndTimeout), Option(""))
    }
  }

}

object ConfigActor {
  object FindAll
  case class ConfigResponse(frontendConfiguration:FrontendConfiguration)
} 
Example 3
Source File: LauncherActorUtils.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
package com.stratio.sparta.serving.api.utils

import akka.actor.{Props, _}
import com.stratio.sparta.driver.service.StreamingContextService
import com.stratio.sparta.serving.api.actor.{LocalLauncherActor, MarathonLauncherActor}
import com.stratio.sparta.serving.core.actor.ClusterLauncherActor
import com.stratio.sparta.serving.core.actor.LauncherActor.Start
import com.stratio.sparta.serving.core.constants.AkkaConstant._
import com.stratio.sparta.serving.core.constants.AppConstant
import com.stratio.sparta.serving.core.models.policy.PolicyModel
import com.stratio.sparta.serving.core.utils.PolicyStatusUtils

trait LauncherActorUtils extends PolicyStatusUtils {

  val contextLauncherActorPrefix = "contextLauncherActor"

  val streamingContextService: StreamingContextService

  def launch(policy: PolicyModel, context: ActorContext): PolicyModel = {
    if (isAvailableToRun(policy)) {
      log.info("Streaming Context Available, launching policy ... ")
      val actorName = cleanActorName(s"$contextLauncherActorPrefix-${policy.name}")
      val policyActor = context.children.find(children => children.path.name == actorName)

      val launcherActor = policyActor match {
        case Some(actor) =>
          actor
        case None =>
          log.info(s"Launched -> $actorName")
          if (isExecutionType(policy, AppConstant.ConfigLocal)) {
            log.info(s"Launching policy: ${policy.name} with actor: $actorName in local mode")
            context.actorOf(Props(
              new LocalLauncherActor(streamingContextService, streamingContextService.curatorFramework)), actorName)
          } else {
            if(isExecutionType(policy, AppConstant.ConfigMarathon)) {
              log.info(s"Launching policy: ${policy.name} with actor: $actorName in marathon mode")
              context.actorOf(Props(new MarathonLauncherActor(streamingContextService.curatorFramework)), actorName)
            }
            else {
              log.info(s"Launching policy: ${policy.name} with actor: $actorName in cluster mode")
              context.actorOf(Props(new ClusterLauncherActor(streamingContextService.curatorFramework)), actorName)
            }
          }
      }
      launcherActor ! Start(policy)
    }
    policy
  }
} 
Example 4
Source File: HeadquartersConfiguration.scala    From ddd-leaven-akka-v2   with MIT License 5 votes vote down vote up
package ecommerce.headquarters.app

import java.util.UUID

import akka.actor.{Props, _}
import com.typesafe.config.Config
import ecommerce.headquarters.app.HeadquartersConfiguration._
import ecommerce.headquarters.processes.OrderProcessManager
import ecommerce.shipping.ShipmentId
import org.slf4j.Logger
import pl.newicom.dddd.actor.{ActorFactory, DefaultConfig, PassivationConfig}
import pl.newicom.dddd.aggregate.{AggregateRootActorFactory, AggregateRootLogger}
import pl.newicom.dddd.coordination.ReceptorConfig
import pl.newicom.dddd.office.LocalOfficeId
import pl.newicom.dddd.process._
import pl.newicom.dddd.scheduling.{Scheduler, SchedulerEvent, schedulingOfficeId}
import pl.newicom.eventstore.EventstoreSubscriber

import scala.concurrent.duration._

object HeadquartersConfiguration {
  val HQDepartment: String = "Headquarters"
}

trait HeadquartersConfiguration {

  def log: Logger
  def config: Config
  implicit def system: ActorSystem

  implicit val schedulingOfficeID: LocalOfficeId[Scheduler] = schedulingOfficeId(HQDepartment)
  implicit val commandQueueOfficeID: LocalOfficeId[CommandSink] = commandSinkOfficeId(HQDepartment)

  implicit object SchedulerFactory extends AggregateRootActorFactory[Scheduler] {
    override def props(pc: PassivationConfig) = Props(new Scheduler(DefaultConfig(pc, replyWithEvents = false)) with AggregateRootLogger[SchedulerEvent] {
      // TODO not needed
      override def id = "global"
    })
  }

  implicit object CommandSinkFactory extends AggregateRootActorFactory[CommandSink] {
    override def props(pc: PassivationConfig) = Props(new CommandSink(DefaultConfig(pc, replyWithEvents = false)) with AggregateRootLogger[CommandEnqueued])
  }

  implicit object OrderProcessManagerActorFactory extends SagaActorFactory[OrderProcessManager] {
    def props(pc: PassivationConfig): Props =
      Props(new OrderProcessManager(DefaultConfig(pc, replyWithEvents = false), () => new ShipmentId(UUID.randomUUID().toString)))
  }

  implicit def receptorActorFactory[A : LocalOfficeId : ActorFactory]: ReceptorActorFactory[A] = new ReceptorActorFactory[A] {
    def receptorFactory: ReceptorFactory = (config: ReceptorConfig) => {
      new Receptor(config.copy(capacity = 100)) with EventstoreSubscriber {
        override def redeliverInterval: FiniteDuration = 10.seconds
      }
    }
  }

} 
Example 5
Source File: HatServerProviderActor.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.resourceManagement.actors

import javax.inject.Inject

import akka.actor.{ Props, _ }
import akka.util.Timeout
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.utils.ActiveHatCounter
import play.api.libs.concurrent.InjectedActorSupport
import play.api.{ Configuration, Logger }

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

class HatServerProviderActor @Inject() (
    hatServerActorFactory: HatServerActor.Factory,
    activeHatcounter: ActiveHatCounter,
    configuration: Configuration)(
    implicit
    val ec: RemoteExecutionContext) extends Actor with InjectedActorSupport {
  private val log = Logger(this.getClass)
  import HatServerProviderActor._

  private val activeServers = mutable.HashMap[String, ActorRef]()
  private implicit val hatServerTimeout: Timeout = configuration.get[FiniteDuration]("resourceManagement.serverProvisioningTimeout")

  def receive: Receive = {
    case HatServerRetrieve(hat) =>
      log.debug(s"Retrieve HAT server $hat for $sender")
      val retrievingSender = sender
      getHatServerActor(hat) map { hatServerActor =>
        log.debug(s"Got HAT server provider actor, forwarding retrieval message with sender $sender $retrievingSender")
        hatServerActor tell (HatServerActor.HatRetrieve(), retrievingSender)
      } onComplete {
        case Success(_) ⇒ ()
        case Failure(e) ⇒ log.warn(s"Error while getting HAT server provider actor: ${e.getMessage}")
      }

    case HatServerStarted(_) =>
      activeHatcounter.increase()

    case HatServerStopped(_) =>
      activeHatcounter.decrease()

    case message =>
      log.debug(s"Received unexpected message $message")
  }

  private def getHatServerActor(hat: String): Future[ActorRef] = {
    doFindOrCreate(hat, hatServerTimeout.duration / 4)
  }

  private val maxAttempts = 3
  private def doFindOrCreate(hat: String, timeout: FiniteDuration, depth: Int = 0): Future[ActorRef] = {
    if (depth >= maxAttempts) {
      log.error(s"HAT server actor for $hat not resolved")
      throw new RuntimeException(s"Can not create actor for $hat and reached max attempts of $maxAttempts")
    }
    val selection = s"/user/hatServerProviderActor/hat:$hat"

    context.actorSelection(selection).resolveOne(timeout) map { hatServerActor =>
      log.debug(s"HAT server actor $selection resolved")
      hatServerActor
    } recoverWith {
      case ActorNotFound(_) =>
        log.debug(s"HAT server actor ($selection) not found, injecting child")
        val hatServerActor = injectedChild(hatServerActorFactory(hat), s"hat:$hat", props = (props: Props) => props.withDispatcher("hat-server-provider-actor-dispatcher"))
        activeServers(hat) = hatServerActor
        log.debug(s"Injected actor $hatServerActor")
        doFindOrCreate(hat, timeout, depth + 1)
    }
  }

}

object HatServerProviderActor {
  case class HatServerRetrieve(hat: String)

  case class HatServerStarted(hat: String)
  case class HatServerStopped(hat: String)
}