akka.actor.ActorPath Scala Examples

The following examples show how to use akka.actor.ActorPath. 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: TAC.scala    From akka-tools   with MIT License 5 votes vote down vote up
package no.nextgentel.oss.akkatools.example2.trustaccountcreation

import java.util.concurrent.TimeUnit

import akka.actor.Status.Failure
import akka.actor.{ActorSystem, Props, ActorPath}
import no.nextgentel.oss.akkatools.aggregate._
import no.nextgentel.oss.akkatools.example2.other.{DoCreateTrustAccount, DoPerformESigning, DoSendEmailToCustomer}

import scala.concurrent.duration.FiniteDuration

class TACAggregate
(
  dmSelf:ActorPath,
  eSigningSystem:ActorPath,
  emailSystem:ActorPath,
  trustAccountSystem:ActorPath
) extends GeneralAggregateDMViaEvent[TACEvent, TACState](dmSelf) {

  override def persistenceIdBase() = TACAggregate.persistenceIdBase

  // Override this one to set different timeout
  override def idleTimeout() = FiniteDuration(60, TimeUnit.SECONDS)

  override var state = TACState.empty() // This is the state of our initial state (empty)

  // transform command to event
  override def cmdToEvent = {
    case c:CreateNewTACCmd        =>
      ResultingEvent( RegisteredEvent(c.info) )
        .onSuccess{ sender() ! "ok" }
        .onError{   (e) => sender() ! Failure(new Exception(s"Failed: $e"))}

    case c:ESigningFailedCmd      => ResultingEvent( ESigningFailedEvent() )
    case c:ESigningCompletedCmd   => ResultingEvent( ESigningCompletedEvent() )
    case c:CompletedCmd           => ResultingEvent( CreatedEvent(c.trustAccountId) )
    case c:DeclinedCmd            => ResultingEvent( DeclinedEvent(c.cause) )
  }

  override def generateDMs = {
    case e:RegisteredEvent  =>
      // We must send message to eSigningSystem
      val msg = DoPerformESigning(dispatchId, e.info.customerNo)
      ResultingDMs( msg, eSigningSystem)

    case e:ESigningCompletedEvent =>
      // ESigning is completed, so we should init creation of the TrustAccount
      val info = state.info.get
      val msg = DoCreateTrustAccount(dispatchId, info.customerNo, info.trustAccountType)
      ResultingDMs(msg, trustAccountSystem)


    case e:DeclinedEvent =>
      // The TrustAccountCreation-process failed - must notify customer
      val msg = DoSendEmailToCustomer(state.info.get.customerNo, s"Sorry.. TAC-failed: ${e.cause}")
      ResultingDMs(msg, emailSystem)

    case e:CreatedEvent =>
      // The TrustAccountCreation-process was success - must notify customer
      val msg = DoSendEmailToCustomer(state.info.get.customerNo, s"Your TrustAccount '${e.trustAccountId}' has been created!")
      ResultingDMs(msg, emailSystem)

  }
}

object TACAggregate {

  val persistenceIdBase = "TAC-"

  def props(dmSelf:ActorPath,
            eSigningSystem:ActorPath,
            emailSystem:ActorPath,
            trustAccountSystem:ActorPath) = Props(new TACAggregate(dmSelf, eSigningSystem, emailSystem ,trustAccountSystem))
}


class TACStarter(system:ActorSystem) extends AggregateStarter("tac", system) with AggregateViewStarter {

  def config(eSigningSystem:ActorPath,
             emailSystem:ActorPath,
             trustAccountSystem:ActorPath):TACStarter = {
    setAggregatePropsCreator{
      dmSelf =>
        TACAggregate.props(dmSelf, eSigningSystem, emailSystem, trustAccountSystem)
    }
    this
  }

  override def createViewProps(aggregateId: String): Props =
    Props( new GeneralAggregateView[TACEvent, TACState](TACAggregate.persistenceIdBase, aggregateId, TACState.empty(), true))
} 
Example 2
package no.nextgentel.oss.akkatools.aggregate.aggregateTest_usingAggregateStateBase

import java.util.UUID

