How do I get exception details from an Akka Supervisor? - scala

I'm testing how a new Actor I'm working on handles unexpected messages. I'd like to assert that it throws a GibberishException in these cases. Here's the test and the implementation so far:
Test:
"""throw a GibberishException for unrecognized messages""" in {
//define a service that creates gibberish-speaking repositories
val stubs = new svcStub(
actorOf(new Actor{
def receive = { case _ => {
self.channel ! "you're savage with the cabbage"
}
}
})
)
val model = actorOf(new HomeModel(stubs.svc,stubs.store))
val supervisor = Supervisor(
SupervisorConfig(
OneForOneStrategy(List(classOf[Exception]), 3, 1000),
Supervise(model,Permanent) :: Nil
)
)
try{
intercept[GibberishException] {
supervisor.start
model !! "plan"
}
} finally {
supervisor.shutdown
}
stubs.store.plan should equal (null)
stubs.svcIsOpen should be (false)
}
Implementation:
class HomeModel(service: PlanService, store: HomeStore)
extends Actor {
private val loaderRepo = service.getRepo()
private var view: Channel[Any] = null
override def postStop() = {
service.close()
}
def receive = {
case "plan" => {
view=self.channel
loaderRepo ! LoadRequest()
}
case p: Plan => {
store.plan=p
view ! store.plan
}
case _ => throw new GibberishException(_)
}
}
However, when I run the test, the exception details get to the Supervisor I established, but I don't know how to do anything with them (like log them or test their type). I'd like to be able to get the exception details here from the supervisor so i can rethrow and intercept them in my test. Outside of a test method, I could imagine this being useful if you wanted to report the nature of an exception in the UI of a running app. Is there a way to get this from the Supervisor when it happens?

Change the OneForOneStrategy to only handle GibberishException, should solve it.

Related

Why does this akka-http route test never complete successfully?

I've a simple route and some tests that success individually, but collectively fail with timeout. Any idea why?
val route = (requestHandler: ActorRef ## Web) => {
get {
pathPrefix("apps") {
pathEndOrSingleSlash {
completeWith(implicitly[ToEntityMarshaller[List[String]]]) { callback =>
requestHandler ! GetAppsRequest(callback)
}
} ~ path("stats") {
completeWith(implicitly[ToEntityMarshaller[List[Stats]]]) { callback =>
requestHandler ! GetStatsRequest(callback)
}
}
} ~ path("apps" / Segment / "stats") { app =>
completeWith(implicitly[ToEntityMarshaller[Stats]]) { callback =>
requestHandler ! GetStatsForOneRequest(app, callback)
}
}
}
}
and tests:
val testProbe = TestProbe()
val testProbeActor = testProbe.ref
.taggedWith[Web]
val timeout = 1.minute
"Route" should "respond to get apps request" in {
implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
Get("/apps") ~> route(testProbeActor) ~> check {
testProbe.receiveOne(timeout) match {
case GetAppsRequest(callback) => {
callback(k8SProperties.apps)
}
}
entityAs[List[String]] should contain("test")
}
testProbe.expectNoMessage(timeout)
}
it should "respond to get stats request for all apps" in {
implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
val app = "test"
Get("/apps/stats") ~> route(testProbeActor) ~> check {
testProbe.receiveOne(timeout) match {
case GetStatsRequest(callback) => {
callback(List(Stats(app, ChronoUnit.SECONDS, Nil)))
}
case other => fail(s"Unexpected message $other.")
}
entityAs[List[Stats]].size shouldBe (1)
entityAs[List[Stats]].head.app shouldBe (app)
}
testProbe.expectNoMessage(timeout)
}
it should "respond to get stats request for one app" in {
implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
val app = "test"
Get(s"/apps/$app/stats") ~> route(testProbeActor) ~> check {
testProbe.receiveOne(timeout) match {
case GetStatsForOneRequest(app, callback) => {
callback(Stats(app, ChronoUnit.SECONDS, Nil))
}
case other => fail(s"Unexpected message $other.")
}
entityAs[Stats].app shouldBe (app)
}
testProbe.expectNoMessage(timeout)
}
Edit:
Opened https://github.com/akka/akka-http/issues/1615
The problem is that you are using a single TestProbe across all three tests. That TestProbe is a single actor and is therefore receiving messages from all three tests. If you simply move your test probe creation and config inside the test bodies, it should work as you expect; specifically these two lines:
val testProbe = TestProbe()
val testProbeActor = testProbe.ref
.taggedWith[Web]
Working code, thanks to me.
"Routes" should "respond to get apps request" in {
testProbe.setAutoPilot((_: ActorRef, msg: Any) => {
msg match {
case GetAppsRequest(callback) => callback(List("test")); TestActor.KeepRunning
case _ => TestActor.NoAutoPilot
}
})
Get("/apps") ~> handler ~> check {
entityAs[List[String]] should contain("test")
}
}
Putting TestProbe inside check hangs forever probably because it creates a deadlock; test waits for callback to be called, and callback isn't called until the body is executed.
Using autopilot sets up an "expectation" that can be fulfilled later thus avoiding the deadlock.

