2011-09-15 10:20:18 +02:00
/* *
* Copyright ( C ) 2009 - 2011 Typesafe Inc . < http : //www.typesafe.com>
*/
2011-09-20 21:44:50 +02:00
package akka.remote
2011-09-15 10:20:18 +02:00
import akka.actor._
2011-10-05 18:44:27 +02:00
import akka.routing._
2011-10-07 15:42:55 +02:00
import akka.actor.Actor._
import akka.actor.Status._
2011-09-15 10:20:18 +02:00
import akka.event.EventHandler
2011-09-19 14:43:28 +02:00
import akka.util.duration._
import akka.config.ConfigurationException
2011-09-15 10:20:18 +02:00
import akka.AkkaException
import RemoteProtocol._
2011-09-19 14:43:28 +02:00
import RemoteDaemonMessageType._
import akka.serialization. { Serialization , Serializer , ActorSerialization , Compression }
import Compression.LZF
2011-09-15 10:20:18 +02:00
import java.net.InetSocketAddress
2011-09-19 14:43:28 +02:00
import com.google.protobuf.ByteString
2011-09-15 10:20:18 +02:00
/* *
2011-09-19 14:43:28 +02:00
* Remote ActorRefProvider . Starts up actor on remote node and creates a RemoteActorRef representing it .
*
* @author < a href = "http://jonasboner.com" > Jonas Bon & # 233 ; r </ a >
2011-09-15 10:20:18 +02:00
*/
class RemoteActorRefProvider extends ActorRefProvider {
2011-09-27 10:40:27 +02:00
import java.util.concurrent.ConcurrentHashMap
import akka.dispatch.Promise
private val actors = new ConcurrentHashMap [ String , Promise [ Option [ ActorRef ] ] ]
2011-10-07 19:42:10 +02:00
2011-10-07 15:42:55 +02:00
private val remoteDaemonConnectionManager = new RemoteConnectionManager ( failureDetector = new BannagePeriodFailureDetector ( 60 seconds ) ) // FIXME make timeout configurable
2011-09-19 14:43:28 +02:00
2011-09-15 10:20:18 +02:00
def actorOf ( props : Props , address : String ) : Option [ ActorRef ] = {
Address . validate ( address )
2011-09-27 10:40:27 +02:00
val newFuture = Promise [ Option [ ActorRef ] ] ( 5000 ) // FIXME is this proper timeout?
val oldFuture = actors . putIfAbsent ( address , newFuture )
if ( oldFuture eq null ) { // we won the race -- create the actor and resolve the future
2011-09-27 16:52:33 +02:00
val actor = try {
2011-09-27 10:40:27 +02:00
Deployer . lookupDeploymentFor ( address ) match {
2011-10-07 15:42:55 +02:00
case Some ( DeploymentConfig . Deploy ( _ , _ , routerType , nrOfInstances , failureDetectorType , DeploymentConfig . RemoteScope ( remoteAddresses ) ) ) ⇒
val failureDetector = DeploymentConfig . failureDetectorTypeFor ( failureDetectorType ) match {
case FailureDetectorType . NoOpFailureDetector ⇒ new NoOpFailureDetector
case FailureDetectorType . RemoveConnectionOnFirstFailureFailureDetector ⇒ new RemoveConnectionOnFirstFailureFailureDetector
case FailureDetectorType . BannagePeriodFailureDetector ( timeToBan ) ⇒ new BannagePeriodFailureDetector ( timeToBan )
case FailureDetectorType . CustomFailureDetector ( implClass ) ⇒ FailureDetector . createCustomFailureDetector ( implClass )
}
2011-09-27 10:40:27 +02:00
2011-10-05 18:44:27 +02:00
val thisHostname = Remote . address . getHostName
val thisPort = Remote . address . getPort
def isReplicaNode : Boolean = remoteAddresses exists { remoteAddress ⇒
remoteAddress . hostname == thisHostname && remoteAddress . port == thisPort
}
if ( isReplicaNode ) {
// we are on one of the replica node for this remote actor
2011-09-27 10:40:27 +02:00
Some ( new LocalActorRef ( props , address , false ) ) // create a local actor
} else {
2011-10-05 18:44:27 +02:00
// we are on the single "reference" node uses the remote actors on the replica nodes
2011-10-07 15:42:55 +02:00
val routerFactory : ( ) ⇒ Router = DeploymentConfig . routerTypeFor ( routerType ) match {
2011-10-05 18:44:27 +02:00
case RouterType . Direct ⇒
if ( remoteAddresses . size != 1 ) throw new ConfigurationException (
"Actor [%s] configured with Direct router must have exactly 1 remote node configured. Found [%s]"
. format ( address , remoteAddresses . mkString ( ", " ) ) )
( ) ⇒ new DirectRouter
case RouterType . Random ⇒
if ( remoteAddresses . size < 1 ) throw new ConfigurationException (
"Actor [%s] configured with Random router must have at least 1 remote node configured. Found [%s]"
. format ( address , remoteAddresses . mkString ( ", " ) ) )
( ) ⇒ new RandomRouter
case RouterType . RoundRobin ⇒
if ( remoteAddresses . size < 1 ) throw new ConfigurationException (
"Actor [%s] configured with RoundRobin router must have at least 1 remote node configured. Found [%s]"
. format ( address , remoteAddresses . mkString ( ", " ) ) )
( ) ⇒ new RoundRobinRouter
2011-10-07 15:42:55 +02:00
case RouterType . ScatterGather ⇒
if ( remoteAddresses . size < 1 ) throw new ConfigurationException (
"Actor [%s] configured with ScatterGather router must have at least 1 remote node configured. Found [%s]"
. format ( address , remoteAddresses . mkString ( ", " ) ) )
( ) ⇒ new ScatterGatherFirstCompletedRouter
2011-10-05 18:44:27 +02:00
case RouterType . LeastCPU ⇒ sys . error ( "Router LeastCPU not supported yet" )
case RouterType . LeastRAM ⇒ sys . error ( "Router LeastRAM not supported yet" )
case RouterType . LeastMessages ⇒ sys . error ( "Router LeastMessages not supported yet" )
case RouterType . Custom ⇒ sys . error ( "Router Custom not supported yet" )
}
2011-10-07 15:42:55 +02:00
var connections = Map . empty [ InetSocketAddress , ActorRef ]
remoteAddresses foreach { remoteAddress : DeploymentConfig . RemoteAddress ⇒
2011-10-05 18:44:27 +02:00
val inetSocketAddress = new InetSocketAddress ( remoteAddress . hostname , remoteAddress . port )
2011-10-07 15:42:55 +02:00
connections += ( inetSocketAddress -> RemoteActorRef ( inetSocketAddress , address , Actor . TIMEOUT , None ) )
2011-10-05 18:44:27 +02:00
}
2011-10-07 15:42:55 +02:00
val connectionManager = new RemoteConnectionManager ( connections , failureDetector )
connections . keys foreach { useActorOnNode ( _ , address , props . creator ) }
2011-10-05 18:44:27 +02:00
Some ( Routing . actorOf ( RoutedProps (
routerFactory = routerFactory ,
2011-10-07 15:42:55 +02:00
connectionManager = connectionManager ) ) )
2011-09-27 10:40:27 +02:00
}
case deploy ⇒ None // non-remote actor
2011-09-27 17:41:02 +02:00
}
2011-09-27 16:52:33 +02:00
} catch {
case e : Exception ⇒
newFuture completeWithException e // so the other threads gets notified of error
throw e
}
2011-09-27 10:40:27 +02:00
2011-10-07 19:42:10 +02:00
// actor foreach Actor.registry.register // only for ActorRegistry backward compat, will be removed later
2011-09-27 16:52:33 +02:00
newFuture completeWithResult actor
2011-09-27 10:40:27 +02:00
actor
} else { // we lost the race -- wait for future to complete
2011-09-27 16:52:33 +02:00
oldFuture . await . resultOrException . getOrElse ( None )
2011-09-15 10:20:18 +02:00
}
}
2011-10-07 19:42:10 +02:00
def actorFor ( address : String ) : Option [ ActorRef ] = actors . get ( address ) match {
case null ⇒ None
case future ⇒ future . await . resultOrException . getOrElse ( None )
}
2011-09-15 10:20:18 +02:00
2011-09-27 11:49:42 +02:00
/* *
* Returns true if the actor was in the provider 's cache and evicted successfully , else false .
*/
private [ akka ] def evict ( address : String ) : Boolean = actors . remove ( address ) ne null
2011-09-19 14:43:28 +02:00
/* *
* Using ( checking out ) actor on a specific node .
*/
def useActorOnNode ( remoteAddress : InetSocketAddress , actorAddress : String , actorFactory : ( ) ⇒ Actor ) {
EventHandler . debug ( this , "Instantiating Actor [%s] on node [%s]" . format ( actorAddress , remoteAddress ) )
val actorFactoryBytes =
Serialization . serialize ( actorFactory ) match {
case Left ( error ) ⇒ throw error
case Right ( bytes ) ⇒
if ( Remote . shouldCompressData ) LZF . compress ( bytes )
else bytes
}
val command = RemoteDaemonMessageProtocol . newBuilder
. setMessageType ( USE )
. setActorAddress ( actorAddress )
. setPayload ( ByteString . copyFrom ( actorFactoryBytes ) )
. build ( )
2011-09-22 03:36:59 +02:00
val connectionFactory =
( ) ⇒ Remote . server . actorFor (
Remote . remoteDaemonServiceName , remoteAddress . getHostName , remoteAddress . getPort )
2011-09-19 14:43:28 +02:00
// try to get the connection for the remote address, if not already there then create it
2011-10-07 15:42:55 +02:00
val connection = remoteDaemonConnectionManager . putIfAbsent ( remoteAddress , connectionFactory )
2011-09-19 14:43:28 +02:00
2011-09-22 03:36:59 +02:00
sendCommandToRemoteNode ( connection , command , withACK = true ) // ensure we get an ACK on the USE command
2011-09-15 10:20:18 +02:00
}
2011-09-19 14:43:28 +02:00
private def sendCommandToRemoteNode (
2011-09-15 10:20:18 +02:00
connection : ActorRef ,
command : RemoteDaemonMessageProtocol ,
2011-09-22 03:36:59 +02:00
withACK : Boolean ) {
2011-09-15 10:20:18 +02:00
2011-09-22 03:36:59 +02:00
if ( withACK ) {
2011-09-15 10:20:18 +02:00
try {
( connection ? ( command , Remote . remoteDaemonAckTimeout ) ) . as [ Status ] match {
2011-09-19 14:43:28 +02:00
case Some ( Success ( receiver ) ) ⇒
EventHandler . debug ( this , "Remote command sent to [%s] successfully received" . format ( receiver ) )
2011-09-15 10:20:18 +02:00
case Some ( Failure ( cause ) ) ⇒
EventHandler . error ( cause , this , cause . toString )
throw cause
case None ⇒
val error = new RemoteException ( "Remote command to [%s] timed out" . format ( connection . address ) )
EventHandler . error ( error , this , error . toString )
throw error
}
} catch {
case e : Exception ⇒
EventHandler . error ( e , this , "Could not send remote command to [%s] due to: %s" . format ( connection . address , e . toString ) )
throw e
}
2011-09-22 03:36:59 +02:00
} else {
connection ! command
2011-09-15 10:20:18 +02:00
}
}
}