import akka.actor.{ActorPath, ActorSystem, Props}
import akka.persistence.{DeleteMessagesFailure, DeleteMessagesSuccess, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotMetadata, SnapshotOffer}
import akka.testkit.{TestKit, TestProbe}
import com.typesafe.config.ConfigFactory
import no.nextgentel.oss.akkatools.aggregate._
import no.nextgentel.oss.akkatools.testing.AggregateTesting
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuiteLike, Matchers}
import org.slf4j.LoggerFactory



  override def onSnapshotOffer(offer: SnapshotOffer): Unit = {
    state = offer.snapshot.asInstanceOf[StringState]
  }

  override def acceptSnapshotRequest(req: SaveSnapshotOfCurrentState): Boolean = {
    if (state == StringState("WAT")) {
      state = StringState("SAVED")
      true
    }
    else {
      state = StringState("WAT") //So it works second time
      false
    }
  }

  override def onSnapshotSuccess(success: SaveSnapshotSuccess): Unit = {
    state = StringState("SUCCESS_SNAP")
  }

  override def onSnapshotFailure(failure: SaveSnapshotFailure): Unit = {
    state = StringState("FAIL_SNAP")
  }

  override def onDeleteMessagesSuccess(success: DeleteMessagesSuccess): Unit = {
    state = StringState("SUCCESS_MSG")
  }

  override def onDeleteMessagesFailure(failure: DeleteMessagesFailure): Unit = {
    state = StringState("FAIL_MSG")
  }

  // Used as prefix/base when constructing the persistenceId to use - the unique ID is extracted runtime from actorPath which is construced by Sharding-coordinator
  override def persistenceIdBase(): String = "/x/"
}

case class StringEv(data: String)

case class StringState(data:String) extends AggregateStateBase[StringEv, StringState] {
  override def transitionState(event: StringEv): StateTransition[StringEv, StringState] =
    StateTransition(StringState(event.data))
} 
Example 3
Source File: HydraIngestJsonSupportSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.http

import akka.actor.ActorPath
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import hydra.core.HydraException
import hydra.core.ingest.IngestionReport
import hydra.core.protocol.{
  IngestorCompleted,
  IngestorError,
  IngestorStatus,
  InvalidRequest
}
import hydra.ingest.IngestorInfo
import org.joda.time.DateTime
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike

class HydraIngestJsonSupportSpec
    extends Matchers
    with AnyFunSpecLike
    with HydraIngestJsonSupport
    with SprayJsonSupport {

  import spray.json._

  describe("Hydra Json Support") {
    it("converts IngestorInfo objects") {
      val time = DateTime.now
      val info = IngestorInfo(
        "test",
        "test",
        ActorPath.fromString("akka://hydra/test/ingestor"),
        time
      )
      val expectedValue =
        s"""{"name":"test","group":"test","path":"akka://hydra/test/ingestor",
          "registeredAt":${time.toJson}}""".parseJson
      info.toJson shouldBe expectedValue
    }

    it("converts IngestorStatus objects") {
      val st = InvalidRequest(new IllegalArgumentException("error"))
        .asInstanceOf[IngestorStatus]
      val stn = InvalidRequest(new IllegalArgumentException())
        .asInstanceOf[IngestorStatus]
      st.toJson shouldBe """{"code":400,"message":"error"}""".parseJson
      stn.toJson shouldBe """{"code":400,"message":"Unknown error."}""".parseJson
      intercept[NotImplementedError] {
        """{"code":400,"message":"error"}""".parseJson.convertTo[IngestorStatus]
      }
    }

    it("converts IngestorError objects with no message") {
      val st = IngestorError(new IllegalArgumentException("error"))
        .asInstanceOf[IngestorStatus]
      val stn = IngestorError(new IllegalArgumentException(""))
        .asInstanceOf[IngestorStatus]
      val stnCause = IngestorError(
        new HydraException("hydra", new IllegalArgumentException("underlying"))
      ).asInstanceOf[IngestorStatus]
      st.toJson shouldBe """{"code":503,"message":"error"}""".parseJson
      stn.toJson shouldBe """{"code":503,"message":""}""".parseJson
      stnCause.toJson shouldBe """{"code":503,"message":"hydra: underlying"}""".parseJson
    }

    it("converts IngestionReport objects") {
      val report =
        IngestionReport("a123", Map("testIngestor" -> IngestorCompleted), 200)
      val json = report.toJson.asJsObject.fields

      val pjson =
        """{"correlationId":"a123","ingestors":{"testIngestor":{"code":200,"message":"OK"}}}""".parseJson.asJsObject.fields

      json("correlationId") shouldBe pjson("correlationId")
      json("ingestors") shouldBe pjson("ingestors")

      intercept[NotImplementedError] {
        """{"correlationId":"1","ingestors":{"testIngestor":{"code":200,
          "message":"OK"}}}""".parseJson.convertTo[IngestionReport]
      }
    }

    it("converts IngestionReport without any ingestors") {
      val report = IngestionReport("1", Map.empty, 200)
      val json = report.toJson.asJsObject.fields

      val pjson =
        """{"correlationId":"1","ingestors":{}}""".parseJson.asJsObject.fields

      json("correlationId") shouldBe pjson("correlationId")
      json("ingestors") shouldBe pjson("ingestors")

    }
  }

} 
Example 4
Source File: HydraJsonSupport.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.core.marshallers