Akka actor system with HTTP interface

I'm trying to create an Akka system which would among other things respond to HTTP requests. I created a few actors who exchange messages fine. I can also use akka-http to respond to HTTP requests. The problem is in connecting those two parts.
TL;DR: How to talk to Akka actors during akka-http request processing?
I created a single actor responsible for bringing up the HTTP system:
class HttpActor extends Actor with ActorLogging {
/* implicits elided */
private def initHttp() = {
val route: Route = path("status") { get { complete { "OK" } } }
Http()(context.system).bindAndHandle(route, "localhost", 8080)
}
private var bound: Option[Future[Http.ServerBinding]] = None
override def receive = {
case HttpActor.Init =>
bound match {
case Some(x) => log.warning("Http already bootstrapping")
case None =>
bound = Some(initHttp(watcher))
}
}
}
object HttpActor {
case object Init
}
As you may see, the actor creates the akka-http service on the first message it receives (no reason, really, it could do it in the constructor as well).
Now, during the request processing I need to communicate with some other actors, and I can't get it working.
My approach:
private def initInteractiveHttp() = {
val route: Route = path("status") {
get { complete { "OK" } }
} ~ path("ask") {
get { complete {
// Here are the interesting two lines:
val otherActorResponse = someOtherActor ? SomeMessage
otherActorResponse.mapTo[String]
} }
Http()(context.system).bindAndHandle(route, "localhost", 8080)
}
This would send a SomeMessage to someOtherActor and wait for response prior to completing the Request-Response cycle. As I understand, however, that messages would be sent from the root HttpActor, which is bad and leads nowhere in terms of scalability. Ideally I would create a distinct instance of specialized actor for every request, but this fails due to akka-http typing. Consider the following example:
class DisposableActor(httpContext: HttpContext) {
override def preStart() = {
// ... send some questions to other actors
}
override def receive = {
case GotAllData(x) => httpContext.complete(x)
}
}
class HttpActorWithDisposables {
// there is a `context` value in scope - we're an actor, after all
private def initHttpWithDisposableActors() = {
val route: Route = path("status") {
get { complete { "OK" } }
} ~ path("ask") {
get { httpContext =>
val props = Props(new DisposableActor(httpContext))
val disposableActor = context.actorOf(props, "disposable-actor-name")
// I have nothing to return here
}
}
Http()(context.system).bindAndHandle(route, "localhost", 8080)
}
With this approach, I can force the DisposableActor to call httpContext.complete at some point of time. This should correctly end the Request-Response processing cycle. The Route DSL, however, requires to return a valid response (or Future) inside the get block, so this approach doesn't work.
Your first approach is quite alright, actually.
The ask pattern creates a lightweight, disposable actor for you that waits on the result (non-blockingly) to complete the future. It basically does all the things you want to replicate with the DisposableActor and your main HttpActor is not stressed by this.
If you still want to use a different actor, there is completeWith:
completeWith(instanceOf[String]) { complete =>
// complete is of type String => Unit
val props = Props(new DisposableActor(complete))
val disposableActor = context.actorOf(props, "disposable-actor-name")
// completeWith expects you to return unit
}
And in you actor, call the complete function when you have the result
class DisposableActor(complete: String => Unit) {
override def receive = {
case GotAllData(x) =>
complete(x)
context stop self // don't for get to stop the actor
}
}

how to perform supervision in akka

I have two actors one is parent and one is child ,The child actor is responsible for fetching data from MongoDB against an given id and reply back the data to the calling actor which is a parent in my case ,Now i want to apply supervision in my child actor i know how to perform supervision strategy but how to do it in my code that's confusing me
i am catching exception in my try/catch block so that every type of exception will be caught but then i am stuck on the point how to app,y supervision as i don't know exactly what exception my code will throw in future here is my code please help me
ReadOnlyAdminQueryActor.scala(Patent Actor)
class ReadOnlyAdminQueryActor extends Actor{
val log = LoggerFactory.getLogger("controller")
case ReadOnlyAdminReadByID(idList)=>
var RetunedLists = new MutableList[ReadOnlyAdmin]()
RetunedLists= readById(idList)
sender ! RetunedLists //return list of ReadOnlyAdmin objects to the calling actor (matched uuid results)
def readById(idList:MutableList[Int]):MutableList[ReadOnlyAdmin]= {
var connection=MongoFactory.getConnection
var collection=MongoFactory.getCollection(connection, "readOnlyAdmin")
var RetunedList = new MutableList[ReadOnlyAdmin]()
var id:Int=0
var email:String=""
var SecondryEmail:Option[String]=None
var FirstName:String=""
var LastName:String=""
var userStatus:String=""
log.info("readOnlyAdmin query class data method readByID")
for(Id<-idList){
val q=QueryBuilder.start("_id").is(Id)
val cursor=collection.find(q.get)
var obj=new BasicDBObject
try {
while(cursor.hasNext)
{
obj=cursor.next().asInstanceOf[BasicDBObject]
id=obj.getString("_id").toInt
email=obj.getString("Email")
SecondryEmail=Option(obj.getString("SecondryEmail"))
FirstName=obj.getString("FirstName")
LastName=obj.getString("LastName")
userStatus=obj.getString("UserStatus")
val readOnlyAdmin=new ReadOnlyAdmin(id,FirstName, LastName, email, SecondryEmail ,"",UserStatus.withName(userStatus))
RetunedList+=readOnlyAdmin //adding objects in a list
}//end of while
}//end of try
catch
{
case e: Exception => log.error("printStackTrace"+e.printStackTrace)
}
finally{
cursor.close()
MongoFactory.closeConnection(connection)
}
}//end for loop
RetunedList
}
}
ReadOnlyAdminReadMongoActor.scala (Child Actor)
class ReadOnlyAdminReadMongoActor extends Actor{
val log = LoggerFactory.getLogger("controller")
val ReadOnlyAdminQueryActor=context.actorOf(Props[ReadOnlyAdminQueryActor].withDispatcher("akka.actor.readOnlyAdminReadMongoActor-dispatcher"), name = "ReadOnlyAdminQueryActor")
case ReadOnlyAdminReadFromMongoById(readOnlyAdmin,idList)=>
var RetunedLists = new MutableList[ReadOnlyAdmin]()
implicit val timeout = Timeout(10 seconds)//wait for 10 seconds
override val supervisorStrategy: SupervisorStrategy = {
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 10 seconds) {
case x: Exception => ???
}
}
val future:Future[MutableList[ReadOnlyAdmin]] = ask(ReadOnlyAdminQueryActor,ReadOnlyAdminReadByID(idList)).mapTo[MutableList[ReadOnlyAdmin]]
future.onComplete {
case Success(result)=>
RetunedLists=result
for(a<-RetunedLists)
{
log.info ("id is "+a.getUuid+"First name is "+a.getFirstName
+"Last name is "+a.getLastName+"Email is "+a.getEmail
+"secondry email is "+a.getSecondryEmail+"user status is "+a.getUserStatus)
}
case Failure(e)=>
log.error(" in failure")
log.error("printStackTrace"+e.printStackTrace)
}
object Test extends App{
val system = ActorSystem("TestSystem")
val readOnlyAdmin= new ReadOnlyAdmin
var uuidsList = new MutableList[Int]()
uuidsList+=123
val ReadOnlyAdminReadMongoActor=system.actorOf(Props[ReadOnlyAdminReadMongoActor].withDispatcher("akka.actor.readOnlyAdminReadMongoActor-dispatcher"), name = "ReadOnlyAdminReadMongoActor")
ReadOnlyAdminReadMongoActor ! ReadOnlyAdminReadFromMongoById(readOnlyAdmin,uuidsList)
}
how can i perform supervision in a correct way and how do i came to know which exception will be thrown in my child actor also Fortunately, Java libraries explicitly say what they're going to throw, and Scala libraries almost always throw very little or no even in IDE no information is shown when we hover the mouse on the code
please help me thanks in advance
The supervisor strategy belongs with the Parent, not the Child. The child should throw its exceptions and the parent determines how to handle the failure. In the code below, the Child actor will be restarted 3 times, then terminate:
class Parent extends Actor {
override def preStart(): Unit = {
self ! "Start Child"
}
def receive = {
case "Start Child" => context.actorOf(Props[Child])
}
override def supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3) {
case ex: Throwable => Restart
}
}
class Child extends Actor {
override def preStart() = {
self ! "Throw"
}
def receive = {
case "Throw" => throw new Exception("Throwing")
}
}

Akka supervisor actor do not handle exception when child actor throws an exception within onFailure of a future

I'm facing a problem with an Akka supervisor actor. When the child actor throws an exception within onFailure method of a future result, the supervisor does not handle the error (I want to restart the child in the case of a ConnectException).
I'm using Akka 2.3.7.
This is the supervisor actor:
class MobileUsersActor extends Actor with ActorLogging {
import Model.Implicits._
import Model.MobileNotifications
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 1 minute) {
case _: java.net.ConnectException => {
Logger.error("API connection error. Check your proxy configuration.")
Restart
}
}
def receive = {
case Start => findMobileUsers
}
private def findMobileUsers = {
val notis = MobileNotificationsRepository().find()
notis.map(invokePushSender)
}
private def invokePushSender(notis: List[MobileNotifications]) = {
notis.foreach { n =>
val pushSender = context.actorOf(PushSenderActor.props)
pushSender ! Send(n)
}
}
}
And this is the child actor:
class PushSenderActor extends Actor with ActorLogging {
def receive = {
case Send(noti) => {
val response = sendPushNotification(noti) onFailure {
case e: ConnectException => throw e
}
}
}
private def sendPushNotification(noti: MobileNotifications): Future[WSResponse] = {
val message = "Push notification message example"
Logger.info(s"Push Notification >> $message to users " + noti.users)
PushClient.sendNotification(message, noti.users)
}
}
I tried to notify sender with an akka.actor.Status.Failure(e) as is suggested here, but did not work, the exception keep unhandled by the supervisor.
As a workaround, I found this way to get it work:
class PushSenderActor extends Actor with ActorLogging {
def receive = {
case Send(noti) => {
val response = sendPushNotification(noti) onFailure {
case e: ConnectException => self ! APIConnectionError
}
}
case APIConnectionError => throw new ConnectException
}
private def sendPushNotification(noti: MobileNotifications): Future[WSResponse] = {
val message = "Push notification message example"
Logger.info(s"Push Notification >> $message to users " + noti.users)
PushClient.sendNotification(message, noti.users)
}
}
Is this an Akka bug or am I doing something wrong?
Thanks!
I think that the problem is that the exception thrown inside the Future doesn't belong to the same thread (potentially) as the one the Actor is running (someone more experienced can elaborate on this). So, the problem is that the exception thrown inside the Future body is "swallowed" and not propagated to the Actor. Since this is the case, the Actor doesn't fail and so there's no need to apply the supervision strategy. So, the first solution that comes to my mind is to wrap the exception inside the Future in some message, send it to yourself, and then throw it from inside the Actor context itself. This time, the Exception will be caught and the supervision strategy will be applied. Note, however, that unless you send the Send(noti) message again, you will not see the Exception happening since the Actor was restarted. All in all, the code would be like this:
class PushSenderActor extends Actor with ActorLogging {
case class SmthFailed(e: Exception)
def receive = {
case Send(noti) => {
val response = sendPushNotification(noti) onFailure {
case e: ConnectException => self ! SmthFailed(e) // send the exception to yourself
}
}
case SmthFailed(e) =>
throw e // this one will be caught by the supervisor
}
private def sendPushNotification(noti: MobileNotifications): Future[WSResponse] = {
val message = "Push notification message example"
Logger.info(s"Push Notification >> $message to users " + noti.users)
PushClient.sendNotification(message, noti.users)
}
}
Hope it helped.