import java.io.{PrintWriter, StringWriter}
import java.util.UUID

import akka.actor.ActorPath
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCode
import hydra.common.util.Resource._
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import spray.json.{JsString, _}

import scala.util.{Failure, Success, Try}


  implicit def tryWriter[R: JsonWriter]: RootJsonWriter[Try[R]] =
    new RootJsonWriter[Try[R]] {

      override def write(responseTry: Try[R]): JsValue = {
        responseTry match {
          case Success(r) => JsObject("success" -> r.toJson)
          case Failure(t) => JsObject("failure" -> t.toJson)
        }
      }
    }

  implicit object StreamTypeFormat extends RootJsonFormat[StreamType] {

    def read(json: JsValue): StreamType = json match {
      case JsString("Notification") => Notification
      case JsString("History")      => History
      case JsString("CurrentState") => CurrentState
      case JsString("Telemetry")    => Telemetry
      case _ => {
        import scala.reflect.runtime.{universe => ru}
        val tpe = ru.typeOf[StreamType]
        val clazz = tpe.typeSymbol.asClass
        throw new DeserializationException(
          s"expected a streamType of ${clazz.knownDirectSubclasses}, but got $json"
        )
      }
    }

    def write(obj: StreamType): JsValue = {
      JsString(obj.toString)
    }
  }

  implicit val genericErrorFormat = jsonFormat2(GenericError)

  implicit val topicCreationMetadataFormat = jsonFormat8(TopicMetadataRequest)

  implicit val genericSchemaFormat = jsonFormat2(GenericSchema)

}

case class GenericError(status: Int, errorMessage: String)

case class TopicMetadataRequest(
    schema: JsObject,
    streamType: StreamType,
    derived: Boolean,
    deprecated: Option[Boolean],
    dataClassification: String,
    contact: String,
    additionalDocumentation: Option[String],
    notes: Option[String]
)

case class GenericSchema(name: String, namespace: String) {
  def subject = s"$namespace.$name"
}

sealed trait StreamType
case object Notification extends StreamType
case object CurrentState extends StreamType
case object History extends StreamType
case object Telemetry extends StreamType 
Example 5
Source File: IdentifyFeyActors.scala    From incubator-retired-iota   with Apache License 2.0 5 votes vote down vote up
package org.apache.iota.fey

import akka.actor.{Actor, ActorIdentity, ActorLogging, ActorPath, Identify}
import akka.routing.{ActorRefRoutee, GetRoutees, Routees}
import play.api.libs.json._

import scala.collection.mutable.HashSet

protected class IdentifyFeyActors extends Actor with ActorLogging {

  import IdentifyFeyActors._

  override def receive: Receive = {
    case IDENTIFY_TREE(startPath) =>
      log.info("Current Actors in system:")
      actorsPath = HashSet.empty
      rootPath = startPath
      log.info(startPath)
      self ! ActorPath.fromString(startPath)

    case path: ActorPath =>
      context.actorSelection(path / "*") ! Identify(())
      context.actorSelection(path / "*") ! GetRoutees

    case ActorIdentity(_, Some(ref)) =>
      actorsPath.add(ref.path.toString)
      log.info(ref.path.toString)
      self ! ref.path

    case routees:Routees =>
      routees.routees
        .map(_.asInstanceOf[ActorRefRoutee])
        .foreach(routee => {
          log.info(routee.ref.path.toString)
          actorsPath.add(routee.ref.path.toString)
        })

    case _ =>
  }
}

protected object IdentifyFeyActors{

  
  def generateTreeJson(): String = {
    val trie = new Trie("FEY-MANAGEMENT-SYSTEM")
    actorsPath.map(_.replace("user/","")).foreach(trie.append(_))

    Json.stringify(trie.print)
  }

  //Static HTML content from d3
  val html = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/d3Tree.html"), "UTF-8")
    .getLines()
    .mkString("\n")

  def getHTMLTree(json: String): String = {
   html.replace("$MYJSONHIERARCHY", json)
  }

} 
Example 6
Source File: WorkerStateReporter.scala    From maha   with Apache License 2.0 5 votes vote down vote up
// Copyright 2018, Yahoo Inc.
// Licensed under the terms of the Apache License 2.0. Please see LICENSE file in project root for terms.

package com.yahoo.maha.worker.state

import java.io.File

import akka.actor.{Actor, ActorPath, ActorSystem, Props}
import com.typesafe.config.{Config, ConfigFactory}
import com.yahoo.maha.core.Engine
import com.yahoo.maha.worker.state.actor._
import grizzled.slf4j.Logging


object WorkerStateReporter extends Logging {

  // Use a bounded mailbox to prevent memory leaks in the rare case when jobs get piled up to be processed by the actor
  val defaultConfig: Config = ConfigFactory.parseString(
    """
      |akka.actor.nonblocking_bounded_mailbox {
      |  mailbox-type = akka.dispatch.NonBlockingBoundedMailbox
      |  mailbox-capacity = 10000
      |}
      |akka {
      |  loggers = ["akka.event.slf4j.Slf4jLogger"]
      |  loglevel = "INFO"
      |}
      |""".stripMargin)

}



case class WorkerStateReporter(akkaConf: String) extends Logging {

  val config: Config = {
    val file = new File(akkaConf)
    if(file.exists() && file.canRead) {
      info(s"Using akka conf file : ${file.getAbsolutePath}")
      ConfigFactory.parseFile(file)
    } else {
      info("Using default akka config")
      WorkerStateReporter.defaultConfig
    }
  }
  val system = ActorSystem("maha-workers", config)
  lazy val workerStateActorPath: ActorPath = {
    val actorConfig = WorkerStateActorConfig()
    val props: Props = Props(classOf[WorkerStateActor], actorConfig).withMailbox("akka.actor.nonblocking_bounded_mailbox")
    val path = system.actorOf(props, actorConfig.name).path
    info(s"Created WorkerStateActor: $path")
    path
  }

  def jobStarted(executionType: ExecutionType, jobId: Long, engine: Engine, cost: Long, estimatedRows: Long, userId: String): Unit = {
    sendMessage(JobStarted(executionType, jobId, engine, cost, estimatedRows, userId))
  }

  def jobEnded(executionType: ExecutionType, jobId: Long, engine: Engine, cost: Long, estimatedRows: Long, userId: String): Unit = {
    sendMessage(JobEnded(executionType, jobId, engine, cost, estimatedRows, userId))
  }

  def sendMessage(actorMessage:WorkerStateActorMessage) = {
    try {
      system.actorSelection(workerStateActorPath).tell(actorMessage, Actor.noSender)
    } catch {
      case t: Throwable =>
        warn(s"Failed to send $actorMessage message to WorkerStateActor", t)
    }
  }
} 
Example 7
Source File: RoutedActorRef.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package akka.routing

import akka.ConfigurationException
import akka.actor.ActorPath
import akka.actor.ActorSystemImpl
import akka.actor.Cell
import akka.actor.InternalActorRef
import akka.actor.Props
import akka.actor.RepointableActorRef
import akka.actor.UnstartedCell
import akka.dispatch.BalancingDispatcher
import akka.dispatch.MailboxType
import akka.dispatch.MessageDispatcher


private[akka] class RoutedActorRef(
  _system: ActorSystemImpl,
  _routerProps: Props,
  _routerDispatcher: MessageDispatcher,
  _routerMailbox: MailboxType,
  _routeeProps: Props,
  _supervisor: InternalActorRef,
  _path: ActorPath)
  extends RepointableActorRef(_system, _routerProps, _routerDispatcher, _routerMailbox, _supervisor, _path) {

  // verify that a BalancingDispatcher is not used with a Router
  if (_routerProps.routerConfig != NoRouter && _routerDispatcher.isInstanceOf[BalancingDispatcher]) {
    throw new ConfigurationException(
      "Configuration for " + this +
        " is invalid - you can not use a 'BalancingDispatcher' as a Router's dispatcher, you can however use it for the routees.")
  } else _routerProps.routerConfig.verifyConfig(_path)

  override def newCell(old: UnstartedCell): Cell = {
    val cell = props.routerConfig match {
      case pool: Pool if pool.resizer.isDefined ⇒
        new ResizablePoolCell(system, this, props, dispatcher, _routeeProps, supervisor, pool)
      case _ ⇒
        new RoutedActorCell(system, this, props, dispatcher, _routeeProps, supervisor)
    }
    cell.init(sendSupervise = false, mailboxType)
  }

} 
Example 8
Source File: LogkafkaViewCacheActor.scala    From CMAK   with Apache License 2.0 5 votes vote down vote up
package kafka.manager.logkafka

import akka.actor.{ActorPath, Cancellable}
import kafka.manager.model.{ClusterContext, ActorModel}
import ActorModel._
import kafka.manager.base.{LongRunningPoolActor, LongRunningPoolConfig}
import kafka.manager.features.KMLogKafkaFeature

import scala.concurrent.duration._
import scala.util.Try


case class LogkafkaViewCacheActorConfig(logkafkaStateActorPath: ActorPath, 
                                      clusterContext: ClusterContext,
                                      longRunningPoolConfig: LongRunningPoolConfig, 
                                      updatePeriod: FiniteDuration = 10 seconds)
class LogkafkaViewCacheActor(config: LogkafkaViewCacheActorConfig) extends LongRunningPoolActor {
  