Attach a callback to run after a scala spray server successfully sends a response

I want to do something like the following:
object SprayTest extends App with SimpleRoutingApp {
implicit val system = ActorSystem("my-system")
import system.dispatcher
startServer(interface = "0.0.0.0", port = 8080) {
post {
path("configNetwork") {
entity(as[Config]) { config =>
complete {
// has a response indicating "OK"
// also, restarts the network interface
handleConfig(config)
}
}
}
}
}
}
The problem is that handleConfig reinitializes the network interface, so remote hosts accessing this endpoint never receive their response.
One way to solve this is to run handleConfig in a separate thread and complete the request immediately with some response like "OK". This isn't a good solution however because it introduces a race condition between the future and the request completion (also, it always fails if the future is executed in a "same thread" execution context).
Therefore, an ideal solution would be to attach a callback to a "write response" future and perform the network re-initialization there, after the response has been successfully sent. Is there a way to achieve this in the spray framework?
As a simple example of the race condition, consider the following two examples:
object SprayTest extends App with SimpleRoutingApp {
implicit val system = ActorSystem("my-system")
import system.dispatcher
startServer(interface = "0.0.0.0", port = 8080) {
post {
path("configNetwork") {
entity(as[Config]) { config =>
ctx =>
ctx.complete("OK")
System.exit(0) // empty response due to this executing before response is sent
}
}
}
}
}
object SprayTest extends App with SimpleRoutingApp {
implicit val system = ActorSystem("my-system")
import system.dispatcher
startServer(interface = "0.0.0.0", port = 8080) {
post {
path("configNetwork") {
entity(as[Config]) { config =>
ctx =>
ctx.complete("OK")
Thread.sleep(1000)
System.exit(0) // response is "OK" because of the sleep
}
}
}
}
}
You can use the withAck method on HttpResponse to receive notification when the response is sent on the wire. Here is a sketch of what that would look like in code, though I suspect if you're reconfiguring the low-level network interface then you will need to actually close the http listener and rebind.
case object NetworkReady
class ApiManager extends HttpServiceActor with Directives {
override def receive: Receive = networkReady
private def networkReady: Receive = runRoute(routes) orElse networkManagementEvents
private def networkManagementEvents: Receive = {
case Config =>
context.become(reconfiguringNetwork)
magicallyReconfigureNetwork pipeTo self
}
private def magicallyReconfigureNetwork: Future[NetworkReady] = ???
private def reconfiguringNetwork: Receive = {
case NetworkReady => context.become(networkReady)
case _: HttpRequest => sender() ! HttpResponse(ServiceUnavailable)
case _: Tcp.Connected => sender() ! Tcp.Close
}
private def routes: Route = {
(post & path("configNetwork") & entity(as[Config])) { config =>
complete(HttpResponse(OK).withAck(config))
}
}
}