  private[this] val ZERO = BigDecimal(0)

  private[this] var cancellable : Option[Cancellable] = None

  private[this] var logkafkaIdentities : Map[String, LogkafkaIdentity] = Map.empty

  private[this] var logkafkaConfigsOption : Option[LogkafkaConfigs] = None

  private[this] var logkafkaClientsOption : Option[LogkafkaClients] = None

  override def preStart() = {
    if (config.clusterContext.clusterFeatures.features(KMLogKafkaFeature)) {
      log.info("Started actor %s".format(self.path))
      log.info("Scheduling updater for %s".format(config.updatePeriod))
      cancellable = Some(
        context.system.scheduler.schedule(0 seconds,
          config.updatePeriod,
          self,
          LKVForceUpdate)(context.system.dispatcher,self)
      )
    }
  }

  @scala.throws[Exception](classOf[Exception])
  override def postStop(): Unit = {
    log.info("Stopped actor %s".format(self.path))
    log.info("Cancelling updater...")
    Try(cancellable.map(_.cancel()))
    super.postStop()
  }

  override protected def longRunningPoolConfig: LongRunningPoolConfig = config.longRunningPoolConfig

  override protected def longRunningQueueFull(): Unit = {
    log.error("Long running pool queue full, skipping!")
  }

  override def processActorRequest(request: ActorRequest): Unit = {
    request match {
      case LKVForceUpdate =>
        log.info("Updating logkafka view...")
        //ask for logkafka configs 
        val lastLogkafkaConfigsUpdateMillisOption: Option[Long] = logkafkaConfigsOption.map(_.lastUpdateMillis)
        context.actorSelection(config.logkafkaStateActorPath).tell(LKSGetAllLogkafkaConfigs(lastLogkafkaConfigsUpdateMillisOption), self)
        //ask for logkafka clients
        val lastLogkafkaClientsUpdateMillisOption: Option[Long] = logkafkaClientsOption.map(_.lastUpdateMillis)
        context.actorSelection(config.logkafkaStateActorPath).tell(LKSGetAllLogkafkaClients(lastLogkafkaClientsUpdateMillisOption), self)

      case LKVGetLogkafkaIdentities =>
        sender ! logkafkaIdentities
        
      case any: Any => log.warning("bvca : processActorRequest : Received unknown message: {}", any)
    }
  }

  override def processActorResponse(response: ActorResponse): Unit = {
    response match {
      case lcg: LogkafkaConfigs =>
        logkafkaConfigsOption = Some(lcg)
        updateView()

      case lct: LogkafkaClients =>
        logkafkaClientsOption = Some(lct)
        updateView()

      case any: Any => log.warning("bvca : processActorResponse : Received unknown message: {}", any)
    }
  }

  private[this] def updateView(): Unit = {
    for {
      logkafkaConfigs <- logkafkaConfigsOption
      logkafkaClients <- logkafkaClientsOption
    } {
      val lcgMap = Map(logkafkaConfigs.configs map { a => a.logkafka_id -> a }: _*)
      val lctMap = Map(logkafkaClients.clients map { a => a.logkafka_id -> a }: _*)
      logkafkaIdentities = lcgMap.map (kv =>
        kv._1 -> LogkafkaIdentity.from(kv._1, Some(kv._2), lctMap.get(kv._1)))
    }
  }
} 
Example 9
Source File: AkkaSuite.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.module.akka

import scala.concurrent.duration._

import akka.actor.ActorPath
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pureconfig.generic.auto._
import pureconfig.syntax._

class AkkaSuite extends AnyFlatSpec with Matchers with EitherValues {

  case class TimeoutConf(timeout: Timeout)
  case class PathConf(path: ActorPath)

  it should "be able to read a config with a Timeout" in {
    val expected = 5.seconds
    val config = ConfigFactory.parseString(s"""{ timeout: $expected }""")
    config.to[TimeoutConf].right.value shouldEqual TimeoutConf(Timeout(expected))
  }

  it should "load a valid ActorPath" in {
    val str = "akka://my-sys/user/service-a/worker1"
    val expected = ActorPath.fromString(str)
    val config = ConfigFactory.parseString(s"""{ path: "$str" }""")
    config.to[PathConf].right.value shouldEqual PathConf(expected)
  }

  it should "not load invalid ActorPath" in {
    val config = ConfigFactory.parseString("""{ path: "this is this the path you're looking for" }""")
    config.to[PathConf] should be('left)
  }
} 
Example 10
Source File: ActorRefPathSelection.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
import akka.actor.{Actor, ActorPath, ActorRef, ActorSystem, PoisonPill, Props}

case object Shutdown

class SimpleActor extends Actor {
  def receive = {
    case Shutdown => context.stop(self)
  }
}

object ActorRefActorPathApp extends App {
  val actorSystem = ActorSystem("SimpleSystem")
  val actorRef1:ActorRef = actorSystem.actorOf(Props[SimpleActor],"SimpleActor")
  println(s"Actor Reference1 = ${actorRef1}")
  println(s"Actor Path1 = ${actorRef1.path}")
  val actorPath:ActorPath = actorSystem / "SimpleActor"
  println(s"Actor Path = ${actorPath}")

  actorRef1 ! Shutdown

  Thread.sleep(1000)

  val actorRef2:ActorRef = actorSystem.actorOf(Props[SimpleActor],"SimpleActor")
  println(s"Actor Reference2 = ${actorRef2}")
  println(s"Actor Path2 = ${actorRef2.path}")

  actorSystem.terminate
} 
Example 11
Source File: ResultProcessor.scala    From akka-iot-mqtt-v2   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package akkaiot

import akka.actor.{ Props, ActorRef, Actor, ActorLogging, ActorPath }
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator

object ResultProcessor {
  def props(iotPath: ActorPath): Props = Props(new ResultProcessor(iotPath))
}

class ResultProcessor(iotPath: ActorPath) extends Actor with ActorLogging {

  val mediator = DistributedPubSub(context.system).mediator
  mediator ! DistributedPubSubMediator.Subscribe(Master.ResultsTopic, self)

  def receive = {
    case _: DistributedPubSubMediator.SubscribeAck =>
    case result: WorkResult =>
      log.info("Result Processor -> Got work result: {}-{} | State {} | Setting {}", result.deviceType, result.deviceId, result.nextState, result.nextSetting)

      context.actorSelection(iotPath) ! result
      log.info("Result Processor -> Sent work result for {}-{} to IoT Manager", result.deviceType, result.deviceId)
  }
} 
Example 12
Source File: CoordinatorZk.scala    From affinity   with Apache License 2.0 5 votes vote down vote up
package io.amient.affinity.core.cluster

import java.util

import akka.actor.{ActorPath, ActorSystem}
import com.typesafe.config.Config
import io.amient.affinity.core.cluster.Coordinator.CoordinatorConf
import io.amient.affinity.core.cluster.CoordinatorZk.CoordinatorZkConf
import io.amient.affinity.core.config.CfgStruct
import io.amient.affinity.core.util.{ZkClients, ZkConf}
import org.I0Itec.zkclient.IZkChildListener
import org.apache.zookeeper.CreateMode

import scala.collection.JavaConverters._

object CoordinatorZk {

  object CoordinatorZkConf extends CoordinatorZkConf {
    override def apply(config: Config) = new CoordinatorZkConf()(config)
  }

  class CoordinatorZkConf extends CfgStruct[CoordinatorZkConf](classOf[CoordinatorConf]) {
    val ZooKeeper = struct("zookeeper", new ZkConf, true)
    val ZkRoot = string("zookeeper.root", "/affinity")
      .doc("znode under which coordination data between affinity nodes will be registered")
  }

}

class CoordinatorZk(system: ActorSystem, group: String, _conf: CoordinatorConf) extends Coordinator(system, group) {
  val conf = CoordinatorZkConf(_conf)
  val zkConf = conf.ZooKeeper()
  val zkRoot = conf.ZkRoot()
  val groupRoot = s"$zkRoot/${system.name}/$group/online"
  val peersRoot = s"$zkRoot/${system.name}/$group/peers"

  private val zk = ZkClients.get(zkConf)

  if (!zk.exists(groupRoot)) zk.createPersistent(groupRoot, true)

  updateChildren(zk.subscribeChildChanges(groupRoot, new IZkChildListener() {
    override def handleChildChange(parentPath: String, children: util.List[String]): Unit = {
      updateChildren(children)
    }
  }))

  override def register(actorPath: ActorPath): String = {
    zk.create(s"$groupRoot/", actorPath.toString(), CreateMode.EPHEMERAL_SEQUENTIAL)
  }

  override def unregister(handle: String) = zk.delete(handle)

  override def close(): Unit = if (!closed.get) {
    super.close()
    ZkClients.close(zk);
  }

  private def listAsIndexedSeq(list: util.List[String]) = list.asScala.toIndexedSeq

  private def updateChildren(children: util.List[String]): Unit = {
    if (children != null) {
      val newHandles = listAsIndexedSeq(children).map(id => s"$groupRoot/$id")
      val newState = newHandles.map(handle => (handle, zk.readData[String](handle))).toMap
      updateGroup(newState)
    }
  }

  override def registerPeer(akkaAddress: String, knownZid: Option[String]): String = {

    if (!zk.exists(peersRoot)) zk.createPersistent(peersRoot, true)
    val nodes = zk.getChildren(peersRoot).asScala.map(i => (i, zk.readData[String](s"$peersRoot/$i")))
    val zid: String = knownZid.flatMap { id =>
      nodes.find(_._1 == id) match {
        case Some((_, prevAkkaAddress)) if (prevAkkaAddress == akkaAddress) => Some(id)
        case Some(_) => zk.writeData(s"$peersRoot/$id", akkaAddress); Some(id)
        case None => None
      }
    } getOrElse {
      nodes.find(_._2 == akkaAddress) match {
        case Some((id, _)) => id
        case None => zk.create(s"$peersRoot/", akkaAddress, CreateMode.PERSISTENT_SEQUENTIAL).substring(peersRoot.length+1)
      }
    }

    def update(zids: util.List[String]) = updatePeers(zids.asScala.toList)
    try zid finally update(zk.subscribeChildChanges(peersRoot, new IZkChildListener() {
      override def handleChildChange(parentPath: String, zids: util.List[String]): Unit = update(zids)
    }))
  }

} 
Example 13
Source File: RegionSpec.scala    From affinity   with Apache License 2.0 5 votes vote down vote up
package io.amient.affinity.core.actor

import akka.actor.{ActorPath, ActorSystem, PoisonPill, Props}
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import io.amient.affinity.AffinityActorSystem
import io.amient.affinity.core.cluster.Coordinator
import org.scalatest.concurrent.{Eventually, IntegrationPatience}
import org.scalatest.{Matchers, WordSpecLike}

import scala.concurrent.duration._
import scala.language.postfixOps


class RegionSpec extends WordSpecLike with Matchers with Eventually with IntegrationPatience {

  val system: ActorSystem = AffinityActorSystem.create(ConfigFactory.load("regionspec"))

  val testPartition = Props(new Partition {
    override def preStart(): Unit = {
      Thread.sleep(100)
      super.preStart()
    }

    override def handle: Receive = {
      case _: IllegalStateException => context.stop(self)
      case _ =>
    }
  })


  "A Region Actor" must {
    "must keep Coordinator Updated during partition failure & restart scenario" in {
      //      val zk = new EmbeddedZookeperServer {}
      try {
        val coordinator = Coordinator.create(system, "region")
        try {
          val d = 1 second
          implicit val timeout = Timeout(d)

          val region = system.actorOf(Props(new Container("region") {
            val partitions = List(0, 1, 2, 3)
            for (partition <- partitions) {
              context.actorOf(testPartition, name = partition.toString)
            }
          }), name = "region")
          eventually {
            coordinator.members.size should be(4)
          }

          //first stop Partition explicitly - it shouldn't be restarted
          import system.dispatcher
          system.actorSelection(ActorPath.fromString(coordinator.members.head._2)).resolveOne.foreach {
            case actorRef => system.stop(actorRef)
          }
          eventually {
            coordinator.members.size should be(3)
          }

          //now simulate error in one of the partitions
          val partitionToFail = coordinator.members.head._2
          system.actorSelection(ActorPath.fromString(partitionToFail)).resolveOne.foreach {
            case actorRef => actorRef ! new IllegalStateException("Exception expected by the Test")
          }
          eventually {
            coordinator.members.size should be(2)
          }
          eventually {
            coordinator.members should not contain (partitionToFail)
          }

          region ! PoisonPill

        } finally {
          coordinator.close
        }
      } finally {
        //        zk.close()
      }
    }
  }

}

class RegionSpecPartition extends Partition {
  override def preStart(): Unit = {
    Thread.sleep(100)
    super.preStart()
  }

  override def handle: Receive = {
    case _: IllegalStateException => context.stop(self)
    case _ =>
  }
} 
Example 14
Source File: ActorSystems.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.events

import akka.actor.{ActorPath, ActorRef, ActorSystem}
import akka.viz.ActorCellInstrumentation

import scala.collection.breakOut
import scala.ref.WeakReference
import scala.util.Try

object ActorSystems {

  private[this] val systemReferences = scala.collection.mutable.Map[String, WeakReference[ActorSystem]]()

  def systems: scala.collection.immutable.Map[String, ActorSystem] = systemReferences.flatMap {
    case (name, ref) => ref.get.map {
      system => name -> system
    }
  }(breakOut)

  def registerSystem(system: ActorSystem): Unit = {
    systemReferences.update(system.name, WeakReference(system))
  }

  def tell(path: String, message: Any): Unit = {
    Try {
      val actorPath = ActorPath.fromString(path)
      systems.get(actorPath.address.system).foreach {
        system =>
          system.actorSelection(actorPath).tell(message, ActorRef.noSender)
      }
    }
  }

  def refreshActorState(path: String): Unit = {
    tell(path, ActorCellInstrumentation.RefreshInternalStateMsg)
  }

} 
Example 15
Source File: RareBooks.scala    From reactive-application-development-scala   with Apache License 2.0 5 votes vote down vote up
package com.rarebooks.library

import akka.actor.{Actor, ActorLogging, ActorPath, Address, OneForOneStrategy, Props, RootActorPath, Stash, SupervisorStrategy}
import akka.routing.{ActorRefRoutee, RoundRobinRoutingLogic, Router}

import scala.concurrent.duration.{Duration, FiniteDuration, MILLISECONDS => Millis}

object RareBooks {

  case object Close
  case object Open
  case object Report

//  val name: String =
//    "rare-books"
//
//  def pathFor(address: Address): ActorPath =
//    RootActorPath(address) / "user" / name
  
  def props: Props =
    Props(new RareBooks)
}

class RareBooks extends Actor with ActorLogging with Stash {

  import context.dispatcher
  import RareBooks._
  import LibraryProtocol._

  override val supervisorStrategy: SupervisorStrategy = {
    val decider: SupervisorStrategy.Decider = {
      case Librarian.ComplainException(complain, customer) =>
        customer ! Credit()
        log.info(s"RareBooks sent customer $customer a credit")
        SupervisorStrategy.Restart
    }
    OneForOneStrategy()(decider orElse super.supervisorStrategy.decider)
  }

  private val openDuration: FiniteDuration =
    Duration(context.system.settings.config.getDuration("rare-books.open-duration", Millis), Millis)

  private val closeDuration: FiniteDuration =
    Duration(context.system.settings.config.getDuration("rare-books.close-duration", Millis), Millis)

  private val nbrOfLibrarians: Int = context.system.settings.config getInt "rare-books.nbr-of-librarians"

  private val findBookDuration: FiniteDuration =
    Duration(context.system.settings.config.getDuration("rare-books.librarian.find-book-duration", Millis), Millis)

  private val maxComplainCount: Int = context.system.settings.config getInt "rare-books.librarian.max-complain-count"

  var requestsToday: Int = 0
  var totalRequests: Int = 0

  var router: Router = createLibrarian()

  context.system.scheduler.scheduleOnce(openDuration, self, Close)

  
  protected def createLibrarian(): Router = {
    var cnt: Int = 0
    val routees: Vector[ActorRefRoutee] = Vector.fill(nbrOfLibrarians) {
      val r = context.actorOf(Librarian.props(findBookDuration, maxComplainCount), s"librarian-$cnt")
      cnt += 1
      ActorRefRoutee(r)
    }
    Router(RoundRobinRoutingLogic(), routees)
  }
} 
Example 16
Source File: AkkaArbitraryInstances.scala    From lithium   with Apache License 2.0 5 votes vote down vote up
package akka.cluster.swissborg

import akka.actor.{ActorPath, Address, ChildActorPath, RootActorPath}
import akka.cluster.{Member, UniqueAddress, Reachability => _}
import com.swissborg.lithium.instances.ArbitraryTestInstances._
import org.scalacheck.Arbitrary._
import org.scalacheck.{Arbitrary, Gen}
import shapeless.tag
import shapeless.tag.@@


object AkkaArbitraryInstances {
  sealed trait JoiningTag
  type JoiningMember = Member @@ JoiningTag

  implicit val arbJoiningMember: Arbitrary[JoiningMember] = Arbitrary {
    for {
      uniqueAddress <- arbitrary[UniqueAddress]
    } yield tag[JoiningTag][Member](Member(uniqueAddress, Set("dc-datacenter")))
  }

  implicit val arbRootActorPath: Arbitrary[RootActorPath] = Arbitrary(arbitrary[Address].map(RootActorPath(_)))

  def arbChildActorPath(parent: ActorPath): Arbitrary[ChildActorPath] =
    Arbitrary(for {
      c   <- Gen.alphaChar
      cs  <- Gen.alphaStr
      uid <- Gen.chooseNum(0, Int.MaxValue)
      name = s"$c$cs"
    } yield new ChildActorPath(parent, name, uid))

  def arbActorPath(depth: Int, parent: ActorPath): Arbitrary[ActorPath] =
    Arbitrary(
      if (depth <= 0) Gen.const(parent)
      else arbChildActorPath(parent).arbitrary.flatMap(arbActorPath(depth - 1, _).arbitrary)
    )

  implicit val arbActorPath0: Arbitrary[ActorPath] = Arbitrary(for {
    depth  <- Gen.chooseNum(0, 10)
    parent <- arbitrary[RootActorPath]
    path   <- arbActorPath(depth, parent).arbitrary
  } yield path)
}