From 824158a6980edf2a085f1b97d8e58034843be8ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Wed, 30 Jan 2013 18:10:45 +0100 Subject: [PATCH 01/18] First iteration of Fire-and-Forget style UDP IO --- .../scala/akka/io/UdpFFIntegrationSpec.scala | 59 ++++++ akka-actor/src/main/resources/reference.conf | 58 ++++++ akka-actor/src/main/scala/akka/io/UdpFF.scala | 177 +++++++++++++++++ .../main/scala/akka/io/UdpFFListener.scala | 89 +++++++++ .../src/main/scala/akka/io/UdpFFManager.scala | 60 ++++++ .../main/scala/akka/io/UdpFFSelector.scala | 186 ++++++++++++++++++ .../src/main/scala/akka/io/UdpFFSender.scala | 36 ++++ .../main/scala/akka/io/WithUdpFFSend.scala | 63 ++++++ 8 files changed, 728 insertions(+) create mode 100644 akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpFF.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpFFListener.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpFFManager.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpFFSelector.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpFFSender.scala create mode 100644 akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala new file mode 100644 index 0000000000..21d61c3e1d --- /dev/null +++ b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala @@ -0,0 +1,59 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.testkit.{ TestProbe, ImplicitSender, AkkaSpec } +import akka.io.UdpFF._ +import TestUtils._ +import akka.util.ByteString +import java.net.InetSocketAddress +import akka.actor.ActorRef + +class UdpFFIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with ImplicitSender { + + def bindUdp(handler: ActorRef): (InetSocketAddress, ActorRef) = { + val address = temporaryServerAddress() + val commander = TestProbe() + commander.send(IO(UdpFF), Bind(handler, address)) + commander.expectMsg(Bound) + (address, commander.sender) + } + + val simpleSender: ActorRef = { + val commander = TestProbe() + commander.send(IO(UdpFF), SimpleSender) + commander.expectMsg(SimpleSendReady) + commander.sender + } + + "The UDP Fire-and-Forget implementation" must { + + "be able to send without binding" in { + val (serverAddress, server) = bindUdp(testActor) + val data = ByteString("To infinity and beyond!") + simpleSender ! Send(data, serverAddress) + + expectMsgPF() { + case Received(d, _) ⇒ + d must be === data + } + } + + "be able to send with binding" in { + val (serverAddress, _) = bindUdp(testActor) + val (clientAddress, client) = bindUdp(testActor) + val data = ByteString("Fly little packet!") + + client ! Send(data, serverAddress) + + expectMsgPF() { + case Received(d, a) ⇒ + d must be === data + a must be === clientAddress + } + } + + } + +} diff --git a/akka-actor/src/main/resources/reference.conf b/akka-actor/src/main/resources/reference.conf index 9d86ff75b2..859ae7acbf 100644 --- a/akka-actor/src/main/resources/reference.conf +++ b/akka-actor/src/main/resources/reference.conf @@ -445,6 +445,62 @@ akka { management-dispatcher = "akka.actor.default-dispatcher" } + udpFF { + + # The number of selectors to stripe the served channels over; each of + # these will use one select loop on the selector-dispatcher. + nr-of-selectors = 1 + + # Maximum number of open channels supported by this UDP module Generally + # UDP does not require a large number of channels, therefore it is + # recommended to keep this setting low. + max-channels = 4096 + + # The select loop can be used in two modes: + # - setting "infinite" will select without a timeout, hogging a thread + # - setting a positive timeout will do a bounded select call, + # enabling sharing of a single thread between multiple selectors + # (in this case you will have to use a different configuration for the + # selector-dispatcher, e.g. using "type=Dispatcher" with size 1) + # - setting it to zero means polling, i.e. calling selectNow() + select-timeout = infinite + + # When trying to assign a new connection to a selector and the chosen + # selector is at full capacity, retry selector choosing and assignment + # this many times before giving up + selector-association-retries = 10 + + # The number of bytes per direct buffer in the pool used to read or write + # network data from the kernel. + direct-buffer-size = 128 KiB + + # The maximal number of direct buffers kept in the direct buffer pool for + # reuse. + max-direct-buffer-pool-size = 1000 + + # The maximum number of bytes delivered by a `Received` message. Before + # more data is read from the network the connection actor will try to + # do other work. + received-message-size-limit = unlimited + + # Enable fine grained logging of what goes on inside the implementation. + # Be aware that this may log more than once per message sent to the actors + # of the tcp implementation. + trace-logging = off + + # Fully qualified config path which holds the dispatcher configuration + # to be used for running the select() calls in the selectors + selector-dispatcher = "akka.io.pinned-dispatcher" + + # Fully qualified config path which holds the dispatcher configuration + # for the read/write worker actors + worker-dispatcher = "akka.actor.default-dispatcher" + + # Fully qualified config path which holds the dispatcher configuration + # for the selector management actors + management-dispatcher = "akka.actor.default-dispatcher" + } + # IMPORTANT NOTICE: # # The following settings belong to the deprecated akka.actor.IO @@ -463,4 +519,6 @@ akka { # 0 or negative means that the platform default will be used. default-backlog = 1000 } + + } diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala new file mode 100644 index 0000000000..b6d78fc1d1 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -0,0 +1,177 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor._ +import akka.util.ByteString +import java.net.{ DatagramSocket, Socket, InetSocketAddress } +import scala.collection.immutable +import com.typesafe.config.Config +import scala.concurrent.duration.Duration +import java.nio.ByteBuffer + +object UdpFF extends ExtensionKey[UdpFFExt] { + + // Java API + override def get(system: ActorSystem): UdpFFExt = system.extension(this) + + /** + * SocketOption is a package of data (from the user) and associated + * behavior (how to apply that to a socket). + */ + sealed trait SocketOption { + /** + * Action to be taken for this option before calling bind() + */ + def beforeBind(s: DatagramSocket): Unit = () + + } + + object SO { + + /** + * [[akka.io.UdpFF.SocketOption]] to set the SO_BROADCAST option + * + * For more information see [[java.net.DatagramSocket#setBroadcast]] + */ + case class Broadcast(on: Boolean) extends SocketOption { + override def beforeBind(s: DatagramSocket): Unit = s.setBroadcast(on) + } + + /** + * [[akka.io.UdpFF.SocketOption]] to set the SO_RCVBUF option + * + * For more information see [[java.net.Socket#setReceiveBufferSize]] + */ + case class ReceiveBufferSize(size: Int) extends SocketOption { + require(size > 0, "ReceiveBufferSize must be > 0") + override def beforeBind(s: DatagramSocket): Unit = s.setReceiveBufferSize(size) + } + + /** + * [[akka.io.UdpFF.SocketOption]] to enable or disable SO_REUSEADDR + * + * For more information see [[java.net.Socket#setReuseAddress]] + */ + case class ReuseAddress(on: Boolean) extends SocketOption { + override def beforeBind(s: DatagramSocket): Unit = s.setReuseAddress(on) + } + + /** + * [[akka.io.UdpFF.SocketOption]] to set the SO_SNDBUF option. + * + * For more information see [[java.net.Socket#setSendBufferSize]] + */ + case class SendBufferSize(size: Int) extends SocketOption { + require(size > 0, "SendBufferSize must be > 0") + override def beforeBind(s: DatagramSocket): Unit = s.setSendBufferSize(size) + } + + /** + * [[akka.io.UdpFF.SocketOption]] to set the traffic class or + * type-of-service octet in the IP header for packets sent from this + * socket. + * + * For more information see [[java.net.Socket#setTrafficClass]] + */ + case class TrafficClass(tc: Int) extends SocketOption { + require(0 <= tc && tc <= 255, "TrafficClass needs to be in the interval [0, 255]") + override def beforeBind(s: DatagramSocket): Unit = s.setTrafficClass(tc) + } + } + + trait Command + + case object NoAck + case class Send(payload: ByteString, target: InetSocketAddress, ack: Any) extends Command { + require(ack != null, "ack must be non-null. Use NoAck if you don't want acks.") + + def wantsAck: Boolean = ack != NoAck + } + object Send { + def apply(data: ByteString, target: InetSocketAddress): Send = Send(data, target, NoAck) + } + + case class Bind(handler: ActorRef, + endpoint: InetSocketAddress, + options: immutable.Traversable[SocketOption] = Nil) extends Command + case object Unbind extends Command + + case object SimpleSender extends Command + + case object StopReading extends Command + case object ResumeReading extends Command + + trait Event + + case class Received(data: ByteString, sender: InetSocketAddress) extends Event + case class CommandFailed(cmd: Command) extends Event + case object Bound extends Event + case object SimpleSendReady extends Event + case object Unbound extends Event + + sealed trait CloseCommand extends Command + case object Close extends CloseCommand + case object Abort extends CloseCommand + + case class SendFailed(cause: Throwable) extends Event + +} + +class UdpFFExt(system: ExtendedActorSystem) extends IO.Extension { + + val Settings = new Settings(system.settings.config.getConfig("akka.io.udpFF")) + class Settings private[UdpFFExt] (config: Config) { + import config._ + + val NrOfSelectors = getInt("nr-of-selectors") + val MaxChannels = getString("max-channels") match { + case "unlimited" ⇒ -1 + case _ ⇒ getInt("max-channels") + } + val SelectTimeout = getString("select-timeout") match { + case "infinite" ⇒ Duration.Inf + case x ⇒ Duration(x) + } + val SelectorAssociationRetries = getInt("selector-association-retries") + val DirectBufferSize = getIntBytes("direct-buffer-size") + val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") + + val SelectorDispatcher = getString("selector-dispatcher") + val WorkerDispatcher = getString("worker-dispatcher") + val ManagementDispatcher = getString("management-dispatcher") + val TraceLogging = getBoolean("trace-logging") + + require(NrOfSelectors > 0, "nr-of-selectors must be > 0") + require(MaxChannels == -1 || MaxChannels > 0, "max-channels must be > 0 or 'unlimited'") + require(SelectTimeout >= Duration.Zero, "select-timeout must not be negative") + require(SelectorAssociationRetries >= 0, "selector-association-retries must be >= 0") + + val MaxChannelsPerSelector = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) + + private[this] def getIntBytes(path: String): Int = { + val size = getBytes(path) + require(size < Int.MaxValue, s"$path must be < 2 GiB") + size.toInt + } + } + + val manager = { + system.asInstanceOf[ActorSystemImpl].systemActorOf( + props = Props(new UdpFFManager(this)), + name = "IO-UDP-FF") + } + + val bufferPool: BufferPool = new DirectByteBufferPool(Settings.DirectBufferSize, Settings.MaxDirectBufferPoolSize) +} + +trait WithUdpFFBufferPool { + def udpFF: UdpFFExt + + def acquireBuffer(): ByteBuffer = + udpFF.bufferPool.acquire() + + def releaseBuffer(buffer: ByteBuffer): Unit = + udpFF.bufferPool.release(buffer) +} \ No newline at end of file diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala new file mode 100644 index 0000000000..f8b72e6f6c --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -0,0 +1,89 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor.{ ActorLogging, Actor, ActorRef } +import akka.io.UdpFF._ +import akka.io.UdpFFSelector._ +import akka.util.ByteString +import java.net.InetSocketAddress +import java.nio.channels.DatagramChannel +import java.nio.channels.SelectionKey._ +import scala.collection.immutable +import scala.util.control.NonFatal + +private[io] class UdpFFListener(selectorRouter: ActorRef, + handler: ActorRef, + endpoint: InetSocketAddress, + bindCommander: ActorRef, + val udpFF: UdpFFExt, + options: immutable.Traversable[SocketOption]) + extends Actor with ActorLogging with WithUdpFFBufferPool with WithUdpFFSend { + import udpFF.Settings._ + + def selector: ActorRef = context.parent + + context.watch(handler) // sign death pact + val channel = { + val datagramChannel = DatagramChannel.open + datagramChannel.configureBlocking(false) + val socket = datagramChannel.socket + options.foreach(_.beforeBind(socket)) + socket.bind(endpoint) // will blow up the actor constructor if the bind fails + datagramChannel + } + context.parent ! RegisterDatagramChannel(channel, OP_READ) + bindCommander ! Bound + log.debug("Successfully bound to {}", endpoint) + + def receive: Receive = receiveInternal orElse sendHandlers + + def receiveInternal: Receive = { + case StopReading ⇒ selector ! StopReading + case ResumeReading ⇒ selector ! ReadInterest + case ChannelReadable ⇒ doReceive(handler, None) + + case CommandFailed(RegisterDatagramChannel(datagramChannel, _)) ⇒ + log.warning("Could not bind to UDP port since selector capacity limit is reached, aborting bind") + try datagramChannel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing channel") + } + + case Unbind ⇒ + log.debug("Unbinding endpoint {}", endpoint) + channel.close() + sender ! Unbound + log.debug("Unbound endpoint {}, stopping listener", endpoint) + context.stop(self) + } + + def doReceive(handler: ActorRef, closeCommander: Option[ActorRef]): Unit = { + val buffer = acquireBuffer() + try { + buffer.clear() + buffer.limit(DirectBufferSize) + + channel.receive(buffer) match { + case sender: InetSocketAddress ⇒ + buffer.flip() + handler ! Received(ByteString(buffer), sender) + case _ ⇒ // Ignore + } + + selector ! ReadInterest + } finally releaseBuffer(buffer) + } + + override def postStop() { + try { + if (channel.isOpen) { + log.debug("Closing serverSocketChannel after being stopped") + channel.close() + } + } catch { + case NonFatal(e) ⇒ log.error(e, "Error closing ServerSocketChannel") + } + } +} diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala new file mode 100644 index 0000000000..f4c39fad1a --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -0,0 +1,60 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor.{ ActorRef, Props, Actor } +import akka.io.UdpFF._ +import akka.routing.RandomRouter + +/** + * UdpFFManager is a facade for simple fire-and-forget style UDP operations + * + * UdpFFManager is obtainable by calling {{{ IO(UdpFF) }}} (see [[akka.io.IO]] and [[akka.io.UdpFF]]) + * + * *Warning!* UdpFF uses [[java.nio.channels.DatagramChannel#send]] to deliver datagrams, and as a consequence if a + * security manager has been installed then for each datagram it will verify if the target address and port number are + * permitted. If this performance overhead is undesirable use the connection style Udp extension. + * + * == Bind and send == + * + * To bind and listen to a local address, a [[akka.io.UdpFF..Bind]] command must be sent to this actor. If the binding + * was successful, the sender of the [[akka.io.UdpFF.Bind]] will be notified with a [[akka.io.UdpFF.Bound]] + * message. The sender of the [[akka.io.UdpFF.Bound]] message is the Listener actor (an internal actor responsible for + * listening to server events). To unbind the port an [[akka.io.Tcp.Unbind]] message must be sent to the Listener actor. + * + * If the bind request is rejected because the Udp system is not able to register more channels (see the nr-of-selectors + * and max-channels configuration options in the akka.io.udpFF section of the configuration) the sender will be notified + * with a [[akka.io.UdpFF.CommandFailed]] message. This message contains the original command for reference. + * + * The handler provided in the [[akka.io.UdpFF.Bind]] message will receive inbound datagrams to the bound port + * wrapped in [[akka.io.UdpFF.Received]] messages which contain the payload of the datagram and the sender address. + * + * UDP datagrams can be sent by sending [[akka.io.UdpFF.Send]] messages to the Listener actor. The sender port of the + * outbound datagram will be the port to which the Listener is bound. + * + * == Simple send == + * + * UdpFF provides a simple method of sending UDP datagrams if no reply is expected. To acquire the Sender actor + * a SimpleSend message has to be sent to the manager. The sender of the command will be notified by a SimpleSendReady + * message that the service is available. UDP datagrams can be sent by sending [[akka.io.UdpFF.Send]] messages to the + * sender of SimpleSendReady. All the datagrams will contain an ephemeral local port as sender and answers will be + * discarded. + * + */ +private[io] class UdpFFManager(udpFF: UdpFFExt) extends Actor { + + val selectorPool = context.actorOf( + props = Props(new UdpFFSelector(self, udpFF)).withRouter(RandomRouter(udpFF.Settings.NrOfSelectors)), + name = "selectors") + + lazy val anonymousSender: ActorRef = context.actorOf( + props = Props(new UdpFFSender(udpFF, selectorPool)), + name = "simplesend") + + def receive = { + case c: Bind ⇒ selectorPool forward c + case SimpleSender ⇒ anonymousSender forward SimpleSender + } + +} diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala b/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala new file mode 100644 index 0000000000..86ebbd2a94 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala @@ -0,0 +1,186 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.io.UdpFF._ +import akka.actor._ +import java.lang.Runnable +import java.nio.channels.{ DatagramChannel, SelectionKey } +import java.nio.channels.SelectionKey._ +import java.nio.channels.spi.SelectorProvider +import scala.collection.immutable +import scala.concurrent.duration._ +import scala.util.control.NonFatal + +private[io] object UdpFFSelector { + case class Retry(command: Command, retriesLeft: Int) { require(retriesLeft >= 0) } + case class RegisterDatagramChannel(channel: DatagramChannel, initialOps: Int) extends Command + + case object ChannelReadable + case object ChannelWritable + case object ReadInterest + case object WriteInterest +} + +private[io] class UdpFFSelector(manager: ActorRef, udp: UdpFFExt) extends Actor with ActorLogging { + + import UdpFFSelector._ + import udp.Settings._ + + @volatile var childrenKeys = immutable.HashMap.empty[String, SelectionKey] + val sequenceNumber = Iterator from 0 + val selectorManagementDispatcher = context.system.dispatchers.lookup(SelectorDispatcher) + val selector = SelectorProvider.provider.openSelector + val OP_READ_AND_WRITE = OP_READ + OP_WRITE // compile-time constant + + def receive: Receive = { + case WriteInterest ⇒ execute(enableInterest(OP_WRITE, sender)) + case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) + case StopReading ⇒ execute(disableInterest(OP_READ, sender)) + + case cmd: Bind ⇒ + handleBind(cmd, SelectorAssociationRetries) + + case RegisterDatagramChannel(channel, initialOps) ⇒ + execute(registerDatagramChannel(channel, sender, initialOps)) + + case Retry(command, 0) ⇒ + log.warning("Command '{}' failed since all selectors are at capacity", command) + sender ! CommandFailed(command) + + case Retry(cmd: Bind, retriesLeft) ⇒ + handleBind(cmd, retriesLeft) + + case Terminated(child) ⇒ + execute(unregister(child)) + } + + override def postStop() { + try { + try { + val iterator = selector.keys.iterator + while (iterator.hasNext) iterator.next().channel.close() + } finally selector.close() + } catch { + case NonFatal(e) ⇒ log.error(e, "Error closing selector or key") + } + } + + // we can never recover from failures of a connection or listener child + override def supervisorStrategy = SupervisorStrategy.stoppingStrategy + + def handleBind(cmd: Bind, retriesLeft: Int): Unit = + withCapacityProtection(cmd, retriesLeft) { + import cmd._ + val commander = sender + spawnChild(() ⇒ new UdpFFListener(context.parent, handler, endpoint, commander, udp, options)) + } + + def withCapacityProtection(cmd: Command, retriesLeft: Int)(body: ⇒ Unit): Unit = { + log.debug("Executing {}", cmd) + if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { + body + } else { + log.warning("Rejecting '{}' with {} retries left, retrying...", cmd, retriesLeft) + context.parent forward Retry(cmd, retriesLeft - 1) + } + } + + def spawnChild(creator: () ⇒ Actor) = + context.watch { + context.actorOf( + props = Props(creator, dispatcher = WorkerDispatcher), + name = sequenceNumber.next().toString) + } + + //////////////// Management Tasks scheduled via the selectorManagementDispatcher ///////////// + + def execute(task: Task): Unit = { + selectorManagementDispatcher.execute(task) + selector.wakeup() + } + + def updateKeyMap(child: ActorRef, key: SelectionKey): Unit = + childrenKeys = childrenKeys.updated(child.path.name, key) + + def registerDatagramChannel(channel: DatagramChannel, connection: ActorRef, initialOps: Int) = + new Task { + def tryRun() { + val key = channel.register(selector, initialOps, connection) + updateKeyMap(connection, key) + } + } + + // TODO: evaluate whether we could run the following two tasks directly on the TcpSelector actor itself rather than + // on the selector-management-dispatcher. The trade-off would be using a ConcurrentHashMap + // rather than an unsynchronized one, but since switching interest ops is so frequent + // the change might be beneficial, provided the underlying implementation really is thread-safe + // and behaves consistently on all platforms. + def enableInterest(op: Int, connection: ActorRef) = + new Task { + def tryRun() { + val key = childrenKeys(connection.path.name) + key.interestOps(key.interestOps | op) + } + } + + def disableInterest(op: Int, connection: ActorRef) = + new Task { + def tryRun() { + val key = childrenKeys(connection.path.name) + key.interestOps(key.interestOps & ~op) + } + } + + def unregister(child: ActorRef) = + new Task { + def tryRun() { + childrenKeys = childrenKeys - child.path.name + } + } + + val select = new Task { + val doSelect: () ⇒ Int = + SelectTimeout match { + case Duration.Zero ⇒ () ⇒ selector.selectNow() + case Duration.Inf ⇒ () ⇒ selector.select() + case x ⇒ val millis = x.toMillis; () ⇒ selector.select(millis) + } + def tryRun() { + if (doSelect() > 0) { + val keys = selector.selectedKeys + val iterator = keys.iterator() + while (iterator.hasNext) { + val key = iterator.next + if (key.isValid) { + key.interestOps(0) // prevent immediate reselection by always clearing + val connection = key.attachment.asInstanceOf[ActorRef] + key.readyOps match { + case OP_READ ⇒ connection ! ChannelReadable + case OP_WRITE ⇒ connection ! ChannelWritable + case OP_READ_AND_WRITE ⇒ connection ! ChannelWritable; connection ! ChannelReadable + case x ⇒ log.warning("Invalid readyOps: {}", x) + } + } else log.warning("Invalid selection key: {}", key) + } + keys.clear() // we need to remove the selected keys from the set, otherwise they remain selected + } + selectorManagementDispatcher.execute(this) // re-schedules select behind all currently queued tasks + } + } + + selectorManagementDispatcher.execute(select) // start selection "loop" + + abstract class Task extends Runnable { + def tryRun() + def run() { + try tryRun() + catch { + case _: java.nio.channels.ClosedSelectorException ⇒ // ok, expected during shutdown + case NonFatal(e) ⇒ log.error(e, "Error during selector management task: {}", e) + } + } + } +} + diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala new file mode 100644 index 0000000000..11218531d1 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala @@ -0,0 +1,36 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor._ +import java.nio.channels.DatagramChannel +import akka.io.UdpFF._ +import akka.io.UdpFFSelector.RegisterDatagramChannel + +/** + * Base class for TcpIncomingConnection and TcpOutgoingConnection. + */ +private[io] class UdpFFSender(val udpFF: UdpFFExt, val selector: ActorRef) + extends Actor with ActorLogging with WithUdpFFBufferPool with WithUdpFFSend { + + val channel = { + val datagramChannel = DatagramChannel.open + datagramChannel.configureBlocking(false) + datagramChannel + } + selector ! RegisterDatagramChannel(channel, 0) + + def receive: Receive = internalReceive orElse sendHandlers + + def internalReceive: Receive = { + case SimpleSender ⇒ sender ! SimpleSendReady + } + + override def postStop(): Unit = if (channel.isOpen) channel.close() + + override def postRestart(reason: Throwable): Unit = + throw new IllegalStateException("Restarting not supported for connection actors.") + +} + diff --git a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala new file mode 100644 index 0000000000..8e81f584fb --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala @@ -0,0 +1,63 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor.{ ActorRef, ActorLogging, Actor } +import akka.io.UdpFF.{ CommandFailed, Send } +import akka.io.UdpFFSelector._ +import java.nio.channels.DatagramChannel + +trait WithUdpFFSend { + me: Actor with ActorLogging with WithUdpFFBufferPool ⇒ + + var pendingSend: (Send, ActorRef) = null + def writePending = pendingSend ne null + + def selector: ActorRef + def channel: DatagramChannel + def udpFF: UdpFFExt + val settings = udpFF.Settings + + import settings._ + + def sendHandlers: Receive = { + + case send: Send if writePending ⇒ + if (TraceLogging) log.debug("Dropping write because queue is full") + sender ! CommandFailed(send) + + case send: Send if send.payload.isEmpty ⇒ + if (send.wantsAck) + sender ! send.ack + + case send: Send ⇒ + pendingSend = (send, sender) + selector ! WriteInterest + + case ChannelWritable ⇒ doSend() + + } + + final def doSend(): Unit = { + + val buffer = acquireBuffer() + try { + val (send, commander) = pendingSend + buffer.clear() + send.payload.copyToBuffer(buffer) + buffer.flip() + val writtenBytes = channel.send(buffer, send.target) + if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes) + + // Datagram channel either sends the whole message, or nothing + if (writtenBytes == 0) commander ! CommandFailed(send) + else if (send.wantsAck) commander ! send.ack + + } finally { + releaseBuffer(buffer) + pendingSend = null + } + + } +} From ad60b155c624b8034542186ea21a4c5118ee1721 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Fri, 1 Feb 2013 12:38:13 +0100 Subject: [PATCH 02/18] Temporary LIMBO commit, but UDP now uses the unified selector --- .../main/scala/akka/io/SelectionHandler.scala | 288 ++++++++++++++++++ akka-actor/src/main/scala/akka/io/UdpFF.scala | 25 +- .../main/scala/akka/io/UdpFFListener.scala | 18 +- .../src/main/scala/akka/io/UdpFFManager.scala | 9 +- .../main/scala/akka/io/UdpFFSelector.scala | 2 +- .../src/main/scala/akka/io/UdpFFSender.scala | 4 +- .../main/scala/akka/io/WithUdpFFSend.scala | 4 +- 7 files changed, 314 insertions(+), 36 deletions(-) create mode 100644 akka-actor/src/main/scala/akka/io/SelectionHandler.scala diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala new file mode 100644 index 0000000000..e1f48de592 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -0,0 +1,288 @@ +/** + * Copyright (C) 2009-2012 Typesafe Inc. + */ + +package akka.io + +import java.lang.Runnable +import java.nio.channels.spi.SelectorProvider +import java.nio.channels.{ SelectableChannel, SelectionKey } +import java.nio.channels.SelectionKey._ +import scala.util.control.NonFatal +import scala.collection.immutable +import scala.concurrent.duration._ +import akka.actor._ +import com.typesafe.config.Config +import akka.actor.Terminated + +abstract class SelectionHandlerSettings(config: Config) { + import config._ + + val MaxChannels = getString("max-channels") match { + case "unlimited" ⇒ -1 + case _ ⇒ getInt("max-channels") + } + val SelectTimeout = getString("select-timeout") match { + case "infinite" ⇒ Duration.Inf + case x ⇒ Duration(x) + } + val SelectorAssociationRetries = getInt("selector-association-retries") + + val SelectorDispatcher = getString("selector-dispatcher") + val WorkerDispatcher = getString("worker-dispatcher") + val TraceLogging = getBoolean("trace-logging") + + require(MaxChannels == -1 || MaxChannels > 0, "max-channels must be > 0 or 'unlimited'") + require(SelectTimeout >= Duration.Zero, "select-timeout must not be negative") + require(SelectorAssociationRetries >= 0, "selector-association-retries must be >= 0") + + def MaxChannelsPerSelector: Int + +} + +private[io] object SelectionHandler { + //FIXME: temporary + case class KickStartCommand(childProps: Props) + + case class RegisterChannel(channel: SelectableChannel, initialOps: Int) + case class Retry(command: KickStartCommand, retriesLeft: Int) { require(retriesLeft >= 0) } + + case object ChannelConnectable + case object ChannelAcceptable + case object ChannelReadable + case object ChannelWritable + case object AcceptInterest + case object ReadInterest + case object WriteInterest +} + +private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandlerSettings) extends Actor with ActorLogging { + import SelectionHandler._ + import settings._ + + @volatile var childrenKeys = immutable.HashMap.empty[String, SelectionKey] + val sequenceNumber = Iterator.from(0) + val selectorManagementDispatcher = context.system.dispatchers.lookup(SelectorDispatcher) + val selector = SelectorProvider.provider.openSelector + val OP_READ_AND_WRITE = OP_READ | OP_WRITE // compile-time constant + + def receive: Receive = { + case WriteInterest ⇒ execute(enableInterest(OP_WRITE, sender)) + case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) + case AcceptInterest ⇒ execute(enableInterest(OP_ACCEPT, sender)) + + //case StopReading ⇒ execute(disableInterest(OP_READ, sender)) + + // case cmd: RegisterIncomingConnection ⇒ + // handleIncomingConnection(cmd, SelectorAssociationRetries) + // + // case cmd: Connect ⇒ + // handleConnect(cmd, SelectorAssociationRetries) + // + // case cmd: Bind ⇒ + // handleBind(cmd, SelectorAssociationRetries) + + case cmd: KickStartCommand ⇒ + kickStart(cmd, SelectorAssociationRetries) + + // case RegisterOutgoingConnection(channel) ⇒ + // execute(registerOutgoingConnection(channel, sender)) + // + // case RegisterServerSocketChannel(channel) ⇒ + // execute(registerListener(channel, sender)) + + case RegisterChannel(channel, initialOps) ⇒ + execute(registerChannel(channel, sender, initialOps)) + + // case Retry(command, 0) ⇒ + // log.warning("Command '{}' failed since all selectors are at capacity", command) + // sender ! CommandFailed(command) + + case Retry(cmd, retriesLeft) ⇒ + kickStart(cmd, retriesLeft) + + // case Retry(cmd: RegisterIncomingConnection, retriesLeft) ⇒ + // handleIncomingConnection(cmd, retriesLeft) + // + // case Retry(cmd: Connect, retriesLeft) ⇒ + // handleConnect(cmd, retriesLeft) + // + // case Retry(cmd: Bind, retriesLeft) ⇒ + // handleBind(cmd, retriesLeft) + + case Terminated(child) ⇒ + execute(unregister(child)) + } + + override def postStop() { + try { + try { + val iterator = selector.keys.iterator + while (iterator.hasNext) iterator.next().channel.close() + } finally selector.close() + } catch { + case NonFatal(e) ⇒ log.error(e, "Error closing selector or key") + } + } + + // we can never recover from failures of a connection or listener child + override def supervisorStrategy = SupervisorStrategy.stoppingStrategy + + // def handleIncomingConnection(cmd: RegisterIncomingConnection, retriesLeft: Int): Unit = + // withCapacityProtection(cmd, retriesLeft) { + // import cmd._ + // val connection = spawnChild(() ⇒ new TcpIncomingConnection(channel, tcp, handler, options)) + // execute(registerIncomingConnection(channel, connection)) + // } + // + // def handleConnect(cmd: Connect, retriesLeft: Int): Unit = + // withCapacityProtection(cmd, retriesLeft) { + // import cmd._ + // val commander = sender + // spawnChild(() ⇒ new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options)) + // } + // + // def handleBind(cmd: Bind, retriesLeft: Int): Unit = + // withCapacityProtection(cmd, retriesLeft) { + // import cmd._ + // val commander = sender + // spawnChild(() ⇒ new TcpListener(context.parent, handler, endpoint, backlog, commander, tcp.Settings, options)) + // } + + def kickStart(cmd: KickStartCommand, retriesLeft: Int): Unit = withCapacityProtection(cmd, retriesLeft) { + spawnChild(cmd.childProps) // TODO: inject sender somehow + } + + def withCapacityProtection(cmd: KickStartCommand, retriesLeft: Int)(body: ⇒ Unit): Unit = { + log.debug("Executing {}", cmd) + if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { + body + } else { + log.warning("Rejecting '{}' with {} retries left, retrying...", cmd, retriesLeft) + context.parent forward Retry(cmd, retriesLeft - 1) + } + } + + def spawnChild(props: Props) = + context.watch { + context.actorOf( + props = props.withDispatcher(WorkerDispatcher), + name = sequenceNumber.next().toString) + } + + //////////////// Management Tasks scheduled via the selectorManagementDispatcher ///////////// + + def execute(task: Task): Unit = { + selectorManagementDispatcher.execute(task) + selector.wakeup() + } + + def updateKeyMap(child: ActorRef, key: SelectionKey): Unit = + childrenKeys = childrenKeys.updated(child.path.name, key) + + // def registerOutgoingConnection(channel: SocketChannel, connection: ActorRef) = + // new Task { + // def tryRun() { + // val key = channel.register(selector, OP_CONNECT, connection) + // updateKeyMap(connection, key) + // } + // } + // + // def registerListener(channel: ServerSocketChannel, listener: ActorRef) = + // new Task { + // def tryRun() { + // val key = channel.register(selector, OP_ACCEPT, listener) + // updateKeyMap(listener, key) + // listener ! Bound + // } + // } + // + // def registerIncomingConnection(channel: SocketChannel, connection: ActorRef) = + // new Task { + // def tryRun() { + // // we only enable reading after the user-level connection handler has registered + // val key = channel.register(selector, 0, connection) + // updateKeyMap(connection, key) + // } + // } + + def registerChannel(channel: SelectableChannel, channelActor: ActorRef, initialOps: Int): Task = + new Task { + def tryRun() { + updateKeyMap(channelActor, channel.register(selector, initialOps, channelActor)) + } + } + + // TODO: evaluate whether we could run the following two tasks directly on the TcpSelector actor itself rather than + // on the selector-management-dispatcher. The trade-off would be using a ConcurrentHashMap + // rather than an unsynchronized one, but since switching interest ops is so frequent + // the change might be beneficial, provided the underlying implementation really is thread-safe + // and behaves consistently on all platforms. + def enableInterest(op: Int, connection: ActorRef) = + new Task { + def tryRun() { + val key = childrenKeys(connection.path.name) + key.interestOps(key.interestOps | op) + } + } + + def disableInterest(op: Int, connection: ActorRef) = + new Task { + def tryRun() { + val key = childrenKeys(connection.path.name) + key.interestOps(key.interestOps & ~op) + } + } + + def unregister(child: ActorRef) = + new Task { + def tryRun() { + childrenKeys = childrenKeys - child.path.name + } + } + + val select = new Task { + val doSelect: () ⇒ Int = + SelectTimeout match { + case Duration.Zero ⇒ () ⇒ selector.selectNow() + case Duration.Inf ⇒ () ⇒ selector.select() + case x ⇒ val millis = x.toMillis; () ⇒ selector.select(millis) + } + def tryRun() { + if (doSelect() > 0) { + val keys = selector.selectedKeys + val iterator = keys.iterator() + while (iterator.hasNext) { + val key = iterator.next + if (key.isValid) { + key.interestOps(0) // prevent immediate reselection by always clearing + val connection = key.attachment.asInstanceOf[ActorRef] + key.readyOps match { + case OP_READ ⇒ connection ! ChannelReadable + case OP_WRITE ⇒ connection ! ChannelWritable + case OP_READ_AND_WRITE ⇒ connection ! ChannelWritable; connection ! ChannelReadable + case x if (x & OP_ACCEPT) > 0 ⇒ connection ! ChannelAcceptable + case x if (x & OP_CONNECT) > 0 ⇒ connection ! ChannelConnectable + case x ⇒ log.warning("Invalid readyOps: {}", x) + } + } else log.warning("Invalid selection key: {}", key) + } + keys.clear() // we need to remove the selected keys from the set, otherwise they remain selected + } + selectorManagementDispatcher.execute(this) // re-schedules select behind all currently queued tasks + } + } + + selectorManagementDispatcher.execute(select) // start selection "loop" + + abstract class Task extends Runnable { + def tryRun() + def run() { + try tryRun() + catch { + case _: java.nio.channels.ClosedSelectorException ⇒ // ok, expected during shutdown + case NonFatal(e) ⇒ log.error(e, "Error during selector management task: {}", e) + } + } + } +} \ No newline at end of file diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index b6d78fc1d1..a82c01a56a 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -121,34 +121,19 @@ object UdpFF extends ExtensionKey[UdpFFExt] { class UdpFFExt(system: ExtendedActorSystem) extends IO.Extension { - val Settings = new Settings(system.settings.config.getConfig("akka.io.udpFF")) - class Settings private[UdpFFExt] (config: Config) { - import config._ + val settings = new Settings(system.settings.config.getConfig("akka.io.udpFF")) + class Settings private[UdpFFExt] (_config: Config) extends SelectionHandlerSettings(_config) { + import _config._ val NrOfSelectors = getInt("nr-of-selectors") - val MaxChannels = getString("max-channels") match { - case "unlimited" ⇒ -1 - case _ ⇒ getInt("max-channels") - } - val SelectTimeout = getString("select-timeout") match { - case "infinite" ⇒ Duration.Inf - case x ⇒ Duration(x) - } - val SelectorAssociationRetries = getInt("selector-association-retries") val DirectBufferSize = getIntBytes("direct-buffer-size") val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") - val SelectorDispatcher = getString("selector-dispatcher") - val WorkerDispatcher = getString("worker-dispatcher") val ManagementDispatcher = getString("management-dispatcher") - val TraceLogging = getBoolean("trace-logging") require(NrOfSelectors > 0, "nr-of-selectors must be > 0") - require(MaxChannels == -1 || MaxChannels > 0, "max-channels must be > 0 or 'unlimited'") - require(SelectTimeout >= Duration.Zero, "select-timeout must not be negative") - require(SelectorAssociationRetries >= 0, "selector-association-retries must be >= 0") - val MaxChannelsPerSelector = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) + override val MaxChannelsPerSelector = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) private[this] def getIntBytes(path: String): Int = { val size = getBytes(path) @@ -163,7 +148,7 @@ class UdpFFExt(system: ExtendedActorSystem) extends IO.Extension { name = "IO-UDP-FF") } - val bufferPool: BufferPool = new DirectByteBufferPool(Settings.DirectBufferSize, Settings.MaxDirectBufferPoolSize) + val bufferPool: BufferPool = new DirectByteBufferPool(settings.DirectBufferSize, settings.MaxDirectBufferPoolSize) } trait WithUdpFFBufferPool { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index f8b72e6f6c..f356163303 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -5,7 +5,7 @@ package akka.io import akka.actor.{ ActorLogging, Actor, ActorRef } import akka.io.UdpFF._ -import akka.io.UdpFFSelector._ +import akka.io.SelectionHandler._ import akka.util.ByteString import java.net.InetSocketAddress import java.nio.channels.DatagramChannel @@ -20,7 +20,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, val udpFF: UdpFFExt, options: immutable.Traversable[SocketOption]) extends Actor with ActorLogging with WithUdpFFBufferPool with WithUdpFFSend { - import udpFF.Settings._ + import udpFF.settings._ def selector: ActorRef = context.parent @@ -33,7 +33,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, socket.bind(endpoint) // will blow up the actor constructor if the bind fails datagramChannel } - context.parent ! RegisterDatagramChannel(channel, OP_READ) + context.parent ! RegisterChannel(channel, OP_READ) bindCommander ! Bound log.debug("Successfully bound to {}", endpoint) @@ -44,12 +44,12 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, case ResumeReading ⇒ selector ! ReadInterest case ChannelReadable ⇒ doReceive(handler, None) - case CommandFailed(RegisterDatagramChannel(datagramChannel, _)) ⇒ - log.warning("Could not bind to UDP port since selector capacity limit is reached, aborting bind") - try datagramChannel.close() - catch { - case NonFatal(e) ⇒ log.error(e, "Error closing channel") - } + // case CommandFailed(RegisterChannel(channel, _)) ⇒ + // log.warning("Could not bind to UDP port since selector capacity limit is reached, aborting bind") + // try channel.close() + // catch { + // case NonFatal(e) ⇒ log.error(e, "Error closing channel") + // } case Unbind ⇒ log.debug("Unbinding endpoint {}", endpoint) diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index f4c39fad1a..d699f7f18e 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -6,6 +6,7 @@ package akka.io import akka.actor.{ ActorRef, Props, Actor } import akka.io.UdpFF._ import akka.routing.RandomRouter +import akka.io.SelectionHandler.KickStartCommand /** * UdpFFManager is a facade for simple fire-and-forget style UDP operations @@ -45,15 +46,19 @@ import akka.routing.RandomRouter private[io] class UdpFFManager(udpFF: UdpFFExt) extends Actor { val selectorPool = context.actorOf( - props = Props(new UdpFFSelector(self, udpFF)).withRouter(RandomRouter(udpFF.Settings.NrOfSelectors)), + props = Props(new SelectionHandler(self, udpFF.settings)).withRouter(RandomRouter(udpFF.settings.NrOfSelectors)), name = "selectors") + // FIXME: fix close overs lazy val anonymousSender: ActorRef = context.actorOf( props = Props(new UdpFFSender(udpFF, selectorPool)), name = "simplesend") def receive = { - case c: Bind ⇒ selectorPool forward c + case Bind(handler, endpoint, options) ⇒ + val commander = sender + selectorPool forward KickStartCommand(Props( + new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options))) case SimpleSender ⇒ anonymousSender forward SimpleSender } diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala b/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala index 86ebbd2a94..ec151ade47 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala @@ -26,7 +26,7 @@ private[io] object UdpFFSelector { private[io] class UdpFFSelector(manager: ActorRef, udp: UdpFFExt) extends Actor with ActorLogging { import UdpFFSelector._ - import udp.Settings._ + import udp.settings._ @volatile var childrenKeys = immutable.HashMap.empty[String, SelectionKey] val sequenceNumber = Iterator from 0 diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala index 11218531d1..c1e23c4213 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala @@ -6,7 +6,7 @@ package akka.io import akka.actor._ import java.nio.channels.DatagramChannel import akka.io.UdpFF._ -import akka.io.UdpFFSelector.RegisterDatagramChannel +import akka.io.SelectionHandler.RegisterChannel /** * Base class for TcpIncomingConnection and TcpOutgoingConnection. @@ -19,7 +19,7 @@ private[io] class UdpFFSender(val udpFF: UdpFFExt, val selector: ActorRef) datagramChannel.configureBlocking(false) datagramChannel } - selector ! RegisterDatagramChannel(channel, 0) + selector ! RegisterChannel(channel, 0) def receive: Receive = internalReceive orElse sendHandlers diff --git a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala index 8e81f584fb..07ad4132e7 100644 --- a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala +++ b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala @@ -5,7 +5,7 @@ package akka.io import akka.actor.{ ActorRef, ActorLogging, Actor } import akka.io.UdpFF.{ CommandFailed, Send } -import akka.io.UdpFFSelector._ +import akka.io.SelectionHandler._ import java.nio.channels.DatagramChannel trait WithUdpFFSend { @@ -17,7 +17,7 @@ trait WithUdpFFSend { def selector: ActorRef def channel: DatagramChannel def udpFF: UdpFFExt - val settings = udpFF.Settings + val settings = udpFF.settings import settings._ From 8b4a3b0b9271bdb5b1efdcebb36a998c12ab21fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Fri, 1 Feb 2013 13:11:17 +0100 Subject: [PATCH 03/18] Another LIMBO commit, but TCP now uses the unified selector --- .../test/scala/akka/io/TcpListenerSpec.scala | 2 +- .../main/scala/akka/io/SelectionHandler.scala | 6 +- akka-actor/src/main/scala/akka/io/Tcp.scala | 18 +- .../main/scala/akka/io/TcpConnection.scala | 2 +- .../scala/akka/io/TcpIncomingConnection.scala | 2 + .../src/main/scala/akka/io/TcpListener.scala | 30 +-- .../src/main/scala/akka/io/TcpManager.scala | 12 +- .../scala/akka/io/TcpOutgoingConnection.scala | 6 +- .../src/main/scala/akka/io/TcpSelector.scala | 2 +- .../src/main/scala/akka/io/UdpFFManager.scala | 2 +- .../main/scala/akka/io/UdpFFSelector.scala | 186 ------------------ 11 files changed, 43 insertions(+), 225 deletions(-) delete mode 100644 akka-actor/src/main/scala/akka/io/UdpFFSelector.scala diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index 2a38c1547b..0ec8f792bd 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -94,7 +94,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { private class ListenerParent extends Actor { val listener = context.actorOf( props = Props(new TcpListener(selectorRouter.ref, handler.ref, endpoint, 100, bindCommander.ref, - Tcp(system).Settings, Nil)), + Tcp(system), Nil)), name = "test-listener-" + counter.next()) parent.watch(listener) def receive: Receive = { diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index e1f48de592..1389ea8c1f 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -43,6 +43,8 @@ abstract class SelectionHandlerSettings(config: Config) { private[io] object SelectionHandler { //FIXME: temporary case class KickStartCommand(childProps: Props) + // FIXME: all actors should listen to this + case object KickStartDone case class RegisterChannel(channel: SelectableChannel, initialOps: Int) case class Retry(command: KickStartCommand, retriesLeft: Int) { require(retriesLeft >= 0) } @@ -150,7 +152,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler // } def kickStart(cmd: KickStartCommand, retriesLeft: Int): Unit = withCapacityProtection(cmd, retriesLeft) { - spawnChild(cmd.childProps) // TODO: inject sender somehow + spawnChild(cmd.childProps) ! KickStartDone } def withCapacityProtection(cmd: KickStartCommand, retriesLeft: Int)(body: ⇒ Unit): Unit = { @@ -163,7 +165,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler } } - def spawnChild(props: Props) = + def spawnChild(props: Props): ActorRef = context.watch { context.actorOf( props = props.withDispatcher(WorkerDispatcher), diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index df3e3fe320..4b71c81676 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -179,19 +179,12 @@ object Tcp extends ExtensionKey[TcpExt] { class TcpExt(system: ExtendedActorSystem) extends IO.Extension { val Settings = new Settings(system.settings.config.getConfig("akka.io.tcp")) - class Settings private[TcpExt] (config: Config) { - import config._ + // FIXME: get away with subclassess + class Settings private[TcpExt] (_config: Config) extends SelectionHandlerSettings(_config) { + import _config._ val NrOfSelectors = getInt("nr-of-selectors") - val MaxChannels = getString("max-channels") match { - case "unlimited" ⇒ -1 - case _ ⇒ getInt("max-channels") - } - val SelectTimeout = getString("select-timeout") match { - case "infinite" ⇒ Duration.Inf - case x ⇒ Duration(x) - } - val SelectorAssociationRetries = getInt("selector-association-retries") + val BatchAcceptLimit = getInt("batch-accept-limit") val DirectBufferSize = getIntBytes("direct-buffer-size") val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") @@ -203,10 +196,7 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { case "unlimited" ⇒ Int.MaxValue case x ⇒ getIntBytes("received-message-size-limit") } - val SelectorDispatcher = getString("selector-dispatcher") - val WorkerDispatcher = getString("worker-dispatcher") val ManagementDispatcher = getString("management-dispatcher") - val TraceLogging = getBoolean("trace-logging") require(NrOfSelectors > 0, "nr-of-selectors must be > 0") require(MaxChannels == -1 || MaxChannels > 0, "max-channels must be > 0 or 'unlimited'") diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index a586881c67..60690e4b23 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -15,7 +15,7 @@ import scala.concurrent.duration._ import akka.actor._ import akka.util.ByteString import Tcp._ -import TcpSelector._ +import akka.io.SelectionHandler._ /** * Base class for TcpIncomingConnection and TcpOutgoingConnection. diff --git a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala index 1036509b4e..0c25b7f46b 100644 --- a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala @@ -8,6 +8,7 @@ import java.nio.channels.SocketChannel import scala.collection.immutable import akka.actor.ActorRef import Tcp.SocketOption +import akka.io.SelectionHandler.RegisterChannel /** * An actor handling the connection state machine for an incoming, already connected @@ -22,6 +23,7 @@ private[io] class TcpIncomingConnection(_channel: SocketChannel, context.watch(handler) // sign death pact completeConnect(handler, options) + context.parent ! RegisterChannel(channel, 0) def receive = PartialFunction.empty } diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index c110b65a39..2b23787fe9 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -5,12 +5,12 @@ package akka.io import java.net.InetSocketAddress -import java.nio.channels.ServerSocketChannel +import java.nio.channels.{ SelectionKey, ServerSocketChannel } import scala.annotation.tailrec import scala.collection.immutable import scala.util.control.NonFatal -import akka.actor.{ ActorLogging, ActorRef, Actor } -import TcpSelector._ +import akka.actor.{ Props, ActorLogging, ActorRef, Actor } +import akka.io.SelectionHandler._ import Tcp._ private[io] class TcpListener(selectorRouter: ActorRef, @@ -18,10 +18,11 @@ private[io] class TcpListener(selectorRouter: ActorRef, endpoint: InetSocketAddress, backlog: Int, bindCommander: ActorRef, - settings: TcpExt#Settings, + tcp: TcpExt, options: immutable.Traversable[SocketOption]) extends Actor with ActorLogging { def selector: ActorRef = context.parent + import tcp.Settings._ context.watch(handler) // sign death pact val channel = { @@ -32,25 +33,25 @@ private[io] class TcpListener(selectorRouter: ActorRef, socket.bind(endpoint, backlog) // will blow up the actor constructor if the bind fails serverSocketChannel } - context.parent ! RegisterServerSocketChannel(channel) + context.parent ! RegisterChannel(channel, SelectionKey.OP_ACCEPT) log.debug("Successfully bound to {}", endpoint) def receive: Receive = { - case Bound ⇒ + case KickStartDone ⇒ bindCommander ! Bound context.become(bound) } def bound: Receive = { case ChannelAcceptable ⇒ - acceptAllPending(settings.BatchAcceptLimit) + acceptAllPending(BatchAcceptLimit) - case CommandFailed(RegisterIncomingConnection(socketChannel, _, _)) ⇒ - log.warning("Could not register incoming connection since selector capacity limit is reached, closing connection") - try socketChannel.close() - catch { - case NonFatal(e) ⇒ log.error(e, "Error closing channel") - } + // case CommandFailed(RegisterIncomingConnection(socketChannel, _, _)) ⇒ + // log.warning("Could not register incoming connection since selector capacity limit is reached, closing connection") + // try socketChannel.close() + // catch { + // case NonFatal(e) ⇒ log.error(e, "Error closing channel") + // } case Unbind ⇒ log.debug("Unbinding endpoint {}", endpoint) @@ -70,7 +71,8 @@ private[io] class TcpListener(selectorRouter: ActorRef, if (socketChannel != null) { log.debug("New connection accepted") socketChannel.configureBlocking(false) - selectorRouter ! RegisterIncomingConnection(socketChannel, handler, options) + //selectorRouter ! RegisterIncomingConnection(socketChannel, handler, options) + selectorRouter ! KickStartCommand(Props(new TcpIncomingConnection(socketChannel, tcp, handler, options))) acceptAllPending(limit - 1) } } else context.parent ! AcceptInterest diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index 0ef1ca3e52..94e07e015f 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -7,6 +7,7 @@ package akka.io import akka.actor.{ ActorLogging, Actor, Props } import akka.routing.RandomRouter import Tcp._ +import akka.io.SelectionHandler.KickStartCommand /** * TcpManager is a facade for accepting commands ([[akka.io.Tcp.Command]]) to open client or server TCP connections. @@ -46,10 +47,17 @@ import Tcp._ private[io] class TcpManager(tcp: TcpExt) extends Actor with ActorLogging { val selectorPool = context.actorOf( - props = Props(new TcpSelector(self, tcp)).withRouter(RandomRouter(tcp.Settings.NrOfSelectors)), + props = Props(new SelectionHandler(self, tcp.Settings)).withRouter(RandomRouter(tcp.Settings.NrOfSelectors)), name = "selectors") def receive = { - case x @ (_: Connect | _: Bind) ⇒ selectorPool forward x + //case x @ (_: Connect | _: Bind) ⇒ selectorPool forward x + case Connect(remoteAddress, localAddress, options) ⇒ + val commander = sender + selectorPool ! KickStartCommand(Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options))) + + case Bind(handler, endpoint, backlog, options) ⇒ + val commander = sender + selectorPool ! KickStartCommand(Props(new TcpListener(selectorPool, handler, endpoint, backlog, commander, tcp, options))) } } diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 040d866e5b..1a04f6bc5c 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -6,10 +6,10 @@ package akka.io import java.net.InetSocketAddress import java.io.IOException -import java.nio.channels.SocketChannel +import java.nio.channels.{ SelectionKey, SocketChannel } import scala.collection.immutable import akka.actor.ActorRef -import TcpSelector._ +import akka.io.SelectionHandler._ import Tcp._ /** @@ -32,7 +32,7 @@ private[io] class TcpOutgoingConnection(_tcp: TcpExt, if (channel.connect(remoteAddress)) completeConnect(commander, options) else { - selector ! RegisterOutgoingConnection(channel) + selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) context.become(connecting(commander, options)) } diff --git a/akka-actor/src/main/scala/akka/io/TcpSelector.scala b/akka-actor/src/main/scala/akka/io/TcpSelector.scala index 4e0dd6f9a8..f9ec086b76 100644 --- a/akka-actor/src/main/scala/akka/io/TcpSelector.scala +++ b/akka-actor/src/main/scala/akka/io/TcpSelector.scala @@ -95,7 +95,7 @@ private[io] class TcpSelector(manager: ActorRef, tcp: TcpExt) extends Actor with withCapacityProtection(cmd, retriesLeft) { import cmd._ val commander = sender - spawnChild(() ⇒ new TcpListener(context.parent, handler, endpoint, backlog, commander, tcp.Settings, options)) + spawnChild(() ⇒ new TcpListener(context.parent, handler, endpoint, backlog, commander, tcp, options)) } def withCapacityProtection(cmd: Command, retriesLeft: Int)(body: ⇒ Unit): Unit = { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index d699f7f18e..0c58e78112 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -57,7 +57,7 @@ private[io] class UdpFFManager(udpFF: UdpFFExt) extends Actor { def receive = { case Bind(handler, endpoint, options) ⇒ val commander = sender - selectorPool forward KickStartCommand(Props( + selectorPool ! KickStartCommand(Props( new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options))) case SimpleSender ⇒ anonymousSender forward SimpleSender } diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala b/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala deleted file mode 100644 index ec151ade47..0000000000 --- a/akka-actor/src/main/scala/akka/io/UdpFFSelector.scala +++ /dev/null @@ -1,186 +0,0 @@ -/** - * Copyright (C) 2009-2013 Typesafe Inc. - */ -package akka.io - -import akka.io.UdpFF._ -import akka.actor._ -import java.lang.Runnable -import java.nio.channels.{ DatagramChannel, SelectionKey } -import java.nio.channels.SelectionKey._ -import java.nio.channels.spi.SelectorProvider -import scala.collection.immutable -import scala.concurrent.duration._ -import scala.util.control.NonFatal - -private[io] object UdpFFSelector { - case class Retry(command: Command, retriesLeft: Int) { require(retriesLeft >= 0) } - case class RegisterDatagramChannel(channel: DatagramChannel, initialOps: Int) extends Command - - case object ChannelReadable - case object ChannelWritable - case object ReadInterest - case object WriteInterest -} - -private[io] class UdpFFSelector(manager: ActorRef, udp: UdpFFExt) extends Actor with ActorLogging { - - import UdpFFSelector._ - import udp.settings._ - - @volatile var childrenKeys = immutable.HashMap.empty[String, SelectionKey] - val sequenceNumber = Iterator from 0 - val selectorManagementDispatcher = context.system.dispatchers.lookup(SelectorDispatcher) - val selector = SelectorProvider.provider.openSelector - val OP_READ_AND_WRITE = OP_READ + OP_WRITE // compile-time constant - - def receive: Receive = { - case WriteInterest ⇒ execute(enableInterest(OP_WRITE, sender)) - case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) - case StopReading ⇒ execute(disableInterest(OP_READ, sender)) - - case cmd: Bind ⇒ - handleBind(cmd, SelectorAssociationRetries) - - case RegisterDatagramChannel(channel, initialOps) ⇒ - execute(registerDatagramChannel(channel, sender, initialOps)) - - case Retry(command, 0) ⇒ - log.warning("Command '{}' failed since all selectors are at capacity", command) - sender ! CommandFailed(command) - - case Retry(cmd: Bind, retriesLeft) ⇒ - handleBind(cmd, retriesLeft) - - case Terminated(child) ⇒ - execute(unregister(child)) - } - - override def postStop() { - try { - try { - val iterator = selector.keys.iterator - while (iterator.hasNext) iterator.next().channel.close() - } finally selector.close() - } catch { - case NonFatal(e) ⇒ log.error(e, "Error closing selector or key") - } - } - - // we can never recover from failures of a connection or listener child - override def supervisorStrategy = SupervisorStrategy.stoppingStrategy - - def handleBind(cmd: Bind, retriesLeft: Int): Unit = - withCapacityProtection(cmd, retriesLeft) { - import cmd._ - val commander = sender - spawnChild(() ⇒ new UdpFFListener(context.parent, handler, endpoint, commander, udp, options)) - } - - def withCapacityProtection(cmd: Command, retriesLeft: Int)(body: ⇒ Unit): Unit = { - log.debug("Executing {}", cmd) - if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { - body - } else { - log.warning("Rejecting '{}' with {} retries left, retrying...", cmd, retriesLeft) - context.parent forward Retry(cmd, retriesLeft - 1) - } - } - - def spawnChild(creator: () ⇒ Actor) = - context.watch { - context.actorOf( - props = Props(creator, dispatcher = WorkerDispatcher), - name = sequenceNumber.next().toString) - } - - //////////////// Management Tasks scheduled via the selectorManagementDispatcher ///////////// - - def execute(task: Task): Unit = { - selectorManagementDispatcher.execute(task) - selector.wakeup() - } - - def updateKeyMap(child: ActorRef, key: SelectionKey): Unit = - childrenKeys = childrenKeys.updated(child.path.name, key) - - def registerDatagramChannel(channel: DatagramChannel, connection: ActorRef, initialOps: Int) = - new Task { - def tryRun() { - val key = channel.register(selector, initialOps, connection) - updateKeyMap(connection, key) - } - } - - // TODO: evaluate whether we could run the following two tasks directly on the TcpSelector actor itself rather than - // on the selector-management-dispatcher. The trade-off would be using a ConcurrentHashMap - // rather than an unsynchronized one, but since switching interest ops is so frequent - // the change might be beneficial, provided the underlying implementation really is thread-safe - // and behaves consistently on all platforms. - def enableInterest(op: Int, connection: ActorRef) = - new Task { - def tryRun() { - val key = childrenKeys(connection.path.name) - key.interestOps(key.interestOps | op) - } - } - - def disableInterest(op: Int, connection: ActorRef) = - new Task { - def tryRun() { - val key = childrenKeys(connection.path.name) - key.interestOps(key.interestOps & ~op) - } - } - - def unregister(child: ActorRef) = - new Task { - def tryRun() { - childrenKeys = childrenKeys - child.path.name - } - } - - val select = new Task { - val doSelect: () ⇒ Int = - SelectTimeout match { - case Duration.Zero ⇒ () ⇒ selector.selectNow() - case Duration.Inf ⇒ () ⇒ selector.select() - case x ⇒ val millis = x.toMillis; () ⇒ selector.select(millis) - } - def tryRun() { - if (doSelect() > 0) { - val keys = selector.selectedKeys - val iterator = keys.iterator() - while (iterator.hasNext) { - val key = iterator.next - if (key.isValid) { - key.interestOps(0) // prevent immediate reselection by always clearing - val connection = key.attachment.asInstanceOf[ActorRef] - key.readyOps match { - case OP_READ ⇒ connection ! ChannelReadable - case OP_WRITE ⇒ connection ! ChannelWritable - case OP_READ_AND_WRITE ⇒ connection ! ChannelWritable; connection ! ChannelReadable - case x ⇒ log.warning("Invalid readyOps: {}", x) - } - } else log.warning("Invalid selection key: {}", key) - } - keys.clear() // we need to remove the selected keys from the set, otherwise they remain selected - } - selectorManagementDispatcher.execute(this) // re-schedules select behind all currently queued tasks - } - } - - selectorManagementDispatcher.execute(select) // start selection "loop" - - abstract class Task extends Runnable { - def tryRun() - def run() { - try tryRun() - catch { - case _: java.nio.channels.ClosedSelectorException ⇒ // ok, expected during shutdown - case NonFatal(e) ⇒ log.error(e, "Error during selector management task: {}", e) - } - } - } -} - From 58ab585844ddc7f282a6e1ccdcafd75bdb3b937b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Mon, 4 Feb 2013 11:21:04 +0100 Subject: [PATCH 04/18] Various fixes to tests --- .../scala/akka/io/TcpConnectionSpec.scala | 9 +- .../test/scala/akka/io/TcpListenerSpec.scala | 30 ++--- .../main/scala/akka/io/SelectionHandler.scala | 105 ++++-------------- .../src/main/scala/akka/io/TcpListener.scala | 3 +- .../src/main/scala/akka/io/TcpManager.scala | 12 +- .../scala/akka/io/TcpOutgoingConnection.scala | 12 +- .../src/main/scala/akka/io/UdpFFManager.scala | 9 +- 7 files changed, 61 insertions(+), 119 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index c5d67a50be..08c7b745f2 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -15,13 +15,13 @@ import scala.concurrent.duration._ import scala.util.control.NonFatal import org.scalatest.matchers._ import Tcp._ -import TcpSelector._ +import akka.io.SelectionHandler._ import TestUtils._ import akka.actor.{ ActorRef, PoisonPill, Terminated } import akka.testkit.{ AkkaSpec, EventFilter, TestActorRef, TestProbe } import akka.util.ByteString import akka.actor.DeathPactException -import akka.actor.DeathPactException +import java.nio.channels.SelectionKey._ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") { val serverAddress = temporaryServerAddress() @@ -241,7 +241,8 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val buffer = ByteBuffer.allocate(1) val thrown = evaluating { serverSideChannel.read(buffer) } must produce[IOException] - thrown.getMessage must be("Connection reset by peer") + // FIXME: On windows this message is localized + //thrown.getMessage must be("Connection reset by peer") } "close the connection and reply with `ConfirmedClosed` upong reception of an `ConfirmedClose` command" in withEstablishedConnection(setSmallRcvBuffer) { setup ⇒ @@ -519,7 +520,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val connectionActor = connectionActorCons(selector.ref, userHandler.ref) val clientSideChannel = connectionActor.underlyingActor.channel - selector.expectMsg(RegisterOutgoingConnection(clientSideChannel)) + selector.expectMsg(RegisterChannel(clientSideChannel, OP_CONNECT)) body { UnacceptedSetup( diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index 0ec8f792bd..aa66dc160a 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -8,9 +8,10 @@ import java.net.Socket import scala.concurrent.duration._ import akka.actor.{ Terminated, SupervisorStrategy, Actor, Props } import akka.testkit.{ TestProbe, TestActorRef, AkkaSpec } -import TcpSelector._ import Tcp._ import akka.testkit.EventFilter +import akka.io.SelectionHandler._ +import java.nio.channels.SelectionKey._ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { @@ -19,7 +20,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { "register its ServerSocketChannel with its selector" in new TestSetup "let the Bind commander know when binding is completed" in new TestSetup { - listener ! Bound + listener ! KickStartDone bindCommander.expectMsg(Bound) } @@ -34,13 +35,14 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { listener ! ChannelAcceptable parent.expectMsg(AcceptInterest) - selectorRouter.expectMsgPF() { case RegisterIncomingConnection(_, `handlerRef`, Nil) ⇒ /* ok */ } - selectorRouter.expectMsgPF() { case RegisterIncomingConnection(_, `handlerRef`, Nil) ⇒ /* ok */ } + // FIXME: ugly stuff here + selectorRouter.expectMsgType[KickStartCommand] + selectorRouter.expectMsgType[KickStartCommand] selectorRouter.expectNoMsg(100.millis) // and pick up the last remaining connection on the next ChannelAcceptable listener ! ChannelAcceptable - selectorRouter.expectMsgPF() { case RegisterIncomingConnection(_, `handlerRef`, Nil) ⇒ /* ok */ } + selectorRouter.expectMsgType[KickStartCommand] } "react to Unbind commands by replying with Unbound and stopping itself" in new TestSetup { @@ -59,13 +61,15 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { attemptConnectionToEndpoint() listener ! ChannelAcceptable - val channel = selectorRouter.expectMsgType[RegisterIncomingConnection].channel - channel.isOpen must be(true) + val props = selectorRouter.expectMsgType[KickStartCommand].childProps + // FIXME: need to instantiate propss + //selectorRouter.expectMsgType[RegisterChannel].channel.isOpen must be(true) - EventFilter.warning(pattern = "selector capacity limit", occurrences = 1) intercept { - listener ! CommandFailed(RegisterIncomingConnection(channel, handler.ref, Nil)) - awaitCond(!channel.isOpen) - } + // FIXME: fix this + // EventFilter.warning(pattern = "selector capacity limit", occurrences = 1) intercept { + // //listener ! CommandFailed(RegisterIncomingConnection(channel, handler.ref, Nil)) + // awaitCond(!channel.isOpen) + // } } } @@ -80,10 +84,10 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { val endpoint = TestUtils.temporaryServerAddress() private val parentRef = TestActorRef(new ListenerParent) - parent.expectMsgType[RegisterServerSocketChannel] + parent.expectMsgType[RegisterChannel] def bindListener() { - listener ! Bound + listener ! KickStartDone bindCommander.expectMsg(Bound) } diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 1389ea8c1f..64d6b389f2 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -41,10 +41,12 @@ abstract class SelectionHandlerSettings(config: Config) { } private[io] object SelectionHandler { + //FIXME: temporary - case class KickStartCommand(childProps: Props) + case class KickStartCommand(apiCommand: Any, commander: ActorRef, childProps: Props) // FIXME: all actors should listen to this case object KickStartDone + case class KickStartFailed(apiCommand: Any, commander: ActorRef) case class RegisterChannel(channel: SelectableChannel, initialOps: Int) case class Retry(command: KickStartCommand, retriesLeft: Int) { require(retriesLeft >= 0) } @@ -75,42 +77,19 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler //case StopReading ⇒ execute(disableInterest(OP_READ, sender)) - // case cmd: RegisterIncomingConnection ⇒ - // handleIncomingConnection(cmd, SelectorAssociationRetries) - // - // case cmd: Connect ⇒ - // handleConnect(cmd, SelectorAssociationRetries) - // - // case cmd: Bind ⇒ - // handleBind(cmd, SelectorAssociationRetries) - case cmd: KickStartCommand ⇒ - kickStart(cmd, SelectorAssociationRetries) - - // case RegisterOutgoingConnection(channel) ⇒ - // execute(registerOutgoingConnection(channel, sender)) - // - // case RegisterServerSocketChannel(channel) ⇒ - // execute(registerListener(channel, sender)) + // FIXME: factor out to common + withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) ! KickStartDone } case RegisterChannel(channel, initialOps) ⇒ execute(registerChannel(channel, sender, initialOps)) - // case Retry(command, 0) ⇒ - // log.warning("Command '{}' failed since all selectors are at capacity", command) - // sender ! CommandFailed(command) + case Retry(cmd, 0) ⇒ + // FIXME: extractors + manager ! KickStartFailed(cmd.apiCommand, cmd.commander) case Retry(cmd, retriesLeft) ⇒ - kickStart(cmd, retriesLeft) - - // case Retry(cmd: RegisterIncomingConnection, retriesLeft) ⇒ - // handleIncomingConnection(cmd, retriesLeft) - // - // case Retry(cmd: Connect, retriesLeft) ⇒ - // handleConnect(cmd, retriesLeft) - // - // case Retry(cmd: Bind, retriesLeft) ⇒ - // handleBind(cmd, retriesLeft) + withCapacityProtection(cmd, retriesLeft) { spawnChild(cmd.childProps) ! KickStartDone } case Terminated(child) ⇒ execute(unregister(child)) @@ -118,43 +97,23 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler override def postStop() { try { - try { - val iterator = selector.keys.iterator - while (iterator.hasNext) iterator.next().channel.close() - } finally selector.close() + val iterator = selector.keys.iterator + while (iterator.hasNext) { + val key = iterator.next() + try key.channel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing channel") + } + } + selector.close() } catch { - case NonFatal(e) ⇒ log.error(e, "Error closing selector or key") + case NonFatal(e) ⇒ log.error(e, "Error closing selector") } } // we can never recover from failures of a connection or listener child override def supervisorStrategy = SupervisorStrategy.stoppingStrategy - // def handleIncomingConnection(cmd: RegisterIncomingConnection, retriesLeft: Int): Unit = - // withCapacityProtection(cmd, retriesLeft) { - // import cmd._ - // val connection = spawnChild(() ⇒ new TcpIncomingConnection(channel, tcp, handler, options)) - // execute(registerIncomingConnection(channel, connection)) - // } - // - // def handleConnect(cmd: Connect, retriesLeft: Int): Unit = - // withCapacityProtection(cmd, retriesLeft) { - // import cmd._ - // val commander = sender - // spawnChild(() ⇒ new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options)) - // } - // - // def handleBind(cmd: Bind, retriesLeft: Int): Unit = - // withCapacityProtection(cmd, retriesLeft) { - // import cmd._ - // val commander = sender - // spawnChild(() ⇒ new TcpListener(context.parent, handler, endpoint, backlog, commander, tcp.Settings, options)) - // } - - def kickStart(cmd: KickStartCommand, retriesLeft: Int): Unit = withCapacityProtection(cmd, retriesLeft) { - spawnChild(cmd.childProps) ! KickStartDone - } - def withCapacityProtection(cmd: KickStartCommand, retriesLeft: Int)(body: ⇒ Unit): Unit = { log.debug("Executing {}", cmd) if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { @@ -182,32 +141,6 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler def updateKeyMap(child: ActorRef, key: SelectionKey): Unit = childrenKeys = childrenKeys.updated(child.path.name, key) - // def registerOutgoingConnection(channel: SocketChannel, connection: ActorRef) = - // new Task { - // def tryRun() { - // val key = channel.register(selector, OP_CONNECT, connection) - // updateKeyMap(connection, key) - // } - // } - // - // def registerListener(channel: ServerSocketChannel, listener: ActorRef) = - // new Task { - // def tryRun() { - // val key = channel.register(selector, OP_ACCEPT, listener) - // updateKeyMap(listener, key) - // listener ! Bound - // } - // } - // - // def registerIncomingConnection(channel: SocketChannel, connection: ActorRef) = - // new Task { - // def tryRun() { - // // we only enable reading after the user-level connection handler has registered - // val key = channel.register(selector, 0, connection) - // updateKeyMap(connection, key) - // } - // } - def registerChannel(channel: SelectableChannel, channelActor: ActorRef, initialOps: Int): Task = new Task { def tryRun() { diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index 2b23787fe9..f3cc55d4a5 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -72,7 +72,8 @@ private[io] class TcpListener(selectorRouter: ActorRef, log.debug("New connection accepted") socketChannel.configureBlocking(false) //selectorRouter ! RegisterIncomingConnection(socketChannel, handler, options) - selectorRouter ! KickStartCommand(Props(new TcpIncomingConnection(socketChannel, tcp, handler, options))) + // FIXME null is not nice. There is no explicit API command here + selectorRouter ! KickStartCommand(null, context.system.deadLetters, Props(new TcpIncomingConnection(socketChannel, tcp, handler, options))) acceptAllPending(limit - 1) } } else context.parent ! AcceptInterest diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index 94e07e015f..f8dc6373ad 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -7,7 +7,7 @@ package akka.io import akka.actor.{ ActorLogging, Actor, Props } import akka.routing.RandomRouter import Tcp._ -import akka.io.SelectionHandler.KickStartCommand +import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } /** * TcpManager is a facade for accepting commands ([[akka.io.Tcp.Command]]) to open client or server TCP connections. @@ -52,12 +52,14 @@ private[io] class TcpManager(tcp: TcpExt) extends Actor with ActorLogging { def receive = { //case x @ (_: Connect | _: Bind) ⇒ selectorPool forward x - case Connect(remoteAddress, localAddress, options) ⇒ + case c @ Connect(remoteAddress, localAddress, options) ⇒ val commander = sender - selectorPool ! KickStartCommand(Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options))) + selectorPool ! KickStartCommand(c, commander, Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options))) - case Bind(handler, endpoint, backlog, options) ⇒ + case b @ Bind(handler, endpoint, backlog, options) ⇒ val commander = sender - selectorPool ! KickStartCommand(Props(new TcpListener(selectorPool, handler, endpoint, backlog, commander, tcp, options))) + selectorPool ! KickStartCommand(b, commander, Props(new TcpListener(selectorPool, handler, endpoint, backlog, commander, tcp, options))) + + case KickStartFailed(cmd: Command, commander) ⇒ commander ! CommandFailed(cmd) } } diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 1a04f6bc5c..2c0c766543 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -29,12 +29,12 @@ private[io] class TcpOutgoingConnection(_tcp: TcpExt, options.foreach(_.beforeConnect(channel.socket)) log.debug("Attempting connection to {}", remoteAddress) - if (channel.connect(remoteAddress)) - completeConnect(commander, options) - else { - selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) - context.become(connecting(commander, options)) - } + // if (channel.connect(remoteAddress)) + // completeConnect(commander, options) + // else { + selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) + context.become(connecting(commander, options)) + // } def receive: Receive = PartialFunction.empty diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index 0c58e78112..1a9311a43b 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -6,7 +6,7 @@ package akka.io import akka.actor.{ ActorRef, Props, Actor } import akka.io.UdpFF._ import akka.routing.RandomRouter -import akka.io.SelectionHandler.KickStartCommand +import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } /** * UdpFFManager is a facade for simple fire-and-forget style UDP operations @@ -55,11 +55,12 @@ private[io] class UdpFFManager(udpFF: UdpFFExt) extends Actor { name = "simplesend") def receive = { - case Bind(handler, endpoint, options) ⇒ + case b @ Bind(handler, endpoint, options) ⇒ val commander = sender - selectorPool ! KickStartCommand(Props( + selectorPool ! KickStartCommand(b, commander, Props( new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options))) - case SimpleSender ⇒ anonymousSender forward SimpleSender + case SimpleSender ⇒ anonymousSender forward SimpleSender + case KickStartFailed(cmd: Command, commander) ⇒ commander ! CommandFailed(cmd) } } From 946fb0eec418ebb7a9399d357fe7969d7adf4c4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Mon, 4 Feb 2013 16:24:34 +0100 Subject: [PATCH 05/18] Removed WithByteBuffer and friends --- .../scala/akka/io/DirectByteBufferPool.scala | 10 - .../main/scala/akka/io/TcpConnection.scala | 13 +- .../scala/akka/io/TcpIncomingConnection.scala | 2 +- .../scala/akka/io/TcpOutgoingConnection.scala | 12 +- .../src/main/scala/akka/io/TcpSelector.scala | 242 ------------------ akka-actor/src/main/scala/akka/io/UdpFF.scala | 10 - .../main/scala/akka/io/UdpFFListener.scala | 7 +- .../src/main/scala/akka/io/UdpFFSender.scala | 2 +- .../main/scala/akka/io/WithUdpFFSend.scala | 6 +- 9 files changed, 22 insertions(+), 282 deletions(-) delete mode 100644 akka-actor/src/main/scala/akka/io/TcpSelector.scala diff --git a/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala b/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala index 6d9699122f..cf2f573fd3 100644 --- a/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala +++ b/akka-actor/src/main/scala/akka/io/DirectByteBufferPool.scala @@ -8,16 +8,6 @@ import java.util.concurrent.atomic.AtomicBoolean import java.nio.ByteBuffer import annotation.tailrec -trait WithBufferPool { - def tcp: TcpExt - - def acquireBuffer(): ByteBuffer = - tcp.bufferPool.acquire() - - def releaseBuffer(buffer: ByteBuffer): Unit = - tcp.bufferPool.release(buffer) -} - trait BufferPool { def acquire(): ByteBuffer def release(buf: ByteBuffer) diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index 60690e4b23..b2dea0571c 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -21,8 +21,9 @@ import akka.io.SelectionHandler._ * Base class for TcpIncomingConnection and TcpOutgoingConnection. */ private[io] abstract class TcpConnection(val channel: SocketChannel, - val tcp: TcpExt) extends Actor with ActorLogging with WithBufferPool { + val tcp: TcpExt) extends Actor with ActorLogging { import tcp.Settings._ + import tcp.bufferPool import TcpConnection._ var pendingWrite: PendingWrite = null @@ -137,7 +138,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, } } else MoreDataWaiting(receivedData) - val buffer = acquireBuffer() + val buffer = bufferPool.acquire() try innerRead(buffer, ByteString.empty, ReceivedMessageSizeLimit) match { case NoData ⇒ if (TraceLogging) log.debug("Read nothing.") @@ -157,7 +158,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, doCloseConnection(handler, closeCommander, closeReason) } catch { case e: IOException ⇒ handleError(handler, e) - } finally releaseBuffer(buffer) + } finally bufferPool.release(buffer) } final def doWrite(handler: ActorRef): Unit = { @@ -179,7 +180,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, val buffer = pendingWrite.buffer pendingWrite = null - releaseBuffer(buffer) + bufferPool.release(buffer) } } @@ -256,7 +257,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, abort() if (writePending) - releaseBuffer(pendingWrite.buffer) + bufferPool.release(pendingWrite.buffer) if (closedMessage != null) { val interestedInClose = @@ -288,7 +289,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, def wantsAck = ack != NoAck } def createWrite(write: Write): PendingWrite = { - val buffer = acquireBuffer() + val buffer = bufferPool.acquire() val copied = write.data.copyToBuffer(buffer) buffer.flip() diff --git a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala index 0c25b7f46b..5da609c617 100644 --- a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala @@ -7,7 +7,7 @@ package akka.io import java.nio.channels.SocketChannel import scala.collection.immutable import akka.actor.ActorRef -import Tcp.SocketOption +import akka.io.Tcp.SocketOption import akka.io.SelectionHandler.RegisterChannel /** diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 2c0c766543..1a04f6bc5c 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -29,12 +29,12 @@ private[io] class TcpOutgoingConnection(_tcp: TcpExt, options.foreach(_.beforeConnect(channel.socket)) log.debug("Attempting connection to {}", remoteAddress) - // if (channel.connect(remoteAddress)) - // completeConnect(commander, options) - // else { - selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) - context.become(connecting(commander, options)) - // } + if (channel.connect(remoteAddress)) + completeConnect(commander, options) + else { + selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) + context.become(connecting(commander, options)) + } def receive: Receive = PartialFunction.empty diff --git a/akka-actor/src/main/scala/akka/io/TcpSelector.scala b/akka-actor/src/main/scala/akka/io/TcpSelector.scala deleted file mode 100644 index f9ec086b76..0000000000 --- a/akka-actor/src/main/scala/akka/io/TcpSelector.scala +++ /dev/null @@ -1,242 +0,0 @@ -/** - * Copyright (C) 2009-2012 Typesafe Inc. - */ - -package akka.io - -import java.lang.Runnable -import java.nio.channels.spi.SelectorProvider -import java.nio.channels.{ ServerSocketChannel, SelectionKey, SocketChannel } -import java.nio.channels.SelectionKey._ -import scala.util.control.NonFatal -import scala.collection.immutable -import scala.concurrent.duration._ -import akka.actor._ -import Tcp._ - -private[io] class TcpSelector(manager: ActorRef, tcp: TcpExt) extends Actor with ActorLogging { - import TcpSelector._ - import tcp.Settings._ - - @volatile var childrenKeys = immutable.HashMap.empty[String, SelectionKey] - val sequenceNumber = Iterator.from(0) - val selectorManagementDispatcher = context.system.dispatchers.lookup(SelectorDispatcher) - val selector = SelectorProvider.provider.openSelector - val OP_READ_AND_WRITE = OP_READ + OP_WRITE // compile-time constant - - def receive: Receive = { - case WriteInterest ⇒ execute(enableInterest(OP_WRITE, sender)) - case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) - case AcceptInterest ⇒ execute(enableInterest(OP_ACCEPT, sender)) - - case StopReading ⇒ execute(disableInterest(OP_READ, sender)) - - case cmd: RegisterIncomingConnection ⇒ - handleIncomingConnection(cmd, SelectorAssociationRetries) - - case cmd: Connect ⇒ - handleConnect(cmd, SelectorAssociationRetries) - - case cmd: Bind ⇒ - handleBind(cmd, SelectorAssociationRetries) - - case RegisterOutgoingConnection(channel) ⇒ - execute(registerOutgoingConnection(channel, sender)) - - case RegisterServerSocketChannel(channel) ⇒ - execute(registerListener(channel, sender)) - - case Retry(command, 0) ⇒ - log.warning("Command '{}' failed since all selectors are at capacity", command) - sender ! CommandFailed(command) - - case Retry(cmd: RegisterIncomingConnection, retriesLeft) ⇒ - handleIncomingConnection(cmd, retriesLeft) - - case Retry(cmd: Connect, retriesLeft) ⇒ - handleConnect(cmd, retriesLeft) - - case Retry(cmd: Bind, retriesLeft) ⇒ - handleBind(cmd, retriesLeft) - - case Terminated(child) ⇒ - execute(unregister(child)) - } - - override def postStop() { - try { - try { - val iterator = selector.keys.iterator - while (iterator.hasNext) iterator.next().channel.close() - } finally selector.close() - } catch { - case NonFatal(e) ⇒ log.error(e, "Error closing selector or key") - } - } - - // we can never recover from failures of a connection or listener child - override def supervisorStrategy = SupervisorStrategy.stoppingStrategy - - def handleIncomingConnection(cmd: RegisterIncomingConnection, retriesLeft: Int): Unit = - withCapacityProtection(cmd, retriesLeft) { - import cmd._ - val connection = spawnChild(() ⇒ new TcpIncomingConnection(channel, tcp, handler, options)) - execute(registerIncomingConnection(channel, connection)) - } - - def handleConnect(cmd: Connect, retriesLeft: Int): Unit = - withCapacityProtection(cmd, retriesLeft) { - import cmd._ - val commander = sender - spawnChild(() ⇒ new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options)) - } - - def handleBind(cmd: Bind, retriesLeft: Int): Unit = - withCapacityProtection(cmd, retriesLeft) { - import cmd._ - val commander = sender - spawnChild(() ⇒ new TcpListener(context.parent, handler, endpoint, backlog, commander, tcp, options)) - } - - def withCapacityProtection(cmd: Command, retriesLeft: Int)(body: ⇒ Unit): Unit = { - log.debug("Executing {}", cmd) - if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { - body - } else { - log.warning("Rejecting '{}' with {} retries left, retrying...", cmd, retriesLeft) - context.parent forward Retry(cmd, retriesLeft - 1) - } - } - - def spawnChild(creator: () ⇒ Actor) = - context.watch { - context.actorOf( - props = Props(creator, dispatcher = WorkerDispatcher), - name = sequenceNumber.next().toString) - } - - //////////////// Management Tasks scheduled via the selectorManagementDispatcher ///////////// - - def execute(task: Task): Unit = { - selectorManagementDispatcher.execute(task) - selector.wakeup() - } - - def updateKeyMap(child: ActorRef, key: SelectionKey): Unit = - childrenKeys = childrenKeys.updated(child.path.name, key) - - def registerOutgoingConnection(channel: SocketChannel, connection: ActorRef) = - new Task { - def tryRun() { - val key = channel.register(selector, OP_CONNECT, connection) - updateKeyMap(connection, key) - } - } - - def registerListener(channel: ServerSocketChannel, listener: ActorRef) = - new Task { - def tryRun() { - val key = channel.register(selector, OP_ACCEPT, listener) - updateKeyMap(listener, key) - listener ! Bound - } - } - - def registerIncomingConnection(channel: SocketChannel, connection: ActorRef) = - new Task { - def tryRun() { - // we only enable reading after the user-level connection handler has registered - val key = channel.register(selector, 0, connection) - updateKeyMap(connection, key) - } - } - - // TODO: evaluate whether we could run the following two tasks directly on the TcpSelector actor itself rather than - // on the selector-management-dispatcher. The trade-off would be using a ConcurrentHashMap - // rather than an unsynchronized one, but since switching interest ops is so frequent - // the change might be beneficial, provided the underlying implementation really is thread-safe - // and behaves consistently on all platforms. - def enableInterest(op: Int, connection: ActorRef) = - new Task { - def tryRun() { - val key = childrenKeys(connection.path.name) - key.interestOps(key.interestOps | op) - } - } - - def disableInterest(op: Int, connection: ActorRef) = - new Task { - def tryRun() { - val key = childrenKeys(connection.path.name) - key.interestOps(key.interestOps & ~op) - } - } - - def unregister(child: ActorRef) = - new Task { - def tryRun() { - childrenKeys = childrenKeys - child.path.name - } - } - - val select = new Task { - val doSelect: () ⇒ Int = - SelectTimeout match { - case Duration.Zero ⇒ () ⇒ selector.selectNow() - case Duration.Inf ⇒ () ⇒ selector.select() - case x ⇒ val millis = x.toMillis; () ⇒ selector.select(millis) - } - def tryRun() { - if (doSelect() > 0) { - val keys = selector.selectedKeys - val iterator = keys.iterator() - while (iterator.hasNext) { - val key = iterator.next - if (key.isValid) { - key.interestOps(0) // prevent immediate reselection by always clearing - val connection = key.attachment.asInstanceOf[ActorRef] - key.readyOps match { - case OP_READ ⇒ connection ! ChannelReadable - case OP_WRITE ⇒ connection ! ChannelWritable - case OP_READ_AND_WRITE ⇒ connection ! ChannelWritable; connection ! ChannelReadable - case x if (x & OP_ACCEPT) > 0 ⇒ connection ! ChannelAcceptable - case x if (x & OP_CONNECT) > 0 ⇒ connection ! ChannelConnectable - case x ⇒ log.warning("Invalid readyOps: {}", x) - } - } else log.warning("Invalid selection key: {}", key) - } - keys.clear() // we need to remove the selected keys from the set, otherwise they remain selected - } - selectorManagementDispatcher.execute(this) // re-schedules select behind all currently queued tasks - } - } - - selectorManagementDispatcher.execute(select) // start selection "loop" - - abstract class Task extends Runnable { - def tryRun() - def run() { - try tryRun() - catch { - case _: java.nio.channels.ClosedSelectorException ⇒ // ok, expected during shutdown - case NonFatal(e) ⇒ log.error(e, "Error during selector management task: {}", e) - } - } - } -} - -private[io] object TcpSelector { - case class RegisterOutgoingConnection(channel: SocketChannel) - case class RegisterServerSocketChannel(channel: ServerSocketChannel) - case class RegisterIncomingConnection(channel: SocketChannel, handler: ActorRef, - options: immutable.Traversable[SocketOption]) extends Tcp.Command - case class Retry(command: Command, retriesLeft: Int) { require(retriesLeft >= 0) } - - case object ChannelConnectable - case object ChannelAcceptable - case object ChannelReadable - case object ChannelWritable - case object AcceptInterest - case object ReadInterest - case object WriteInterest -} diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index a82c01a56a..6d9274e191 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -149,14 +149,4 @@ class UdpFFExt(system: ExtendedActorSystem) extends IO.Extension { } val bufferPool: BufferPool = new DirectByteBufferPool(settings.DirectBufferSize, settings.MaxDirectBufferPoolSize) -} - -trait WithUdpFFBufferPool { - def udpFF: UdpFFExt - - def acquireBuffer(): ByteBuffer = - udpFF.bufferPool.acquire() - - def releaseBuffer(buffer: ByteBuffer): Unit = - udpFF.bufferPool.release(buffer) } \ No newline at end of file diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index f356163303..a481559e07 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -19,8 +19,9 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, bindCommander: ActorRef, val udpFF: UdpFFExt, options: immutable.Traversable[SocketOption]) - extends Actor with ActorLogging with WithUdpFFBufferPool with WithUdpFFSend { + extends Actor with ActorLogging with WithUdpFFSend { import udpFF.settings._ + import udpFF.bufferPool def selector: ActorRef = context.parent @@ -60,7 +61,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, } def doReceive(handler: ActorRef, closeCommander: Option[ActorRef]): Unit = { - val buffer = acquireBuffer() + val buffer = bufferPool.acquire() try { buffer.clear() buffer.limit(DirectBufferSize) @@ -73,7 +74,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, } selector ! ReadInterest - } finally releaseBuffer(buffer) + } finally bufferPool.release(buffer) } override def postStop() { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala index c1e23c4213..4e6245c160 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala @@ -12,7 +12,7 @@ import akka.io.SelectionHandler.RegisterChannel * Base class for TcpIncomingConnection and TcpOutgoingConnection. */ private[io] class UdpFFSender(val udpFF: UdpFFExt, val selector: ActorRef) - extends Actor with ActorLogging with WithUdpFFBufferPool with WithUdpFFSend { + extends Actor with ActorLogging with WithUdpFFSend { val channel = { val datagramChannel = DatagramChannel.open diff --git a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala index 07ad4132e7..da837c35fd 100644 --- a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala +++ b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala @@ -9,7 +9,7 @@ import akka.io.SelectionHandler._ import java.nio.channels.DatagramChannel trait WithUdpFFSend { - me: Actor with ActorLogging with WithUdpFFBufferPool ⇒ + me: Actor with ActorLogging ⇒ var pendingSend: (Send, ActorRef) = null def writePending = pendingSend ne null @@ -41,7 +41,7 @@ trait WithUdpFFSend { final def doSend(): Unit = { - val buffer = acquireBuffer() + val buffer = udpFF.bufferPool.acquire() try { val (send, commander) = pendingSend buffer.clear() @@ -55,7 +55,7 @@ trait WithUdpFFSend { else if (send.wantsAck) commander ! send.ack } finally { - releaseBuffer(buffer) + udpFF.bufferPool.release(buffer) pendingSend = null } From 1ec065b0cd33ab147bfaf7417c27de5cd997cd9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Tue, 5 Feb 2013 11:48:47 +0100 Subject: [PATCH 06/18] Factored out common manager code and SocketOptions --- .../test/scala/akka/io/IntegrationSpec.scala | 5 +- .../akka/io/IntegrationSpecSupport.scala | 1 + .../scala/akka/io/TcpConnectionSpec.scala | 7 +- akka-actor/src/main/scala/akka/io/IO.scala | 23 +++++- akka-actor/src/main/scala/akka/io/Inet.scala | 82 +++++++++++++++++++ akka-actor/src/main/scala/akka/io/Tcp.scala | 72 +--------------- .../main/scala/akka/io/TcpConnection.scala | 3 +- .../scala/akka/io/TcpIncomingConnection.scala | 2 +- .../src/main/scala/akka/io/TcpListener.scala | 5 +- .../src/main/scala/akka/io/TcpManager.scala | 22 ++--- .../scala/akka/io/TcpOutgoingConnection.scala | 3 +- akka-actor/src/main/scala/akka/io/Udp.scala | 24 ++++++ .../src/main/scala/akka/io/UdpConn.scala | 21 +++++ akka-actor/src/main/scala/akka/io/UdpFF.scala | 70 +--------------- .../main/scala/akka/io/UdpFFListener.scala | 3 +- .../src/main/scala/akka/io/UdpFFManager.scala | 18 ++-- 16 files changed, 188 insertions(+), 173 deletions(-) create mode 100644 akka-actor/src/main/scala/akka/io/Inet.scala create mode 100644 akka-actor/src/main/scala/akka/io/Udp.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpConn.scala diff --git a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala index e4d53f5f9b..1e7a40eb90 100644 --- a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala @@ -6,6 +6,7 @@ package akka.io import akka.testkit.AkkaSpec import akka.util.ByteString +import akka.io.Inet import Tcp._ import TestUtils._ import akka.testkit.EventFilter @@ -64,8 +65,8 @@ class IntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with IntegrationS expectReceivedData(clientHandler, 100000) - override def bindOptions = List(SO.SendBufferSize(1024)) - override def connectOptions = List(SO.ReceiveBufferSize(1024)) + override def bindOptions = List(Inet.SO.SendBufferSize(1024)) + override def connectOptions = List(Inet.SO.ReceiveBufferSize(1024)) } } diff --git a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala b/akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala index 0feeb3809f..692815b96a 100644 --- a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala +++ b/akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala @@ -8,6 +8,7 @@ import scala.annotation.tailrec import akka.testkit.{ AkkaSpec, TestProbe } import akka.actor.ActorRef import scala.collection.immutable +import akka.io.Inet.SocketOption import Tcp._ import TestUtils._ diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index 08c7b745f2..a59f2ccad4 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -22,6 +22,7 @@ import akka.testkit.{ AkkaSpec, EventFilter, TestActorRef, TestProbe } import akka.util.ByteString import akka.actor.DeathPactException import java.nio.channels.SelectionKey._ +import akka.io.Inet.SocketOption class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") { val serverAddress = temporaryServerAddress() @@ -33,7 +34,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val userHandler = TestProbe() val selector = TestProbe() val connectionActor = - createConnectionActor(options = Vector(SO.ReuseAddress(true)))(selector.ref, userHandler.ref) + createConnectionActor(options = Vector(Inet.SO.ReuseAddress(true)))(selector.ref, userHandler.ref) val clientChannel = connectionActor.underlyingActor.channel clientChannel.socket.getReuseAddress must be(true) } @@ -65,7 +66,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") } "bundle incoming Received messages as long as more data is available" in withEstablishedConnection( - clientSocketOptions = List(SO.ReceiveBufferSize(1000000)) // to make sure enough data gets through + clientSocketOptions = List(Inet.SO.ReceiveBufferSize(1000000)) // to make sure enough data gets through ) { setup ⇒ import setup._ @@ -567,7 +568,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") def createConnectionActor( serverAddress: InetSocketAddress = serverAddress, localAddress: Option[InetSocketAddress] = None, - options: immutable.Seq[Tcp.SocketOption] = Nil)( + options: immutable.Seq[SocketOption] = Nil)( _selector: ActorRef, commander: ActorRef): TestActorRef[TcpOutgoingConnection] = { diff --git a/akka-actor/src/main/scala/akka/io/IO.scala b/akka-actor/src/main/scala/akka/io/IO.scala index e787f1295b..2b6cbd9f57 100644 --- a/akka-actor/src/main/scala/akka/io/IO.scala +++ b/akka-actor/src/main/scala/akka/io/IO.scala @@ -4,7 +4,9 @@ package akka.io -import akka.actor.{ ActorRef, ActorSystem, ExtensionKey } +import akka.actor._ +import akka.routing.RandomRouter +import akka.io.SelectionHandler.KickStartCommand object IO { @@ -14,4 +16,23 @@ object IO { def apply[T <: Extension](key: ExtensionKey[T])(implicit system: ActorSystem): ActorRef = key(system).manager + abstract class SelectorBasedManager(selectorSettings: SelectionHandlerSettings, nrOfSelectors: Int) extends Actor { + + val selectorPool = context.actorOf( + props = Props(new SelectionHandler(self, selectorSettings)).withRouter(RandomRouter(nrOfSelectors)), + name = "selectors") + + def createKickStart(pf: PartialFunction[Any, Props], cmd: Any): PartialFunction[Any, KickStartCommand] = { + pf.andThen { props ⇒ + val commander = sender + KickStartCommand(cmd, commander, props) + } + } + + def kickStartReceive(pf: PartialFunction[Any, Props]): Receive = { + //case KickStartFailed = + case cmd if pf.isDefinedAt(cmd) ⇒ selectorPool ! createKickStart(pf, cmd)(cmd) + } + } + } \ No newline at end of file diff --git a/akka-actor/src/main/scala/akka/io/Inet.scala b/akka-actor/src/main/scala/akka/io/Inet.scala new file mode 100644 index 0000000000..9e53507284 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/Inet.scala @@ -0,0 +1,82 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import java.net.{ DatagramSocket, Socket, ServerSocket } + +object Inet { + + /** + * SocketOption is a package of data (from the user) and associated + * behavior (how to apply that to a socket). + */ + trait SocketOption { + + def beforeDatagramBind(ds: DatagramSocket): Unit = () + + def beforeServerSocketBind(ss: ServerSocket): Unit = () + + /** + * Action to be taken for this option before calling connect() + */ + def beforeConnect(s: Socket): Unit = () + /** + * Action to be taken for this option after connect returned (i.e. on + * the slave socket for servers). + */ + def afterConnect(s: Socket): Unit = () + } + + object SO { + + /** + * [[akka.io.Tcp.SocketOption]] to set the SO_RCVBUF option + * + * For more information see [[java.net.Socket.setReceiveBufferSize]] + */ + case class ReceiveBufferSize(size: Int) extends SocketOption { + require(size > 0, "ReceiveBufferSize must be > 0") + override def beforeServerSocketBind(s: ServerSocket): Unit = s.setReceiveBufferSize(size) + override def beforeDatagramBind(s: DatagramSocket): Unit = s.setReceiveBufferSize(size) + override def beforeConnect(s: Socket): Unit = s.setReceiveBufferSize(size) + } + + // server socket options + + /** + * [[akka.io.Tcp.SocketOption]] to enable or disable SO_REUSEADDR + * + * For more information see [[java.net.Socket.setReuseAddress]] + */ + case class ReuseAddress(on: Boolean) extends SocketOption { + override def beforeServerSocketBind(s: ServerSocket): Unit = s.setReuseAddress(on) + override def beforeDatagramBind(s: DatagramSocket): Unit = s.setReuseAddress(on) + override def beforeConnect(s: Socket): Unit = s.setReuseAddress(on) + } + + /** + * [[akka.io.Tcp.SocketOption]] to set the SO_SNDBUF option. + * + * For more information see [[java.net.Socket.setSendBufferSize]] + */ + case class SendBufferSize(size: Int) extends SocketOption { + require(size > 0, "SendBufferSize must be > 0") + override def afterConnect(s: Socket): Unit = s.setSendBufferSize(size) + } + + /** + * [[akka.io.Tcp.SocketOption]] to set the traffic class or + * type-of-service octet in the IP header for packets sent from this + * socket. + * + * For more information see [[java.net.Socket.setTrafficClass]] + */ + case class TrafficClass(tc: Int) extends SocketOption { + require(0 <= tc && tc <= 255, "TrafficClass needs to be in the interval [0, 255]") + override def afterConnect(s: Socket): Unit = s.setTrafficClass(tc) + } + + } + +} diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index 4b71c81676..f7a31a76fe 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -6,7 +6,7 @@ package akka.io import java.net.InetSocketAddress import java.net.Socket -import java.net.ServerSocket +import akka.io.Inet.SocketOption import com.typesafe.config.Config import scala.concurrent.duration._ import scala.collection.immutable @@ -18,56 +18,13 @@ object Tcp extends ExtensionKey[TcpExt] { // Java API override def get(system: ActorSystem): TcpExt = system.extension(this) - /** - * SocketOption is a package of data (from the user) and associated - * behavior (how to apply that to a socket). - */ - sealed trait SocketOption { - /** - * Action to be taken for this option before calling bind() - */ - def beforeBind(s: ServerSocket): Unit = () - /** - * Action to be taken for this option before calling connect() - */ - def beforeConnect(s: Socket): Unit = () - /** - * Action to be taken for this option after connect returned (i.e. on - * the slave socket for servers). - */ - def afterConnect(s: Socket): Unit = () - } - // shared socket options object SO { - /** - * [[akka.io.Tcp.SocketOption]] to set the SO_RCVBUF option - * - * For more information see [[java.net.Socket.setReceiveBufferSize]] - */ - case class ReceiveBufferSize(size: Int) extends SocketOption { - require(size > 0, "ReceiveBufferSize must be > 0") - override def beforeBind(s: ServerSocket): Unit = s.setReceiveBufferSize(size) - override def beforeConnect(s: Socket): Unit = s.setReceiveBufferSize(size) - } - - // server socket options - - /** - * [[akka.io.Tcp.SocketOption]] to enable or disable SO_REUSEADDR - * - * For more information see [[java.net.Socket.setReuseAddress]] - */ - case class ReuseAddress(on: Boolean) extends SocketOption { - override def beforeBind(s: ServerSocket): Unit = s.setReuseAddress(on) - override def beforeConnect(s: Socket): Unit = s.setReuseAddress(on) - } - // general socket options /** - * [[akka.io.Tcp.SocketOption]] to enable or disable SO_KEEPALIVE + * [[akka.io.Inet.SocketOption]] to enable or disable SO_KEEPALIVE * * For more information see [[java.net.Socket.setKeepAlive]] */ @@ -76,7 +33,7 @@ object Tcp extends ExtensionKey[TcpExt] { } /** - * [[akka.io.Tcp.SocketOption]] to enable or disable OOBINLINE (receipt + * [[akka.io.Inet.SocketOption]] to enable or disable OOBINLINE (receipt * of TCP urgent data) By default, this option is disabled and TCP urgent * data is silently discarded. * @@ -86,20 +43,10 @@ object Tcp extends ExtensionKey[TcpExt] { override def afterConnect(s: Socket): Unit = s.setOOBInline(on) } - /** - * [[akka.io.Tcp.SocketOption]] to set the SO_SNDBUF option. - * - * For more information see [[java.net.Socket.setSendBufferSize]] - */ - case class SendBufferSize(size: Int) extends SocketOption { - require(size > 0, "SendBufferSize must be > 0") - override def afterConnect(s: Socket): Unit = s.setSendBufferSize(size) - } - // SO_LINGER is handled by the Close code /** - * [[akka.io.Tcp.SocketOption]] to enable or disable TCP_NODELAY + * [[akka.io.Inet.SocketOption]] to enable or disable TCP_NODELAY * (disable or enable Nagle's algorithm) * * For more information see [[java.net.Socket.setTcpNoDelay]] @@ -108,17 +55,6 @@ object Tcp extends ExtensionKey[TcpExt] { override def afterConnect(s: Socket): Unit = s.setTcpNoDelay(on) } - /** - * [[akka.io.Tcp.SocketOption]] to set the traffic class or - * type-of-service octet in the IP header for packets sent from this - * socket. - * - * For more information see [[java.net.Socket.setTrafficClass]] - */ - case class TrafficClass(tc: Int) extends SocketOption { - require(0 <= tc && tc <= 255, "TrafficClass needs to be in the interval [0, 255]") - override def afterConnect(s: Socket): Unit = s.setTrafficClass(tc) - } } /// COMMANDS diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index b2dea0571c..b331ef0622 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -14,7 +14,8 @@ import scala.util.control.NonFatal import scala.concurrent.duration._ import akka.actor._ import akka.util.ByteString -import Tcp._ +import akka.io.Inet.SocketOption +import akka.io.Tcp._ import akka.io.SelectionHandler._ /** diff --git a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala index 5da609c617..ea2703c40e 100644 --- a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala @@ -7,7 +7,7 @@ package akka.io import java.nio.channels.SocketChannel import scala.collection.immutable import akka.actor.ActorRef -import akka.io.Tcp.SocketOption +import akka.io.Inet.SocketOption import akka.io.SelectionHandler.RegisterChannel /** diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index f3cc55d4a5..541d101327 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -11,7 +11,8 @@ import scala.collection.immutable import scala.util.control.NonFatal import akka.actor.{ Props, ActorLogging, ActorRef, Actor } import akka.io.SelectionHandler._ -import Tcp._ +import akka.io.Inet.SocketOption +import akka.io.Tcp._ private[io] class TcpListener(selectorRouter: ActorRef, handler: ActorRef, @@ -29,7 +30,7 @@ private[io] class TcpListener(selectorRouter: ActorRef, val serverSocketChannel = ServerSocketChannel.open serverSocketChannel.configureBlocking(false) val socket = serverSocketChannel.socket - options.foreach(_.beforeBind(socket)) + options.foreach(_.beforeServerSocketBind(socket)) socket.bind(endpoint, backlog) // will blow up the actor constructor if the bind fails serverSocketChannel } diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index f8dc6373ad..a6d3cc95ab 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -8,6 +8,7 @@ import akka.actor.{ ActorLogging, Actor, Props } import akka.routing.RandomRouter import Tcp._ import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } +import akka.io.IO.SelectorBasedManager /** * TcpManager is a facade for accepting commands ([[akka.io.Tcp.Command]]) to open client or server TCP connections. @@ -44,22 +45,15 @@ import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } * with a [[akka.io.Tcp.CommandFailed]] message. This message contains the original command for reference. * */ -private[io] class TcpManager(tcp: TcpExt) extends Actor with ActorLogging { +private[io] class TcpManager(tcp: TcpExt) extends SelectorBasedManager(tcp.Settings, tcp.Settings.NrOfSelectors) with ActorLogging { - val selectorPool = context.actorOf( - props = Props(new SelectionHandler(self, tcp.Settings)).withRouter(RandomRouter(tcp.Settings.NrOfSelectors)), - name = "selectors") - - def receive = { - //case x @ (_: Connect | _: Bind) ⇒ selectorPool forward x - case c @ Connect(remoteAddress, localAddress, options) ⇒ + def receive = kickStartReceive { + case Connect(remoteAddress, localAddress, options) ⇒ val commander = sender - selectorPool ! KickStartCommand(c, commander, Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options))) - - case b @ Bind(handler, endpoint, backlog, options) ⇒ + Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options)) + case Bind(handler, endpoint, backlog, options) ⇒ val commander = sender - selectorPool ! KickStartCommand(b, commander, Props(new TcpListener(selectorPool, handler, endpoint, backlog, commander, tcp, options))) - - case KickStartFailed(cmd: Command, commander) ⇒ commander ! CommandFailed(cmd) + Props(new TcpListener(selectorPool, handler, endpoint, backlog, commander, tcp, options)) } + } diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 1a04f6bc5c..2c28bbada2 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -10,7 +10,8 @@ import java.nio.channels.{ SelectionKey, SocketChannel } import scala.collection.immutable import akka.actor.ActorRef import akka.io.SelectionHandler._ -import Tcp._ +import akka.io.Inet.SocketOption +import akka.io.Tcp._ /** * An actor handling the connection state machine for an outgoing connection diff --git a/akka-actor/src/main/scala/akka/io/Udp.scala b/akka-actor/src/main/scala/akka/io/Udp.scala new file mode 100644 index 0000000000..c543cf4927 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/Udp.scala @@ -0,0 +1,24 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import java.net.DatagramSocket +import akka.io.Inet.SocketOption + +object Udp { + + object SO { + + /** + * [[akka.io.Inet.SocketOption]] to set the SO_BROADCAST option + * + * For more information see [[java.net.DatagramSocket#setBroadcast]] + */ + case class Broadcast(on: Boolean) extends SocketOption { + override def beforeDatagramBind(s: DatagramSocket): Unit = s.setBroadcast(on) + } + + } + +} diff --git a/akka-actor/src/main/scala/akka/io/UdpConn.scala b/akka-actor/src/main/scala/akka/io/UdpConn.scala new file mode 100644 index 0000000000..651953e65e --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpConn.scala @@ -0,0 +1,21 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor.{ ExtendedActorSystem, Props, ActorSystemImpl, ExtensionKey } + +object UdpConn extends ExtensionKey[UdpConnExt] { + +} + +class UdpConnExt(system: ExtendedActorSystem) extends IO.Extension { + + val manager = { + system.asInstanceOf[ActorSystemImpl].systemActorOf( + props = Props.empty, + name = "IO-UDP-CONN") + } + +} + diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index 6d9274e191..31913dce3d 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -5,82 +5,16 @@ package akka.io import akka.actor._ import akka.util.ByteString -import java.net.{ DatagramSocket, Socket, InetSocketAddress } +import java.net.{ DatagramSocket, InetSocketAddress } import scala.collection.immutable import com.typesafe.config.Config -import scala.concurrent.duration.Duration -import java.nio.ByteBuffer +import akka.io.Inet.SocketOption object UdpFF extends ExtensionKey[UdpFFExt] { // Java API override def get(system: ActorSystem): UdpFFExt = system.extension(this) - /** - * SocketOption is a package of data (from the user) and associated - * behavior (how to apply that to a socket). - */ - sealed trait SocketOption { - /** - * Action to be taken for this option before calling bind() - */ - def beforeBind(s: DatagramSocket): Unit = () - - } - - object SO { - - /** - * [[akka.io.UdpFF.SocketOption]] to set the SO_BROADCAST option - * - * For more information see [[java.net.DatagramSocket#setBroadcast]] - */ - case class Broadcast(on: Boolean) extends SocketOption { - override def beforeBind(s: DatagramSocket): Unit = s.setBroadcast(on) - } - - /** - * [[akka.io.UdpFF.SocketOption]] to set the SO_RCVBUF option - * - * For more information see [[java.net.Socket#setReceiveBufferSize]] - */ - case class ReceiveBufferSize(size: Int) extends SocketOption { - require(size > 0, "ReceiveBufferSize must be > 0") - override def beforeBind(s: DatagramSocket): Unit = s.setReceiveBufferSize(size) - } - - /** - * [[akka.io.UdpFF.SocketOption]] to enable or disable SO_REUSEADDR - * - * For more information see [[java.net.Socket#setReuseAddress]] - */ - case class ReuseAddress(on: Boolean) extends SocketOption { - override def beforeBind(s: DatagramSocket): Unit = s.setReuseAddress(on) - } - - /** - * [[akka.io.UdpFF.SocketOption]] to set the SO_SNDBUF option. - * - * For more information see [[java.net.Socket#setSendBufferSize]] - */ - case class SendBufferSize(size: Int) extends SocketOption { - require(size > 0, "SendBufferSize must be > 0") - override def beforeBind(s: DatagramSocket): Unit = s.setSendBufferSize(size) - } - - /** - * [[akka.io.UdpFF.SocketOption]] to set the traffic class or - * type-of-service octet in the IP header for packets sent from this - * socket. - * - * For more information see [[java.net.Socket#setTrafficClass]] - */ - case class TrafficClass(tc: Int) extends SocketOption { - require(0 <= tc && tc <= 255, "TrafficClass needs to be in the interval [0, 255]") - override def beforeBind(s: DatagramSocket): Unit = s.setTrafficClass(tc) - } - } - trait Command case object NoAck diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index a481559e07..c3600ff121 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -5,6 +5,7 @@ package akka.io import akka.actor.{ ActorLogging, Actor, ActorRef } import akka.io.UdpFF._ +import akka.io.Inet.SocketOption import akka.io.SelectionHandler._ import akka.util.ByteString import java.net.InetSocketAddress @@ -30,7 +31,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, val datagramChannel = DatagramChannel.open datagramChannel.configureBlocking(false) val socket = datagramChannel.socket - options.foreach(_.beforeBind(socket)) + options.foreach(_.beforeDatagramBind(socket)) socket.bind(endpoint) // will blow up the actor constructor if the bind fails datagramChannel } diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index 1a9311a43b..be417166d0 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -7,6 +7,7 @@ import akka.actor.{ ActorRef, Props, Actor } import akka.io.UdpFF._ import akka.routing.RandomRouter import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } +import akka.io.IO.SelectorBasedManager /** * UdpFFManager is a facade for simple fire-and-forget style UDP operations @@ -43,24 +44,19 @@ import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } * discarded. * */ -private[io] class UdpFFManager(udpFF: UdpFFExt) extends Actor { - - val selectorPool = context.actorOf( - props = Props(new SelectionHandler(self, udpFF.settings)).withRouter(RandomRouter(udpFF.settings.NrOfSelectors)), - name = "selectors") +private[io] class UdpFFManager(udpFF: UdpFFExt) extends SelectorBasedManager(udpFF.settings, udpFF.settings.NrOfSelectors) { // FIXME: fix close overs lazy val anonymousSender: ActorRef = context.actorOf( props = Props(new UdpFFSender(udpFF, selectorPool)), name = "simplesend") - def receive = { - case b @ Bind(handler, endpoint, options) ⇒ + def receive = kickStartReceive { + case Bind(handler, endpoint, options) ⇒ val commander = sender - selectorPool ! KickStartCommand(b, commander, Props( - new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options))) - case SimpleSender ⇒ anonymousSender forward SimpleSender - case KickStartFailed(cmd: Command, commander) ⇒ commander ! CommandFailed(cmd) + Props(new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options)) + } orElse { + case SimpleSender ⇒ anonymousSender forward SimpleSender } } From 3505a7e76becce98553782866b51eec944011dfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Tue, 5 Feb 2013 12:17:26 +0100 Subject: [PATCH 07/18] Failed commands in SelectionHandler are now notified in a nicer way. --- .../test/scala/akka/io/TcpListenerSpec.scala | 12 +++---- akka-actor/src/main/scala/akka/io/IO.scala | 17 ++++++---- .../main/scala/akka/io/SelectionHandler.scala | 23 +++++++------ akka-actor/src/main/scala/akka/io/Tcp.scala | 6 ++-- .../src/main/scala/akka/io/TcpListener.scala | 32 ++++++++++++------- .../src/main/scala/akka/io/TcpManager.scala | 4 +-- akka-actor/src/main/scala/akka/io/UdpFF.scala | 4 ++- .../src/main/scala/akka/io/UdpFFManager.scala | 6 ++-- 8 files changed, 58 insertions(+), 46 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index aa66dc160a..da60c7880a 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -20,7 +20,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { "register its ServerSocketChannel with its selector" in new TestSetup "let the Bind commander know when binding is completed" in new TestSetup { - listener ! KickStartDone + listener ! WorkerForCommandDone bindCommander.expectMsg(Bound) } @@ -36,13 +36,13 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { parent.expectMsg(AcceptInterest) // FIXME: ugly stuff here - selectorRouter.expectMsgType[KickStartCommand] - selectorRouter.expectMsgType[KickStartCommand] + selectorRouter.expectMsgType[WorkerForCommand] + selectorRouter.expectMsgType[WorkerForCommand] selectorRouter.expectNoMsg(100.millis) // and pick up the last remaining connection on the next ChannelAcceptable listener ! ChannelAcceptable - selectorRouter.expectMsgType[KickStartCommand] + selectorRouter.expectMsgType[WorkerForCommand] } "react to Unbind commands by replying with Unbound and stopping itself" in new TestSetup { @@ -61,7 +61,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { attemptConnectionToEndpoint() listener ! ChannelAcceptable - val props = selectorRouter.expectMsgType[KickStartCommand].childProps + val props = selectorRouter.expectMsgType[WorkerForCommand].childProps // FIXME: need to instantiate propss //selectorRouter.expectMsgType[RegisterChannel].channel.isOpen must be(true) @@ -87,7 +87,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { parent.expectMsgType[RegisterChannel] def bindListener() { - listener ! KickStartDone + listener ! WorkerForCommandDone bindCommander.expectMsg(Bound) } diff --git a/akka-actor/src/main/scala/akka/io/IO.scala b/akka-actor/src/main/scala/akka/io/IO.scala index 2b6cbd9f57..8f152fe303 100644 --- a/akka-actor/src/main/scala/akka/io/IO.scala +++ b/akka-actor/src/main/scala/akka/io/IO.scala @@ -6,7 +6,7 @@ package akka.io import akka.actor._ import akka.routing.RandomRouter -import akka.io.SelectionHandler.KickStartCommand +import akka.io.SelectionHandler.WorkerForCommand object IO { @@ -16,22 +16,25 @@ object IO { def apply[T <: Extension](key: ExtensionKey[T])(implicit system: ActorSystem): ActorRef = key(system).manager + trait HasFailureMessage { + def failureMessage: Any + } + abstract class SelectorBasedManager(selectorSettings: SelectionHandlerSettings, nrOfSelectors: Int) extends Actor { val selectorPool = context.actorOf( props = Props(new SelectionHandler(self, selectorSettings)).withRouter(RandomRouter(nrOfSelectors)), name = "selectors") - def createKickStart(pf: PartialFunction[Any, Props], cmd: Any): PartialFunction[Any, KickStartCommand] = { - pf.andThen { props ⇒ + private def createKickStart(pf: PartialFunction[HasFailureMessage, Props]): PartialFunction[HasFailureMessage, WorkerForCommand] = { + case cmd ⇒ + val props = pf(cmd) val commander = sender - KickStartCommand(cmd, commander, props) - } + WorkerForCommand(cmd, commander, props) } def kickStartReceive(pf: PartialFunction[Any, Props]): Receive = { - //case KickStartFailed = - case cmd if pf.isDefinedAt(cmd) ⇒ selectorPool ! createKickStart(pf, cmd)(cmd) + case cmd: HasFailureMessage if pf.isDefinedAt(cmd) ⇒ selectorPool ! createKickStart(pf)(cmd) } } diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 64d6b389f2..daadb0c8b5 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -14,6 +14,7 @@ import scala.concurrent.duration._ import akka.actor._ import com.typesafe.config.Config import akka.actor.Terminated +import akka.io.IO.HasFailureMessage abstract class SelectionHandlerSettings(config: Config) { import config._ @@ -42,14 +43,12 @@ abstract class SelectionHandlerSettings(config: Config) { private[io] object SelectionHandler { - //FIXME: temporary - case class KickStartCommand(apiCommand: Any, commander: ActorRef, childProps: Props) + case class WorkerForCommand(apiCommand: HasFailureMessage, commander: ActorRef, childProps: Props) // FIXME: all actors should listen to this - case object KickStartDone - case class KickStartFailed(apiCommand: Any, commander: ActorRef) + case object WorkerForCommandDone case class RegisterChannel(channel: SelectableChannel, initialOps: Int) - case class Retry(command: KickStartCommand, retriesLeft: Int) { require(retriesLeft >= 0) } + case class Retry(command: WorkerForCommand, retriesLeft: Int) { require(retriesLeft >= 0) } case object ChannelConnectable case object ChannelAcceptable @@ -75,21 +74,21 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) case AcceptInterest ⇒ execute(enableInterest(OP_ACCEPT, sender)) + // FIXME: provide StopReading functionality //case StopReading ⇒ execute(disableInterest(OP_READ, sender)) - case cmd: KickStartCommand ⇒ + case cmd: WorkerForCommand ⇒ // FIXME: factor out to common - withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) ! KickStartDone } + withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) ! WorkerForCommandDone } case RegisterChannel(channel, initialOps) ⇒ execute(registerChannel(channel, sender, initialOps)) - case Retry(cmd, 0) ⇒ - // FIXME: extractors - manager ! KickStartFailed(cmd.apiCommand, cmd.commander) + case Retry(WorkerForCommand(cmd, commander, _), 0) ⇒ + commander ! cmd.failureMessage case Retry(cmd, retriesLeft) ⇒ - withCapacityProtection(cmd, retriesLeft) { spawnChild(cmd.childProps) ! KickStartDone } + withCapacityProtection(cmd, retriesLeft) { spawnChild(cmd.childProps) ! WorkerForCommandDone } case Terminated(child) ⇒ execute(unregister(child)) @@ -114,7 +113,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler // we can never recover from failures of a connection or listener child override def supervisorStrategy = SupervisorStrategy.stoppingStrategy - def withCapacityProtection(cmd: KickStartCommand, retriesLeft: Int)(body: ⇒ Unit): Unit = { + def withCapacityProtection(cmd: WorkerForCommand, retriesLeft: Int)(body: ⇒ Unit): Unit = { log.debug("Executing {}", cmd) if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { body diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index f7a31a76fe..625cbd1e7a 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -6,7 +6,7 @@ package akka.io import java.net.InetSocketAddress import java.net.Socket -import akka.io.Inet.SocketOption +import akka.io.Inet._ import com.typesafe.config.Config import scala.concurrent.duration._ import scala.collection.immutable @@ -58,7 +58,9 @@ object Tcp extends ExtensionKey[TcpExt] { } /// COMMANDS - trait Command + trait Command extends IO.HasFailureMessage { + def failureMessage = CommandFailed(this) + } case class Connect(remoteAddress: InetSocketAddress, localAddress: Option[InetSocketAddress] = None, diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index 541d101327..e883310ae3 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -5,7 +5,7 @@ package akka.io import java.net.InetSocketAddress -import java.nio.channels.{ SelectionKey, ServerSocketChannel } +import java.nio.channels.{ SocketChannel, SelectionKey, ServerSocketChannel } import scala.annotation.tailrec import scala.collection.immutable import scala.util.control.NonFatal @@ -13,6 +13,17 @@ import akka.actor.{ Props, ActorLogging, ActorRef, Actor } import akka.io.SelectionHandler._ import akka.io.Inet.SocketOption import akka.io.Tcp._ +import akka.io.IO.HasFailureMessage + +private[io] object TcpListener { + + case class RegisterIncoming(channel: SocketChannel) extends HasFailureMessage { + def failureMessage = FailedRegisterIncoming(channel) + } + + case class FailedRegisterIncoming(channel: SocketChannel) + +} private[io] class TcpListener(selectorRouter: ActorRef, handler: ActorRef, @@ -23,6 +34,7 @@ private[io] class TcpListener(selectorRouter: ActorRef, options: immutable.Traversable[SocketOption]) extends Actor with ActorLogging { def selector: ActorRef = context.parent + import TcpListener._ import tcp.Settings._ context.watch(handler) // sign death pact @@ -38,7 +50,7 @@ private[io] class TcpListener(selectorRouter: ActorRef, log.debug("Successfully bound to {}", endpoint) def receive: Receive = { - case KickStartDone ⇒ + case WorkerForCommandDone ⇒ bindCommander ! Bound context.become(bound) } @@ -47,12 +59,12 @@ private[io] class TcpListener(selectorRouter: ActorRef, case ChannelAcceptable ⇒ acceptAllPending(BatchAcceptLimit) - // case CommandFailed(RegisterIncomingConnection(socketChannel, _, _)) ⇒ - // log.warning("Could not register incoming connection since selector capacity limit is reached, closing connection") - // try socketChannel.close() - // catch { - // case NonFatal(e) ⇒ log.error(e, "Error closing channel") - // } + case FailedRegisterIncoming(socketChannel) ⇒ + log.warning("Could not register incoming connection since selector capacity limit is reached, closing connection") + try socketChannel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing channel") + } case Unbind ⇒ log.debug("Unbinding endpoint {}", endpoint) @@ -72,9 +84,7 @@ private[io] class TcpListener(selectorRouter: ActorRef, if (socketChannel != null) { log.debug("New connection accepted") socketChannel.configureBlocking(false) - //selectorRouter ! RegisterIncomingConnection(socketChannel, handler, options) - // FIXME null is not nice. There is no explicit API command here - selectorRouter ! KickStartCommand(null, context.system.deadLetters, Props(new TcpIncomingConnection(socketChannel, tcp, handler, options))) + selectorRouter ! WorkerForCommand(RegisterIncoming(socketChannel), self, Props(new TcpIncomingConnection(socketChannel, tcp, handler, options))) acceptAllPending(limit - 1) } } else context.parent ! AcceptInterest diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index a6d3cc95ab..81d3f91fa2 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -4,10 +4,8 @@ package akka.io -import akka.actor.{ ActorLogging, Actor, Props } -import akka.routing.RandomRouter import Tcp._ -import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } +import akka.actor.{ ActorLogging, Props } import akka.io.IO.SelectorBasedManager /** diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index 31913dce3d..0d6c49b83e 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -15,7 +15,9 @@ object UdpFF extends ExtensionKey[UdpFFExt] { // Java API override def get(system: ActorSystem): UdpFFExt = system.extension(this) - trait Command + trait Command extends IO.HasFailureMessage { + def failureMessage = CommandFailed(this) + } case object NoAck case class Send(payload: ByteString, target: InetSocketAddress, ack: Any) extends Command { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index be417166d0..4499cb8115 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -3,11 +3,9 @@ */ package akka.io -import akka.actor.{ ActorRef, Props, Actor } -import akka.io.UdpFF._ -import akka.routing.RandomRouter -import akka.io.SelectionHandler.{ KickStartFailed, KickStartCommand } +import akka.actor.{ ActorRef, Props } import akka.io.IO.SelectorBasedManager +import akka.io.UdpFF._ /** * UdpFFManager is a facade for simple fire-and-forget style UDP operations From 78a9e81a6b6ea7dc10cbd49b43b46dfa33b0e290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Tue, 5 Feb 2013 13:26:27 +0100 Subject: [PATCH 08/18] Eliminated KickStartDone and using ChannelRegistered --- .../test/scala/akka/io/TcpListenerSpec.scala | 4 ++-- akka-actor/src/main/scala/akka/io/IO.scala | 6 +++--- .../main/scala/akka/io/SelectionHandler.scala | 8 ++++---- .../scala/akka/io/TcpIncomingConnection.scala | 7 ++++--- .../src/main/scala/akka/io/TcpListener.scala | 2 +- .../src/main/scala/akka/io/TcpManager.scala | 2 +- .../scala/akka/io/TcpOutgoingConnection.scala | 17 +++++++++-------- .../src/main/scala/akka/io/UdpFFListener.scala | 15 ++++++--------- .../src/main/scala/akka/io/UdpFFManager.scala | 2 +- .../src/main/scala/akka/io/UdpFFSender.scala | 9 ++++++--- 10 files changed, 37 insertions(+), 35 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index da60c7880a..e68cc6536e 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -20,7 +20,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { "register its ServerSocketChannel with its selector" in new TestSetup "let the Bind commander know when binding is completed" in new TestSetup { - listener ! WorkerForCommandDone + listener ! ChannelRegistered bindCommander.expectMsg(Bound) } @@ -87,7 +87,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { parent.expectMsgType[RegisterChannel] def bindListener() { - listener ! WorkerForCommandDone + listener ! ChannelRegistered bindCommander.expectMsg(Bound) } diff --git a/akka-actor/src/main/scala/akka/io/IO.scala b/akka-actor/src/main/scala/akka/io/IO.scala index 8f152fe303..5b10023990 100644 --- a/akka-actor/src/main/scala/akka/io/IO.scala +++ b/akka-actor/src/main/scala/akka/io/IO.scala @@ -26,15 +26,15 @@ object IO { props = Props(new SelectionHandler(self, selectorSettings)).withRouter(RandomRouter(nrOfSelectors)), name = "selectors") - private def createKickStart(pf: PartialFunction[HasFailureMessage, Props]): PartialFunction[HasFailureMessage, WorkerForCommand] = { + private def createWorkerMessage(pf: PartialFunction[HasFailureMessage, Props]): PartialFunction[HasFailureMessage, WorkerForCommand] = { case cmd ⇒ val props = pf(cmd) val commander = sender WorkerForCommand(cmd, commander, props) } - def kickStartReceive(pf: PartialFunction[Any, Props]): Receive = { - case cmd: HasFailureMessage if pf.isDefinedAt(cmd) ⇒ selectorPool ! createKickStart(pf)(cmd) + def workerForCommand(pf: PartialFunction[Any, Props]): Receive = { + case cmd: HasFailureMessage if pf.isDefinedAt(cmd) ⇒ selectorPool ! createWorkerMessage(pf)(cmd) } } diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index daadb0c8b5..59b0894543 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -44,10 +44,9 @@ abstract class SelectionHandlerSettings(config: Config) { private[io] object SelectionHandler { case class WorkerForCommand(apiCommand: HasFailureMessage, commander: ActorRef, childProps: Props) - // FIXME: all actors should listen to this - case object WorkerForCommandDone case class RegisterChannel(channel: SelectableChannel, initialOps: Int) + case object ChannelRegistered case class Retry(command: WorkerForCommand, retriesLeft: Int) { require(retriesLeft >= 0) } case object ChannelConnectable @@ -79,7 +78,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler case cmd: WorkerForCommand ⇒ // FIXME: factor out to common - withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) ! WorkerForCommandDone } + withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) } case RegisterChannel(channel, initialOps) ⇒ execute(registerChannel(channel, sender, initialOps)) @@ -88,7 +87,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler commander ! cmd.failureMessage case Retry(cmd, retriesLeft) ⇒ - withCapacityProtection(cmd, retriesLeft) { spawnChild(cmd.childProps) ! WorkerForCommandDone } + withCapacityProtection(cmd, retriesLeft) { spawnChild(cmd.childProps) } case Terminated(child) ⇒ execute(unregister(child)) @@ -144,6 +143,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler new Task { def tryRun() { updateKeyMap(channelActor, channel.register(selector, initialOps, channelActor)) + channelActor ! ChannelRegistered } } diff --git a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala index ea2703c40e..2f7cf9c5fa 100644 --- a/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpIncomingConnection.scala @@ -8,7 +8,7 @@ import java.nio.channels.SocketChannel import scala.collection.immutable import akka.actor.ActorRef import akka.io.Inet.SocketOption -import akka.io.SelectionHandler.RegisterChannel +import akka.io.SelectionHandler.{ ChannelRegistered, RegisterChannel } /** * An actor handling the connection state machine for an incoming, already connected @@ -22,8 +22,9 @@ private[io] class TcpIncomingConnection(_channel: SocketChannel, context.watch(handler) // sign death pact - completeConnect(handler, options) context.parent ! RegisterChannel(channel, 0) - def receive = PartialFunction.empty + def receive = { + case ChannelRegistered ⇒ completeConnect(handler, options) + } } diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index e883310ae3..356319286f 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -50,7 +50,7 @@ private[io] class TcpListener(selectorRouter: ActorRef, log.debug("Successfully bound to {}", endpoint) def receive: Receive = { - case WorkerForCommandDone ⇒ + case ChannelRegistered ⇒ bindCommander ! Bound context.become(bound) } diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index 81d3f91fa2..8761104ba5 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -45,7 +45,7 @@ import akka.io.IO.SelectorBasedManager */ private[io] class TcpManager(tcp: TcpExt) extends SelectorBasedManager(tcp.Settings, tcp.Settings.NrOfSelectors) with ActorLogging { - def receive = kickStartReceive { + def receive = workerForCommand { case Connect(remoteAddress, localAddress, options) ⇒ val commander = sender Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options)) diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 2c28bbada2..6c9231fa46 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -28,17 +28,18 @@ private[io] class TcpOutgoingConnection(_tcp: TcpExt, localAddress.foreach(channel.socket.bind) options.foreach(_.beforeConnect(channel.socket)) + selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) - log.debug("Attempting connection to {}", remoteAddress) - if (channel.connect(remoteAddress)) - completeConnect(commander, options) - else { - selector ! RegisterChannel(channel, SelectionKey.OP_CONNECT) - context.become(connecting(commander, options)) + def receive: Receive = { + case ChannelRegistered ⇒ + log.debug("Attempting connection to {}", remoteAddress) + if (channel.connect(remoteAddress)) + completeConnect(commander, options) + else { + context.become(connecting(commander, options)) + } } - def receive: Receive = PartialFunction.empty - def connecting(commander: ActorRef, options: immutable.Traversable[SocketOption]): Receive = { case ChannelConnectable ⇒ try { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index c3600ff121..cfafb8bc52 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -13,6 +13,8 @@ import java.nio.channels.DatagramChannel import java.nio.channels.SelectionKey._ import scala.collection.immutable import scala.util.control.NonFatal +import akka.io.UdpFF.Received +import akka.io.SelectionHandler.RegisterChannel private[io] class UdpFFListener(selectorRouter: ActorRef, handler: ActorRef, @@ -39,20 +41,15 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, bindCommander ! Bound log.debug("Successfully bound to {}", endpoint) - def receive: Receive = receiveInternal orElse sendHandlers + def receive: Receive = { + case ChannelRegistered ⇒ context.become(readHandlers orElse sendHandlers, discardOld = true) + } - def receiveInternal: Receive = { + def readHandlers: Receive = { case StopReading ⇒ selector ! StopReading case ResumeReading ⇒ selector ! ReadInterest case ChannelReadable ⇒ doReceive(handler, None) - // case CommandFailed(RegisterChannel(channel, _)) ⇒ - // log.warning("Could not bind to UDP port since selector capacity limit is reached, aborting bind") - // try channel.close() - // catch { - // case NonFatal(e) ⇒ log.error(e, "Error closing channel") - // } - case Unbind ⇒ log.debug("Unbinding endpoint {}", endpoint) channel.close() diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index 4499cb8115..3f5c677991 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -49,7 +49,7 @@ private[io] class UdpFFManager(udpFF: UdpFFExt) extends SelectorBasedManager(udp props = Props(new UdpFFSender(udpFF, selectorPool)), name = "simplesend") - def receive = kickStartReceive { + def receive = workerForCommand { case Bind(handler, endpoint, options) ⇒ val commander = sender Props(new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options)) diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala index 4e6245c160..24e222e71c 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala @@ -6,7 +6,7 @@ package akka.io import akka.actor._ import java.nio.channels.DatagramChannel import akka.io.UdpFF._ -import akka.io.SelectionHandler.RegisterChannel +import akka.io.SelectionHandler.{ ChannelRegistered, RegisterChannel } /** * Base class for TcpIncomingConnection and TcpOutgoingConnection. @@ -21,9 +21,12 @@ private[io] class UdpFFSender(val udpFF: UdpFFExt, val selector: ActorRef) } selector ! RegisterChannel(channel, 0) - def receive: Receive = internalReceive orElse sendHandlers + def receive: Receive = { + case ChannelRegistered ⇒ context.become(simpleSendHandlers orElse sendHandlers, discardOld = true) + case _ ⇒ sender ! SimpleSendReady // FIXME: queueing here? + } - def internalReceive: Receive = { + def simpleSendHandlers: Receive = { case SimpleSender ⇒ sender ! SimpleSendReady } From 98a707bd57ee848f5f1cdb2405e96bb0d9743799 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Tue, 5 Feb 2013 13:38:27 +0100 Subject: [PATCH 09/18] Fixed temporarily disabled StopReading operation --- akka-actor/src/main/scala/akka/io/SelectionHandler.scala | 5 ++--- akka-actor/src/main/scala/akka/io/Tcp.scala | 1 - akka-actor/src/main/scala/akka/io/TcpConnection.scala | 6 +++--- akka-actor/src/main/scala/akka/io/UdpFFListener.scala | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 59b0894543..5c3d7c6251 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -55,6 +55,7 @@ private[io] object SelectionHandler { case object ChannelWritable case object AcceptInterest case object ReadInterest + case object DisableReadInterest case object WriteInterest } @@ -73,11 +74,9 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) case AcceptInterest ⇒ execute(enableInterest(OP_ACCEPT, sender)) - // FIXME: provide StopReading functionality - //case StopReading ⇒ execute(disableInterest(OP_READ, sender)) + case DisableReadInterest ⇒ execute(disableInterest(OP_READ, sender)) case cmd: WorkerForCommand ⇒ - // FIXME: factor out to common withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) } case RegisterChannel(channel, initialOps) ⇒ diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index 625cbd1e7a..38c8051714 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -117,7 +117,6 @@ object Tcp extends ExtensionKey[TcpExt] { class TcpExt(system: ExtendedActorSystem) extends IO.Extension { val Settings = new Settings(system.settings.config.getConfig("akka.io.tcp")) - // FIXME: get away with subclassess class Settings private[TcpExt] (_config: Config) extends SelectionHandlerSettings(_config) { import _config._ diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index b331ef0622..dffec75307 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -60,7 +60,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, /** normal connected state */ def connected(handler: ActorRef): Receive = { - case StopReading ⇒ selector ! StopReading + case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest case ChannelReadable ⇒ doRead(handler, None) @@ -83,7 +83,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, /** connection is closing but a write has to be finished first */ def closingWithPendingWrite(handler: ActorRef, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Receive = { - case StopReading ⇒ selector ! StopReading + case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest case ChannelReadable ⇒ doRead(handler, closeCommander) @@ -97,7 +97,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, /** connection is closed on our side and we're waiting from confirmation from the other side */ def closing(handler: ActorRef, closeCommander: Option[ActorRef]): Receive = { - case StopReading ⇒ selector ! StopReading + case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest case ChannelReadable ⇒ doRead(handler, closeCommander) case Abort ⇒ handleClose(handler, Some(sender), Aborted) diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index cfafb8bc52..0d79f64e83 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -46,7 +46,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, } def readHandlers: Receive = { - case StopReading ⇒ selector ! StopReading + case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest case ChannelReadable ⇒ doReceive(handler, None) From e2ce4644f1ebf9914593759036fc12030db8d041 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Tue, 5 Feb 2013 15:48:29 +0100 Subject: [PATCH 10/18] Added connection style UDP (not working fully yet) --- .../akka/io/UdpConnIntegrationSpec.scala | 76 +++++++++++ akka-actor/src/main/resources/reference.conf | 59 ++++++++- .../main/scala/akka/io/SelectionHandler.scala | 8 +- akka-actor/src/main/scala/akka/io/Udp.scala | 22 +++ .../src/main/scala/akka/io/UdpConn.scala | 49 ++++++- .../main/scala/akka/io/UdpConnManager.scala | 18 +++ .../main/scala/akka/io/UdpConnection.scala | 125 ++++++++++++++++++ akka-actor/src/main/scala/akka/io/UdpFF.scala | 33 +---- .../main/scala/akka/io/UdpFFListener.scala | 20 +-- .../main/scala/akka/io/WithUdpFFSend.scala | 2 +- 10 files changed, 365 insertions(+), 47 deletions(-) create mode 100644 akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpConnManager.scala create mode 100644 akka-actor/src/main/scala/akka/io/UdpConnection.scala diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala new file mode 100644 index 0000000000..90bfdb222e --- /dev/null +++ b/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala @@ -0,0 +1,76 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.testkit.{ TestProbe, ImplicitSender, AkkaSpec } +import TestUtils._ +import akka.util.ByteString +import java.net.InetSocketAddress +import akka.actor.ActorRef + +class UdpConnIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with ImplicitSender { + + def bindUdp(handler: ActorRef): (InetSocketAddress, ActorRef) = { + val address = temporaryServerAddress() + val commander = TestProbe() + commander.send(IO(UdpFF), UdpFF.Bind(handler, address)) + commander.expectMsg(UdpFF.Bound) + (address, commander.sender) + } + + def connectUdp(localAddress: Option[InetSocketAddress], remoteAddress: InetSocketAddress): ActorRef = { + val commander = TestProbe() + commander.send(IO(UdpConn), UdpConn.Connect(testActor, localAddress, remoteAddress, Nil)) + commander.expectMsg(UdpConn.Connected) + commander.sender + } + + "The UDP connection oriented implementation" must { + + "be able to send and receive without binding" in { + val (serverAddress, server) = bindUdp(testActor) + val data1 = ByteString("To infinity and beyond!") + val data2 = ByteString("All your datagram belong to us") + connectUdp(localAddress = None, serverAddress) ! UdpConn.Send(data1) + + val clientAddress = expectMsgPF() { + case UdpFF.Received(d, a) ⇒ + d must be === data1 + a + } + + println(clientAddress) + + server ! UdpFF.Send(data2, clientAddress) + + // FIXME: Currently this line fails + expectMsgPF() { + case UdpConn.Received(d) ⇒ d must be === data2 + } + } + + "be able to send and receive with binding" in { + val clientAddress = temporaryServerAddress() + val (serverAddress, server) = bindUdp(testActor) + val data1 = ByteString("To infinity and beyond!") + val data2 = ByteString("All your datagram belong to us") + connectUdp(Some(clientAddress), serverAddress) ! UdpConn.Send(data1) + + expectMsgPF() { + case UdpFF.Received(d, a) ⇒ + d must be === data1 + a must be === clientAddress + } + + server ! UdpFF.Send(data2, clientAddress) + + // FIXME: Currently this line fails + expectMsgPF() { + case UdpConn.Received(d) ⇒ d must be === data2 + } + } + + } + +} diff --git a/akka-actor/src/main/resources/reference.conf b/akka-actor/src/main/resources/reference.conf index 859ae7acbf..b755af0e09 100644 --- a/akka-actor/src/main/resources/reference.conf +++ b/akka-actor/src/main/resources/reference.conf @@ -445,7 +445,7 @@ akka { management-dispatcher = "akka.actor.default-dispatcher" } - udpFF { + udp-fire-and-forget { # The number of selectors to stripe the served channels over; each of # these will use one select loop on the selector-dispatcher. @@ -501,6 +501,63 @@ akka { management-dispatcher = "akka.actor.default-dispatcher" } + udp-connection { + + # The number of selectors to stripe the served channels over; each of + # these will use one select loop on the selector-dispatcher. + nr-of-selectors = 1 + + # Maximum number of open channels supported by this UDP module Generally + # UDP does not require a large number of channels, therefore it is + # recommended to keep this setting low. + max-channels = 4096 + + # The select loop can be used in two modes: + # - setting "infinite" will select without a timeout, hogging a thread + # - setting a positive timeout will do a bounded select call, + # enabling sharing of a single thread between multiple selectors + # (in this case you will have to use a different configuration for the + # selector-dispatcher, e.g. using "type=Dispatcher" with size 1) + # - setting it to zero means polling, i.e. calling selectNow() + select-timeout = infinite + + # When trying to assign a new connection to a selector and the chosen + # selector is at full capacity, retry selector choosing and assignment + # this many times before giving up + selector-association-retries = 10 + + # The number of bytes per direct buffer in the pool used to read or write + # network data from the kernel. + direct-buffer-size = 128 KiB + + # The maximal number of direct buffers kept in the direct buffer pool for + # reuse. + max-direct-buffer-pool-size = 1000 + + # The maximum number of bytes delivered by a `Received` message. Before + # more data is read from the network the connection actor will try to + # do other work. + received-message-size-limit = unlimited + + # Enable fine grained logging of what goes on inside the implementation. + # Be aware that this may log more than once per message sent to the actors + # of the tcp implementation. + trace-logging = off + + # Fully qualified config path which holds the dispatcher configuration + # to be used for running the select() calls in the selectors + selector-dispatcher = "akka.io.pinned-dispatcher" + + # Fully qualified config path which holds the dispatcher configuration + # for the read/write worker actors + worker-dispatcher = "akka.actor.default-dispatcher" + + # Fully qualified config path which holds the dispatcher configuration + # for the selector management actors + management-dispatcher = "akka.actor.default-dispatcher" + } + + # IMPORTANT NOTICE: # # The following settings belong to the deprecated akka.actor.IO diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 5c3d7c6251..0f0c068017 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -70,11 +70,11 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler val OP_READ_AND_WRITE = OP_READ | OP_WRITE // compile-time constant def receive: Receive = { - case WriteInterest ⇒ execute(enableInterest(OP_WRITE, sender)) - case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) - case AcceptInterest ⇒ execute(enableInterest(OP_ACCEPT, sender)) + case WriteInterest ⇒ execute(enableInterest(OP_WRITE, sender)) + case ReadInterest ⇒ execute(enableInterest(OP_READ, sender)) + case AcceptInterest ⇒ execute(enableInterest(OP_ACCEPT, sender)) - case DisableReadInterest ⇒ execute(disableInterest(OP_READ, sender)) + case DisableReadInterest ⇒ execute(disableInterest(OP_READ, sender)) case cmd: WorkerForCommand ⇒ withCapacityProtection(cmd, SelectorAssociationRetries) { spawnChild(cmd.childProps) } diff --git a/akka-actor/src/main/scala/akka/io/Udp.scala b/akka-actor/src/main/scala/akka/io/Udp.scala index c543cf4927..18d874baa4 100644 --- a/akka-actor/src/main/scala/akka/io/Udp.scala +++ b/akka-actor/src/main/scala/akka/io/Udp.scala @@ -5,6 +5,8 @@ package akka.io import java.net.DatagramSocket import akka.io.Inet.SocketOption +import com.typesafe.config.Config +import akka.actor.{ Props, ActorSystemImpl } object Udp { @@ -21,4 +23,24 @@ object Udp { } + private[io] class UdpSettings(_config: Config) extends SelectionHandlerSettings(_config) { + import _config._ + + val NrOfSelectors = getInt("nr-of-selectors") + val DirectBufferSize = getIntBytes("direct-buffer-size") + val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") + + val ManagementDispatcher = getString("management-dispatcher") + + require(NrOfSelectors > 0, "nr-of-selectors must be > 0") + + override val MaxChannelsPerSelector = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) + + private[this] def getIntBytes(path: String): Int = { + val size = getBytes(path) + require(size < Int.MaxValue, s"$path must be < 2 GiB") + size.toInt + } + } + } diff --git a/akka-actor/src/main/scala/akka/io/UdpConn.scala b/akka-actor/src/main/scala/akka/io/UdpConn.scala index 651953e65e..df6715d2c5 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConn.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConn.scala @@ -3,19 +3,62 @@ */ package akka.io -import akka.actor.{ ExtendedActorSystem, Props, ActorSystemImpl, ExtensionKey } +import akka.actor._ +import akka.io.Inet.SocketOption +import akka.io.Udp.UdpSettings +import akka.util.ByteString +import java.net.InetSocketAddress +import scala.collection.immutable object UdpConn extends ExtensionKey[UdpConnExt] { + // Java API + override def get(system: ActorSystem): UdpConnExt = system.extension(this) + + trait Command extends IO.HasFailureMessage { + def failureMessage = CommandFailed(this) + } + + case object NoAck + case class Send(payload: ByteString, ack: Any) extends Command { + require(ack != null, "ack must be non-null. Use NoAck if you don't want acks.") + + def wantsAck: Boolean = ack != NoAck + } + object Send { + def apply(data: ByteString): Send = Send(data, NoAck) + } + + case class Connect(handler: ActorRef, + localAddress: Option[InetSocketAddress], + remoteAddress: InetSocketAddress, + options: immutable.Traversable[SocketOption] = Nil) extends Command + + case object StopReading extends Command + case object ResumeReading extends Command + + trait Event + + case class Received(data: ByteString) extends Event + case class CommandFailed(cmd: Command) extends Event + case object Connected extends Event + case object Disconnected extends Event + + case object Close extends Command + + case class SendFailed(cause: Throwable) extends Event } class UdpConnExt(system: ExtendedActorSystem) extends IO.Extension { + val settings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-fire-and-forget")) + val manager = { system.asInstanceOf[ActorSystemImpl].systemActorOf( - props = Props.empty, + props = Props(new UdpConnManager(this)), name = "IO-UDP-CONN") } -} + val bufferPool: BufferPool = new DirectByteBufferPool(settings.DirectBufferSize, settings.MaxDirectBufferPoolSize) +} \ No newline at end of file diff --git a/akka-actor/src/main/scala/akka/io/UdpConnManager.scala b/akka-actor/src/main/scala/akka/io/UdpConnManager.scala new file mode 100644 index 0000000000..8dbe806c7d --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpConnManager.scala @@ -0,0 +1,18 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor.Props +import akka.io.IO.SelectorBasedManager +import akka.io.UdpConn.Connect + +class UdpConnManager(udpConn: UdpConnExt) extends SelectorBasedManager(udpConn.settings, udpConn.settings.NrOfSelectors) { + + def receive = workerForCommand { + case Connect(handler, localAddress, remoteAddress, options) ⇒ + val commander = sender + Props(new UdpConnection(selectorPool, handler, localAddress, remoteAddress, commander, udpConn, options)) + } + +} diff --git a/akka-actor/src/main/scala/akka/io/UdpConnection.scala b/akka-actor/src/main/scala/akka/io/UdpConnection.scala new file mode 100644 index 0000000000..8f8fd2fb35 --- /dev/null +++ b/akka-actor/src/main/scala/akka/io/UdpConnection.scala @@ -0,0 +1,125 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.io + +import akka.actor.{ Actor, ActorLogging, ActorRef } +import akka.io.Inet.SocketOption +import akka.io.SelectionHandler._ +import akka.io.UdpConn._ +import akka.util.ByteString +import java.net.InetSocketAddress +import java.nio.channels.DatagramChannel +import java.nio.channels.SelectionKey._ +import scala.collection.immutable +import scala.util.control.NonFatal + +private[io] class UdpConnection(selectorRouter: ActorRef, + handler: ActorRef, + localAddress: Option[InetSocketAddress], + remoteAddress: InetSocketAddress, + bindCommander: ActorRef, + val udpConn: UdpConnExt, + options: immutable.Traversable[SocketOption]) extends Actor with ActorLogging { + + def selector: ActorRef = context.parent + + import udpConn._ + import udpConn.settings._ + + var pendingSend: (Send, ActorRef) = null + def writePending = pendingSend ne null + + context.watch(handler) // sign death pact + val channel = { + val datagramChannel = DatagramChannel.open + datagramChannel.configureBlocking(false) + val socket = datagramChannel.socket + options.foreach(_.beforeDatagramBind(socket)) + localAddress foreach { socket.bind } // will blow up the actor constructor if the bind fails + datagramChannel.connect(remoteAddress) + datagramChannel + } + selector ! RegisterChannel(channel, OP_READ) + log.debug("Successfully connected to {}", remoteAddress) + + def receive = { + case ChannelRegistered ⇒ + bindCommander ! Connected + context.become(connected, discardOld = true) + } + + def connected: Receive = { + case StopReading ⇒ selector ! DisableReadInterest + case ResumeReading ⇒ selector ! ReadInterest + case ChannelReadable ⇒ doRead(handler) + + case Close ⇒ + log.debug("Closing UDP connection to {}", remoteAddress) + channel.close() + sender ! Disconnected + log.debug("Connection closed to {}, stopping listener", remoteAddress) + context.stop(self) + + case send: Send if writePending ⇒ + if (TraceLogging) log.debug("Dropping write because queue is full") + sender ! CommandFailed(send) + + case send: Send if send.payload.isEmpty ⇒ + if (send.wantsAck) + sender ! send.ack + + case send: Send ⇒ + pendingSend = (send, sender) + selector ! WriteInterest + + case ChannelWritable ⇒ doWrite() + } + + def doRead(handler: ActorRef): Unit = { + val buffer = bufferPool.acquire() + try { + buffer.clear() + buffer.limit(DirectBufferSize) + + if (channel.read(buffer) > 0) handler ! Received(ByteString(buffer)) + + } finally { + selector ! ReadInterest + bufferPool.release(buffer) + } + } + + final def doWrite(): Unit = { + + val buffer = udpConn.bufferPool.acquire() + try { + val (send, commander) = pendingSend + buffer.clear() + send.payload.copyToBuffer(buffer) + buffer.flip() + val writtenBytes = channel.write(buffer) + if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes) + + // Datagram channel either sends the whole message, or nothing + if (writtenBytes == 0) commander ! CommandFailed(send) + else if (send.wantsAck) commander ! send.ack + + } finally { + udpConn.bufferPool.release(buffer) + pendingSend = null + } + + } + + override def postStop() { + if (channel.isOpen) { + log.debug("Closing DatagramChannel after being stopped") + try channel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing DatagramChannel") + } + } + } + +} diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index 0d6c49b83e..51b1b7429c 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -4,11 +4,11 @@ package akka.io import akka.actor._ -import akka.util.ByteString -import java.net.{ DatagramSocket, InetSocketAddress } -import scala.collection.immutable -import com.typesafe.config.Config import akka.io.Inet.SocketOption +import akka.io.Udp.UdpSettings +import akka.util.ByteString +import java.net.InetSocketAddress +import scala.collection.immutable object UdpFF extends ExtensionKey[UdpFFExt] { @@ -47,36 +47,13 @@ object UdpFF extends ExtensionKey[UdpFFExt] { case object SimpleSendReady extends Event case object Unbound extends Event - sealed trait CloseCommand extends Command - case object Close extends CloseCommand - case object Abort extends CloseCommand - case class SendFailed(cause: Throwable) extends Event } class UdpFFExt(system: ExtendedActorSystem) extends IO.Extension { - val settings = new Settings(system.settings.config.getConfig("akka.io.udpFF")) - class Settings private[UdpFFExt] (_config: Config) extends SelectionHandlerSettings(_config) { - import _config._ - - val NrOfSelectors = getInt("nr-of-selectors") - val DirectBufferSize = getIntBytes("direct-buffer-size") - val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") - - val ManagementDispatcher = getString("management-dispatcher") - - require(NrOfSelectors > 0, "nr-of-selectors must be > 0") - - override val MaxChannelsPerSelector = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) - - private[this] def getIntBytes(path: String): Int = { - val size = getBytes(path) - require(size < Int.MaxValue, s"$path must be < 2 GiB") - size.toInt - } - } + val settings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-fire-and-forget")) val manager = { system.asInstanceOf[ActorSystemImpl].systemActorOf( diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index 0d79f64e83..3f464bccc5 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -38,17 +38,18 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, datagramChannel } context.parent ! RegisterChannel(channel, OP_READ) - bindCommander ! Bound log.debug("Successfully bound to {}", endpoint) def receive: Receive = { - case ChannelRegistered ⇒ context.become(readHandlers orElse sendHandlers, discardOld = true) + case ChannelRegistered ⇒ + bindCommander ! Bound + context.become(readHandlers orElse sendHandlers, discardOld = true) } def readHandlers: Receive = { case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest - case ChannelReadable ⇒ doReceive(handler, None) + case ChannelReadable ⇒ doReceive(handler) case Unbind ⇒ log.debug("Unbinding endpoint {}", endpoint) @@ -58,7 +59,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, context.stop(self) } - def doReceive(handler: ActorRef, closeCommander: Option[ActorRef]): Unit = { + def doReceive(handler: ActorRef): Unit = { val buffer = bufferPool.acquire() try { buffer.clear() @@ -76,13 +77,12 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, } override def postStop() { - try { - if (channel.isOpen) { - log.debug("Closing serverSocketChannel after being stopped") - channel.close() + if (channel.isOpen) { + log.debug("Closing DatagramChannel after being stopped") + try channel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing DatagramChannel") } - } catch { - case NonFatal(e) ⇒ log.error(e, "Error closing ServerSocketChannel") } } } diff --git a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala index da837c35fd..e04c4ca6f5 100644 --- a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala +++ b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala @@ -8,7 +8,7 @@ import akka.io.UdpFF.{ CommandFailed, Send } import akka.io.SelectionHandler._ import java.nio.channels.DatagramChannel -trait WithUdpFFSend { +private[io] trait WithUdpFFSend { me: Actor with ActorLogging ⇒ var pendingSend: (Send, ActorRef) = null From 116dcc0e544e71a26e0ec084e76823743dc7f16c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Wed, 6 Feb 2013 11:38:42 +0100 Subject: [PATCH 11/18] Various minor changes: - added forwarders to SO objects to Inet - added batch read support for UDP - changed write for UDP - SimpleSender is now registered as everone else --- .../test/scala/akka/io/IntegrationSpec.scala | 5 ++--- .../akka/io/UdpConnIntegrationSpec.scala | 8 +++---- .../scala/akka/io/UdpFFIntegrationSpec.scala | 2 +- akka-actor/src/main/resources/reference.conf | 10 +++++++++ akka-actor/src/main/scala/akka/io/Inet.scala | 7 +++++++ .../main/scala/akka/io/SelectionHandler.scala | 1 + akka-actor/src/main/scala/akka/io/Tcp.scala | 2 +- akka-actor/src/main/scala/akka/io/Udp.scala | 4 +++- .../main/scala/akka/io/UdpConnection.scala | 20 +++++++++++------- akka-actor/src/main/scala/akka/io/UdpFF.scala | 2 +- .../main/scala/akka/io/UdpFFListener.scala | 15 +++++++++---- .../src/main/scala/akka/io/UdpFFManager.scala | 10 +++------ .../src/main/scala/akka/io/UdpFFSender.scala | 21 ++++++++++++------- .../main/scala/akka/io/WithUdpFFSend.scala | 18 ++++++++++++---- 14 files changed, 85 insertions(+), 40 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala index 1e7a40eb90..e4d53f5f9b 100644 --- a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala @@ -6,7 +6,6 @@ package akka.io import akka.testkit.AkkaSpec import akka.util.ByteString -import akka.io.Inet import Tcp._ import TestUtils._ import akka.testkit.EventFilter @@ -65,8 +64,8 @@ class IntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with IntegrationS expectReceivedData(clientHandler, 100000) - override def bindOptions = List(Inet.SO.SendBufferSize(1024)) - override def connectOptions = List(Inet.SO.ReceiveBufferSize(1024)) + override def bindOptions = List(SO.SendBufferSize(1024)) + override def connectOptions = List(SO.ReceiveBufferSize(1024)) } } diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala index 90bfdb222e..ece503de33 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala @@ -19,9 +19,9 @@ class UdpConnIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Impli (address, commander.sender) } - def connectUdp(localAddress: Option[InetSocketAddress], remoteAddress: InetSocketAddress): ActorRef = { + def connectUdp(localAddress: Option[InetSocketAddress], remoteAddress: InetSocketAddress, handler: ActorRef): ActorRef = { val commander = TestProbe() - commander.send(IO(UdpConn), UdpConn.Connect(testActor, localAddress, remoteAddress, Nil)) + commander.send(IO(UdpConn), UdpConn.Connect(handler, localAddress, remoteAddress, Nil)) commander.expectMsg(UdpConn.Connected) commander.sender } @@ -32,7 +32,7 @@ class UdpConnIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Impli val (serverAddress, server) = bindUdp(testActor) val data1 = ByteString("To infinity and beyond!") val data2 = ByteString("All your datagram belong to us") - connectUdp(localAddress = None, serverAddress) ! UdpConn.Send(data1) + connectUdp(localAddress = None, serverAddress, testActor) ! UdpConn.Send(data1) val clientAddress = expectMsgPF() { case UdpFF.Received(d, a) ⇒ @@ -55,7 +55,7 @@ class UdpConnIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Impli val (serverAddress, server) = bindUdp(testActor) val data1 = ByteString("To infinity and beyond!") val data2 = ByteString("All your datagram belong to us") - connectUdp(Some(clientAddress), serverAddress) ! UdpConn.Send(data1) + connectUdp(Some(clientAddress), serverAddress, testActor) ! UdpConn.Send(data1) expectMsgPF() { case UdpFF.Received(d, a) ⇒ diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala index 21d61c3e1d..a0f138f041 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala @@ -22,7 +22,7 @@ class UdpFFIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Implici val simpleSender: ActorRef = { val commander = TestProbe() - commander.send(IO(UdpFF), SimpleSender) + commander.send(IO(UdpFF), SimpleSender(Nil)) commander.expectMsg(SimpleSendReady) commander.sender } diff --git a/akka-actor/src/main/resources/reference.conf b/akka-actor/src/main/resources/reference.conf index b755af0e09..c17594a307 100644 --- a/akka-actor/src/main/resources/reference.conf +++ b/akka-actor/src/main/resources/reference.conf @@ -470,6 +470,11 @@ akka { # this many times before giving up selector-association-retries = 10 + # The maximum number of datagrams that are read in one go, + # higher numbers decrease latency, lower numbers increase fairness on + # the worker-dispatcher + batch-receive-limit = 3 + # The number of bytes per direct buffer in the pool used to read or write # network data from the kernel. direct-buffer-size = 128 KiB @@ -526,6 +531,11 @@ akka { # this many times before giving up selector-association-retries = 10 + # The maximum number of datagrams that are read in one go, + # higher numbers decrease latency, lower numbers increase fairness on + # the worker-dispatcher + batch-receive-limit = 3 + # The number of bytes per direct buffer in the pool used to read or write # network data from the kernel. direct-buffer-size = 128 KiB diff --git a/akka-actor/src/main/scala/akka/io/Inet.scala b/akka-actor/src/main/scala/akka/io/Inet.scala index 9e53507284..0b9fb4ca0c 100644 --- a/akka-actor/src/main/scala/akka/io/Inet.scala +++ b/akka-actor/src/main/scala/akka/io/Inet.scala @@ -79,4 +79,11 @@ object Inet { } + trait SoForwarders { + val ReceiveBufferSize = SO.ReceiveBufferSize + val ReuseAddress = SO.ReuseAddress + val SendBufferSize = SO.SendBufferSize + val TrafficClass = SO.TrafficClass + } + } diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 0f0c068017..e7046d8b34 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -208,6 +208,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler selectorManagementDispatcher.execute(select) // start selection "loop" + // FIXME: Add possibility to signal failure of task to someone abstract class Task extends Runnable { def tryRun() def run() { diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index 38c8051714..95218f16cf 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -19,7 +19,7 @@ object Tcp extends ExtensionKey[TcpExt] { override def get(system: ActorSystem): TcpExt = system.extension(this) // shared socket options - object SO { + object SO extends Inet.SoForwarders { // general socket options diff --git a/akka-actor/src/main/scala/akka/io/Udp.scala b/akka-actor/src/main/scala/akka/io/Udp.scala index 18d874baa4..83e8b0d5f1 100644 --- a/akka-actor/src/main/scala/akka/io/Udp.scala +++ b/akka-actor/src/main/scala/akka/io/Udp.scala @@ -10,7 +10,7 @@ import akka.actor.{ Props, ActorSystemImpl } object Udp { - object SO { + object SO extends Inet.SoForwarders { /** * [[akka.io.Inet.SocketOption]] to set the SO_BROADCAST option @@ -29,9 +29,11 @@ object Udp { val NrOfSelectors = getInt("nr-of-selectors") val DirectBufferSize = getIntBytes("direct-buffer-size") val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") + val BatchReceiveLimit = getInt("batch-receive-limit") val ManagementDispatcher = getString("management-dispatcher") + // FIXME: Use new requiring require(NrOfSelectors > 0, "nr-of-selectors must be > 0") override val MaxChannelsPerSelector = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) diff --git a/akka-actor/src/main/scala/akka/io/UdpConnection.scala b/akka-actor/src/main/scala/akka/io/UdpConnection.scala index 8f8fd2fb35..11a5a17f71 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnection.scala @@ -13,6 +13,8 @@ import java.nio.channels.DatagramChannel import java.nio.channels.SelectionKey._ import scala.collection.immutable import scala.util.control.NonFatal +import java.nio.ByteBuffer +import scala.annotation.tailrec private[io] class UdpConnection(selectorRouter: ActorRef, handler: ActorRef, @@ -36,6 +38,7 @@ private[io] class UdpConnection(selectorRouter: ActorRef, datagramChannel.configureBlocking(false) val socket = datagramChannel.socket options.foreach(_.beforeDatagramBind(socket)) + // FIXME: All bind failures have to be reported to the commander in TCP as well localAddress foreach { socket.bind } // will blow up the actor constructor if the bind fails datagramChannel.connect(remoteAddress) datagramChannel @@ -46,13 +49,14 @@ private[io] class UdpConnection(selectorRouter: ActorRef, def receive = { case ChannelRegistered ⇒ bindCommander ! Connected + selector ! ReadInterest context.become(connected, discardOld = true) } def connected: Receive = { case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest - case ChannelReadable ⇒ doRead(handler) + case ChannelReadable ⇒ println("read"); doRead(handler) case Close ⇒ log.debug("Closing UDP connection to {}", remoteAddress) @@ -77,14 +81,17 @@ private[io] class UdpConnection(selectorRouter: ActorRef, } def doRead(handler: ActorRef): Unit = { - val buffer = bufferPool.acquire() - try { + @tailrec def innerRead(readsLeft: Int, buffer: ByteBuffer): Unit = { buffer.clear() buffer.limit(DirectBufferSize) - if (channel.read(buffer) > 0) handler ! Received(ByteString(buffer)) - - } finally { + if (channel.read(buffer) > 0) { + handler ! Received(ByteString(buffer)) + innerRead(readsLeft - 1, buffer) + } + } + val buffer = bufferPool.acquire() + try innerRead(BatchReceiveLimit, buffer) finally { selector ! ReadInterest bufferPool.release(buffer) } @@ -104,7 +111,6 @@ private[io] class UdpConnection(selectorRouter: ActorRef, // Datagram channel either sends the whole message, or nothing if (writtenBytes == 0) commander ! CommandFailed(send) else if (send.wantsAck) commander ! send.ack - } finally { udpConn.bufferPool.release(buffer) pendingSend = null diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index 51b1b7429c..f6d86f7053 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -34,7 +34,7 @@ object UdpFF extends ExtensionKey[UdpFFExt] { options: immutable.Traversable[SocketOption] = Nil) extends Command case object Unbind extends Command - case object SimpleSender extends Command + case class SimpleSender(options: immutable.Traversable[SocketOption] = Nil) extends Command case object StopReading extends Command case object ResumeReading extends Command diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index 3f464bccc5..aa8000eb0b 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -15,6 +15,8 @@ import scala.collection.immutable import scala.util.control.NonFatal import akka.io.UdpFF.Received import akka.io.SelectionHandler.RegisterChannel +import scala.annotation.tailrec +import java.nio.ByteBuffer private[io] class UdpFFListener(selectorRouter: ActorRef, handler: ActorRef, @@ -34,6 +36,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, datagramChannel.configureBlocking(false) val socket = datagramChannel.socket options.foreach(_.beforeDatagramBind(socket)) + // FIXME: signal bind failures socket.bind(endpoint) // will blow up the actor constructor if the bind fails datagramChannel } @@ -60,8 +63,7 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, } def doReceive(handler: ActorRef): Unit = { - val buffer = bufferPool.acquire() - try { + @tailrec def innerReceive(readsLeft: Int, buffer: ByteBuffer) { buffer.clear() buffer.limit(DirectBufferSize) @@ -69,11 +71,16 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, case sender: InetSocketAddress ⇒ buffer.flip() handler ! Received(ByteString(buffer), sender) - case _ ⇒ // Ignore + if (readsLeft > 0) innerReceive(readsLeft - 1, buffer) + case null ⇒ // null means no data was available } + } + val buffer = bufferPool.acquire() + try innerReceive(BatchReceiveLimit, buffer) finally { + bufferPool.release(buffer) selector ! ReadInterest - } finally bufferPool.release(buffer) + } } override def postStop() { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index 3f5c677991..28c47ef995 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -44,17 +44,13 @@ import akka.io.UdpFF._ */ private[io] class UdpFFManager(udpFF: UdpFFExt) extends SelectorBasedManager(udpFF.settings, udpFF.settings.NrOfSelectors) { - // FIXME: fix close overs - lazy val anonymousSender: ActorRef = context.actorOf( - props = Props(new UdpFFSender(udpFF, selectorPool)), - name = "simplesend") - def receive = workerForCommand { case Bind(handler, endpoint, options) ⇒ val commander = sender Props(new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options)) - } orElse { - case SimpleSender ⇒ anonymousSender forward SimpleSender + case SimpleSender(options) ⇒ + val commander = sender + Props(new UdpFFSender(udpFF, options, commander)) } } diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala index 24e222e71c..5303aa79d9 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala @@ -7,27 +7,34 @@ import akka.actor._ import java.nio.channels.DatagramChannel import akka.io.UdpFF._ import akka.io.SelectionHandler.{ ChannelRegistered, RegisterChannel } +import scala.collection.immutable +import akka.io.Inet.SocketOption /** * Base class for TcpIncomingConnection and TcpOutgoingConnection. */ -private[io] class UdpFFSender(val udpFF: UdpFFExt, val selector: ActorRef) +private[io] class UdpFFSender(val udpFF: UdpFFExt, options: immutable.Traversable[SocketOption], val commander: ActorRef) extends Actor with ActorLogging with WithUdpFFSend { + def selector: ActorRef = context.parent + val channel = { val datagramChannel = DatagramChannel.open datagramChannel.configureBlocking(false) + val socket = datagramChannel.socket + + options foreach { o ⇒ + o.beforeDatagramBind(socket) + } + datagramChannel } selector ! RegisterChannel(channel, 0) def receive: Receive = { - case ChannelRegistered ⇒ context.become(simpleSendHandlers orElse sendHandlers, discardOld = true) - case _ ⇒ sender ! SimpleSendReady // FIXME: queueing here? - } - - def simpleSendHandlers: Receive = { - case SimpleSender ⇒ sender ! SimpleSendReady + case ChannelRegistered ⇒ + context.become(sendHandlers, discardOld = true) + commander ! SimpleSendReady } override def postStop(): Unit = if (channel.isOpen) channel.close() diff --git a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala index e04c4ca6f5..09dd37666c 100644 --- a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala +++ b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala @@ -12,6 +12,9 @@ private[io] trait WithUdpFFSend { me: Actor with ActorLogging ⇒ var pendingSend: (Send, ActorRef) = null + // If send fails first, we allow a second go after selected writable, but no more. This flag signals that + // pending send was already tried once. + var retriedSend = false def writePending = pendingSend ne null def selector: ActorRef @@ -33,7 +36,7 @@ private[io] trait WithUdpFFSend { case send: Send ⇒ pendingSend = (send, sender) - selector ! WriteInterest + doSend() case ChannelWritable ⇒ doSend() @@ -51,12 +54,19 @@ private[io] trait WithUdpFFSend { if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes) // Datagram channel either sends the whole message, or nothing - if (writtenBytes == 0) commander ! CommandFailed(send) - else if (send.wantsAck) commander ! send.ack + if (writtenBytes == 0) { + if (retriedSend) { + commander ! CommandFailed(send) + retriedSend = false + pendingSend = null + } else { + selector ! WriteInterest + retriedSend = true + } + } else if (send.wantsAck) commander ! send.ack } finally { udpFF.bufferPool.release(buffer) - pendingSend = null } } From 6f0d0911a92d8fe2cc575a4fb201a50b1708f5e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Wed, 6 Feb 2013 12:17:52 +0100 Subject: [PATCH 12/18] Bind failures are now explicitly reported instead of swallowed --- .../scala/akka/io/CapacityLimitSpec.scala | 2 +- .../scala/akka/io/TcpConnectionSpec.scala | 2 +- ...ionSpec.scala => TcpIntegrationSpec.scala} | 2 +- ....scala => TcpIntegrationSpecSupport.scala} | 2 +- .../test/scala/akka/io/TcpListenerSpec.scala | 3 +- .../src/main/scala/akka/io/TcpListener.scala | 20 +++++++----- .../src/main/scala/akka/io/TcpManager.scala | 8 ++--- .../scala/akka/io/TcpOutgoingConnection.scala | 15 ++++----- .../main/scala/akka/io/UdpConnManager.scala | 4 +-- .../main/scala/akka/io/UdpConnection.scala | 25 ++++++++------- .../main/scala/akka/io/UdpFFListener.scala | 32 +++++++++---------- .../src/main/scala/akka/io/UdpFFManager.scala | 6 ++-- 12 files changed, 63 insertions(+), 58 deletions(-) rename akka-actor-tests/src/test/scala/akka/io/{IntegrationSpec.scala => TcpIntegrationSpec.scala} (96%) rename akka-actor-tests/src/test/scala/akka/io/{IntegrationSpecSupport.scala => TcpIntegrationSpecSupport.scala} (97%) diff --git a/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala b/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala index a61962e223..600aed6114 100644 --- a/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/CapacityLimitSpec.scala @@ -9,7 +9,7 @@ import Tcp._ import TestUtils._ class CapacityLimitSpec extends AkkaSpec("akka.loglevel = ERROR\nakka.io.tcp.max-channels = 4") - with IntegrationSpecSupport { + with TcpIntegrationSpecSupport { "The TCP transport implementation" should { diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index a59f2ccad4..a09dd68cdd 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -573,7 +573,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") commander: ActorRef): TestActorRef[TcpOutgoingConnection] = { TestActorRef( - new TcpOutgoingConnection(Tcp(system), commander, serverAddress, localAddress, options) { + new TcpOutgoingConnection(Tcp(system), commander, Connect(serverAddress, localAddress, options)) { override def postRestart(reason: Throwable) { // ensure we never restart context.stop(self) diff --git a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala similarity index 96% rename from akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala rename to akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala index e4d53f5f9b..9f35951ad9 100644 --- a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpec.scala @@ -11,7 +11,7 @@ import TestUtils._ import akka.testkit.EventFilter import java.io.IOException -class IntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with IntegrationSpecSupport { +class TcpIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with TcpIntegrationSpecSupport { "The TCP transport implementation" should { diff --git a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala similarity index 97% rename from akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala rename to akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala index 692815b96a..4ed3bd9950 100644 --- a/akka-actor-tests/src/test/scala/akka/io/IntegrationSpecSupport.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpIntegrationSpecSupport.scala @@ -12,7 +12,7 @@ import akka.io.Inet.SocketOption import Tcp._ import TestUtils._ -trait IntegrationSpecSupport { _: AkkaSpec ⇒ +trait TcpIntegrationSpecSupport { _: AkkaSpec ⇒ class TestSetup { val bindHandler = TestProbe() diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index e68cc6536e..b04d07d7d8 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -97,8 +97,7 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { private class ListenerParent extends Actor { val listener = context.actorOf( - props = Props(new TcpListener(selectorRouter.ref, handler.ref, endpoint, 100, bindCommander.ref, - Tcp(system), Nil)), + props = Props(new TcpListener(selectorRouter.ref, Tcp(system), bindCommander.ref, Bind(handler.ref, endpoint, 100, Nil))), name = "test-listener-" + counter.next()) parent.watch(listener) def receive: Receive = { diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index 356319286f..51419fa0a5 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -25,17 +25,15 @@ private[io] object TcpListener { } -private[io] class TcpListener(selectorRouter: ActorRef, - handler: ActorRef, - endpoint: InetSocketAddress, - backlog: Int, - bindCommander: ActorRef, - tcp: TcpExt, - options: immutable.Traversable[SocketOption]) extends Actor with ActorLogging { +private[io] class TcpListener(val selectorRouter: ActorRef, + val tcp: TcpExt, + val bindCommander: ActorRef, + val bind: Bind) extends Actor with ActorLogging { def selector: ActorRef = context.parent import TcpListener._ import tcp.Settings._ + import bind._ context.watch(handler) // sign death pact val channel = { @@ -43,7 +41,13 @@ private[io] class TcpListener(selectorRouter: ActorRef, serverSocketChannel.configureBlocking(false) val socket = serverSocketChannel.socket options.foreach(_.beforeServerSocketBind(socket)) - socket.bind(endpoint, backlog) // will blow up the actor constructor if the bind fails + try socket.bind(endpoint, backlog) + catch { + case NonFatal(e) ⇒ + bindCommander ! CommandFailed(bind) + log.error(e, "Bind failed for TCP channel") + context.stop(self) + } serverSocketChannel } context.parent ! RegisterChannel(channel, SelectionKey.OP_ACCEPT) diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index 8761104ba5..032bcfd6bc 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -46,12 +46,12 @@ import akka.io.IO.SelectorBasedManager private[io] class TcpManager(tcp: TcpExt) extends SelectorBasedManager(tcp.Settings, tcp.Settings.NrOfSelectors) with ActorLogging { def receive = workerForCommand { - case Connect(remoteAddress, localAddress, options) ⇒ + case c: Connect ⇒ val commander = sender - Props(new TcpOutgoingConnection(tcp, commander, remoteAddress, localAddress, options)) - case Bind(handler, endpoint, backlog, options) ⇒ + Props(new TcpOutgoingConnection(tcp, commander, c)) + case b: Bind ⇒ val commander = sender - Props(new TcpListener(selectorPool, handler, endpoint, backlog, commander, tcp, options)) + Props(new TcpListener(selectorPool, tcp, commander, b)) } } diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 6c9231fa46..39817efe99 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -4,14 +4,13 @@ package akka.io -import java.net.InetSocketAddress +import akka.actor.ActorRef +import akka.io.Inet.SocketOption +import akka.io.SelectionHandler._ +import akka.io.Tcp._ import java.io.IOException import java.nio.channels.{ SelectionKey, SocketChannel } import scala.collection.immutable -import akka.actor.ActorRef -import akka.io.SelectionHandler._ -import akka.io.Inet.SocketOption -import akka.io.Tcp._ /** * An actor handling the connection state machine for an outgoing connection @@ -19,11 +18,11 @@ import akka.io.Tcp._ */ private[io] class TcpOutgoingConnection(_tcp: TcpExt, commander: ActorRef, - remoteAddress: InetSocketAddress, - localAddress: Option[InetSocketAddress], - options: immutable.Traversable[SocketOption]) + connect: Connect) extends TcpConnection(TcpOutgoingConnection.newSocketChannel(), _tcp) { + import connect._ + context.watch(commander) // sign death pact localAddress.foreach(channel.socket.bind) diff --git a/akka-actor/src/main/scala/akka/io/UdpConnManager.scala b/akka-actor/src/main/scala/akka/io/UdpConnManager.scala index 8dbe806c7d..a93a21259d 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnManager.scala @@ -10,9 +10,9 @@ import akka.io.UdpConn.Connect class UdpConnManager(udpConn: UdpConnExt) extends SelectorBasedManager(udpConn.settings, udpConn.settings.NrOfSelectors) { def receive = workerForCommand { - case Connect(handler, localAddress, remoteAddress, options) ⇒ + case c: Connect ⇒ val commander = sender - Props(new UdpConnection(selectorPool, handler, localAddress, remoteAddress, commander, udpConn, options)) + Props(new UdpConnection(udpConn, commander, c)) } } diff --git a/akka-actor/src/main/scala/akka/io/UdpConnection.scala b/akka-actor/src/main/scala/akka/io/UdpConnection.scala index 11a5a17f71..32e6d09bb6 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnection.scala @@ -16,17 +16,14 @@ import scala.util.control.NonFatal import java.nio.ByteBuffer import scala.annotation.tailrec -private[io] class UdpConnection(selectorRouter: ActorRef, - handler: ActorRef, - localAddress: Option[InetSocketAddress], - remoteAddress: InetSocketAddress, - bindCommander: ActorRef, - val udpConn: UdpConnExt, - options: immutable.Traversable[SocketOption]) extends Actor with ActorLogging { +private[io] class UdpConnection(val udpConn: UdpConnExt, + val commander: ActorRef, + val connect: Connect) extends Actor with ActorLogging { def selector: ActorRef = context.parent import udpConn._ + import connect._ import udpConn.settings._ var pendingSend: (Send, ActorRef) = null @@ -38,9 +35,15 @@ private[io] class UdpConnection(selectorRouter: ActorRef, datagramChannel.configureBlocking(false) val socket = datagramChannel.socket options.foreach(_.beforeDatagramBind(socket)) - // FIXME: All bind failures have to be reported to the commander in TCP as well - localAddress foreach { socket.bind } // will blow up the actor constructor if the bind fails - datagramChannel.connect(remoteAddress) + try { + localAddress foreach { socket.bind } // will blow up the actor constructor if the bind fails + datagramChannel.connect(remoteAddress) + } catch { + case NonFatal(e) ⇒ + log.error(e, "Failure while connecting UDP channel") + commander ! CommandFailed(connect) + context.stop(self) + } datagramChannel } selector ! RegisterChannel(channel, OP_READ) @@ -48,7 +51,7 @@ private[io] class UdpConnection(selectorRouter: ActorRef, def receive = { case ChannelRegistered ⇒ - bindCommander ! Connected + commander ! Connected selector ! ReadInterest context.become(connected, discardOld = true) } diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index aa8000eb0b..0edccefab3 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -4,29 +4,24 @@ package akka.io import akka.actor.{ ActorLogging, Actor, ActorRef } -import akka.io.UdpFF._ -import akka.io.Inet.SocketOption import akka.io.SelectionHandler._ +import akka.io.UdpFF._ import akka.util.ByteString import java.net.InetSocketAddress +import java.nio.ByteBuffer import java.nio.channels.DatagramChannel import java.nio.channels.SelectionKey._ -import scala.collection.immutable -import scala.util.control.NonFatal -import akka.io.UdpFF.Received -import akka.io.SelectionHandler.RegisterChannel import scala.annotation.tailrec -import java.nio.ByteBuffer +import scala.util.control.NonFatal -private[io] class UdpFFListener(selectorRouter: ActorRef, - handler: ActorRef, - endpoint: InetSocketAddress, - bindCommander: ActorRef, - val udpFF: UdpFFExt, - options: immutable.Traversable[SocketOption]) +private[io] class UdpFFListener(val udpFF: UdpFFExt, + val bindCommander: ActorRef, + val bind: Bind) extends Actor with ActorLogging with WithUdpFFSend { - import udpFF.settings._ + + import bind._ import udpFF.bufferPool + import udpFF.settings._ def selector: ActorRef = context.parent @@ -36,8 +31,13 @@ private[io] class UdpFFListener(selectorRouter: ActorRef, datagramChannel.configureBlocking(false) val socket = datagramChannel.socket options.foreach(_.beforeDatagramBind(socket)) - // FIXME: signal bind failures - socket.bind(endpoint) // will blow up the actor constructor if the bind fails + try socket.bind(endpoint) + catch { + case NonFatal(e) ⇒ + bindCommander ! CommandFailed(bind) + log.error(e, "Failed to bind UDP channel") + context.stop(self) + } datagramChannel } context.parent ! RegisterChannel(channel, OP_READ) diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index 28c47ef995..8e3e03617f 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -3,7 +3,7 @@ */ package akka.io -import akka.actor.{ ActorRef, Props } +import akka.actor.Props import akka.io.IO.SelectorBasedManager import akka.io.UdpFF._ @@ -45,9 +45,9 @@ import akka.io.UdpFF._ private[io] class UdpFFManager(udpFF: UdpFFExt) extends SelectorBasedManager(udpFF.settings, udpFF.settings.NrOfSelectors) { def receive = workerForCommand { - case Bind(handler, endpoint, options) ⇒ + case b: Bind ⇒ val commander = sender - Props(new UdpFFListener(selectorPool, handler, endpoint, commander, udpFF, options)) + Props(new UdpFFListener(udpFF, commander, b)) case SimpleSender(options) ⇒ val commander = sender Props(new UdpFFSender(udpFF, options, commander)) From 91d798cee18993ff817e0fc578310a3a0da0d4b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Wed, 6 Feb 2013 17:45:42 +0100 Subject: [PATCH 13/18] Updated tests to work (or be disabled) on Win --- .../scala/akka/io/TcpConnectionSpec.scala | 134 ++++++++++++------ .../test/scala/akka/io/TcpListenerSpec.scala | 34 +++-- .../main/scala/akka/io/TcpConnection.scala | 2 +- 3 files changed, 111 insertions(+), 59 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index a09dd68cdd..1e80f84fa1 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -5,7 +5,7 @@ package akka.io import java.io.IOException -import java.net.{ ConnectException, InetSocketAddress, SocketException } +import java.net.{ Socket, ConnectException, InetSocketAddress, SocketException } import java.nio.ByteBuffer import java.nio.channels.{ SelectionKey, Selector, ServerSocketChannel, SocketChannel } import java.nio.channels.spi.SelectorProvider @@ -27,6 +27,12 @@ import akka.io.Inet.SocketOption class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") { val serverAddress = temporaryServerAddress() + // Helper to avoid Windows localization specific differences + def nonWindows(body: ⇒ Any): Unit = { + if (!System.getProperty("os.name").toLowerCase().contains("win")) body + else log.warning("Detected Windows: ignoring check") + } + "An outgoing connection" must { // common behavior @@ -39,16 +45,17 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") clientChannel.socket.getReuseAddress must be(true) } - "set socket options after connecting" in withLocalServer() { localServer ⇒ + "set socket options after connecting" ignore withLocalServer() { localServer ⇒ + // Workaround for systems where SO_KEEPALIVE is true by default val userHandler = TestProbe() val selector = TestProbe() val connectionActor = - createConnectionActor(options = Vector(SO.KeepAlive(true)))(selector.ref, userHandler.ref) + createConnectionActor(options = Vector(SO.KeepAlive(false)))(selector.ref, userHandler.ref) val clientChannel = connectionActor.underlyingActor.channel - clientChannel.socket.getKeepAlive must be(false) // only set after connection is established + clientChannel.socket.getKeepAlive must be(true) // only set after connection is established EventFilter.warning(pattern = "registration timeout", occurrences = 1) intercept { selector.send(connectionActor, ChannelConnectable) - clientChannel.socket.getKeepAlive must be(true) + clientChannel.socket.getKeepAlive must be(false) } } @@ -146,45 +153,62 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") writer.expectMsg(Ack) } + /* + * Disabled on Windows: http://support.microsoft.com/kb/214397 + * + * "To optimize performance at the application layer, Winsock copies data buffers from application send calls + * to a Winsock kernel buffer. Then, the stack uses its own heuristics (such as Nagle algorithm) to determine + * when to actually put the packet on the wire. You can change the amount of Winsock kernel buffer allocated to + * the socket using the SO_SNDBUF option (it is 8K by default). If necessary, Winsock can buffer significantly more + * than the SO_SNDBUF buffer size. In most cases, the send completion in the application only indicates the data + * buffer in an application send call is copied to the Winsock kernel buffer and does not indicate that the data + * has hit the network medium. The only exception is when you disable the Winsock buffering by setting + * SO_SNDBUF to 0." + */ "stop writing in cases of backpressure and resume afterwards" in - withEstablishedConnection(setSmallRcvBuffer) { setup ⇒ - import setup._ - object Ack1 - object Ack2 + nonWindows { + withEstablishedConnection( + clientSocketOptions = List(SO.ReceiveBufferSize(1000000))) { setup ⇒ + import setup._ + object Ack1 + object Ack2 - clientSideChannel.socket.setSendBufferSize(1024) + clientSideChannel.socket.setSendBufferSize(1024) - val writer = TestProbe() + awaitCond(clientSideChannel.socket.getSendBufferSize == 1024) - // producing backpressure by sending much more than currently fits into - // our send buffer - val firstWrite = writeCmd(Ack1) + val writer = TestProbe() - // try to write the buffer but since the SO_SNDBUF is too small - // it will have to keep the rest of the piece and send it - // when possible - writer.send(connectionActor, firstWrite) - selector.expectMsg(WriteInterest) + // producing backpressure by sending much more than currently fits into + // our send buffer + val firstWrite = writeCmd(Ack1) - // send another write which should fail immediately - // because we don't store more than one piece in flight - val secondWrite = writeCmd(Ack2) - writer.send(connectionActor, secondWrite) - writer.expectMsg(CommandFailed(secondWrite)) + // try to write the buffer but since the SO_SNDBUF is too small + // it will have to keep the rest of the piece and send it + // when possible + writer.send(connectionActor, firstWrite) + selector.expectMsg(WriteInterest) - // reject even empty writes - writer.send(connectionActor, Write.Empty) - writer.expectMsg(CommandFailed(Write.Empty)) + // send another write which should fail immediately + // because we don't store more than one piece in flight + val secondWrite = writeCmd(Ack2) + writer.send(connectionActor, secondWrite) + writer.expectMsg(CommandFailed(secondWrite)) - // there will be immediately more space in the send buffer because - // some data will have been sent by now, so we assume we can write - // again, but still it can't write everything - selector.send(connectionActor, ChannelWritable) + // reject even empty writes + writer.send(connectionActor, Write.Empty) + writer.expectMsg(CommandFailed(Write.Empty)) - // both buffers should now be filled so no more writing - // is possible - pullFromServerSide(TestSize) - writer.expectMsg(Ack1) + // there will be immediately more space in the send buffer because + // some data will have been sent by now, so we assume we can write + // again, but still it can't write everything + selector.send(connectionActor, ChannelWritable) + + // both buffers should now be filled so no more writing + // is possible + pullFromServerSide(TestSize) + writer.expectMsg(Ack1) + } } "respect StopReading and ResumeReading" in withEstablishedConnection() { setup ⇒ @@ -193,7 +217,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") // the selector interprets StopReading to deregister interest // for reading - selector.expectMsg(StopReading) + selector.expectMsg(DisableReadInterest) connectionHandler.send(connectionActor, ResumeReading) selector.expectMsg(ReadInterest) } @@ -242,10 +266,21 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val buffer = ByteBuffer.allocate(1) val thrown = evaluating { serverSideChannel.read(buffer) } must produce[IOException] - // FIXME: On windows this message is localized - //thrown.getMessage must be("Connection reset by peer") + nonWindows { thrown.getMessage must be("Connection reset by peer") } } + /* + * Partly disabled on Windows: http://support.microsoft.com/kb/214397 + * + * "To optimize performance at the application layer, Winsock copies data buffers from application send calls + * to a Winsock kernel buffer. Then, the stack uses its own heuristics (such as Nagle algorithm) to determine + * when to actually put the packet on the wire. You can change the amount of Winsock kernel buffer allocated to + * the socket using the SO_SNDBUF option (it is 8K by default). If necessary, Winsock can buffer significantly more + * than the SO_SNDBUF buffer size. In most cases, the send completion in the application only indicates the data + * buffer in an application send call is copied to the Winsock kernel buffer and does not indicate that the data + * has hit the network medium. The only exception is when you disable the Winsock buffering by setting + * SO_SNDBUF to 0." + */ "close the connection and reply with `ConfirmedClosed` upong reception of an `ConfirmedClose` command" in withEstablishedConnection(setSmallRcvBuffer) { setup ⇒ import setup._ @@ -259,12 +294,12 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") connectionHandler.send(connectionActor, writeCmd(Ack)) connectionHandler.send(connectionActor, ConfirmedClose) - connectionHandler.expectNoMsg(100.millis) + nonWindows { connectionHandler.expectNoMsg(100.millis) } pullFromServerSide(TestSize) connectionHandler.expectMsg(Ack) selector.send(connectionActor, ChannelReadable) - connectionHandler.expectNoMsg(100.millis) // not yet + nonWindows { connectionHandler.expectNoMsg(100.millis) } // not yet val buffer = ByteBuffer.allocate(1) serverSelectionKey must be(selectedAs(SelectionKey.OP_READ, 2.seconds)) @@ -292,7 +327,8 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") EventFilter[IOException](occurrences = 1) intercept { abortClose(serverSideChannel) selector.send(connectionActor, ChannelReadable) - connectionHandler.expectMsgType[ErrorClosed].cause must be("Connection reset by peer") + val err = connectionHandler.expectMsgType[ErrorClosed] + nonWindows { err.cause must be("Connection reset by peer") } } // wait a while connectionHandler.expectNoMsg(200.millis) @@ -316,14 +352,15 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") } // error conditions - "report failed connection attempt while not accepted" in withUnacceptedConnection() { setup ⇒ + "report failed connection attempt while not accepted" ignore withUnacceptedConnection() { setup ⇒ import setup._ // close instead of accept localServer.close() EventFilter[SocketException](occurrences = 1) intercept { selector.send(connectionActor, ChannelConnectable) - userHandler.expectMsgType[ErrorClosed].cause must be("Connection reset by peer") + val err = userHandler.expectMsgType[ErrorClosed] + nonWindows { err.cause must be("Connection reset by peer") } } verifyActorTermination(connectionActor) @@ -336,12 +373,14 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val sel = SelectorProvider.provider().openSelector() val key = clientSideChannel.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ) - sel.select(200) + // This timeout should be large enough to work on Windows + sel.select(3000) key.isConnectable must be(true) EventFilter[ConnectException](occurrences = 1) intercept { selector.send(connectionActor, ChannelConnectable) - userHandler.expectMsgType[ErrorClosed].cause must be("Connection refused") + val err = userHandler.expectMsgType[ErrorClosed] + nonWindows { err.cause must be("Connection refused") } } verifyActorTermination(connectionActor) @@ -572,7 +611,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") _selector: ActorRef, commander: ActorRef): TestActorRef[TcpOutgoingConnection] = { - TestActorRef( + val ref = TestActorRef( new TcpOutgoingConnection(Tcp(system), commander, Connect(serverAddress, localAddress, options)) { override def postRestart(reason: Throwable) { // ensure we never restart @@ -580,6 +619,9 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") } override def selector = _selector }) + + ref ! ChannelRegistered + ref } def abortClose(channel: SocketChannel): Unit = { diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala index b04d07d7d8..09ed457959 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpListenerSpec.scala @@ -12,6 +12,7 @@ import Tcp._ import akka.testkit.EventFilter import akka.io.SelectionHandler._ import java.nio.channels.SelectionKey._ +import akka.io.TcpListener.{ RegisterIncoming, FailedRegisterIncoming } class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { @@ -31,18 +32,25 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { attemptConnectionToEndpoint() attemptConnectionToEndpoint() + def expectWorkerForCommand: Unit = { + selectorRouter.expectMsgPF() { + case WorkerForCommand(RegisterIncoming(chan), commander, _) ⇒ + chan.isOpen must be(true) + commander must be === listener + } + } + // since the batch-accept-limit is 2 we must only receive 2 accepted connections listener ! ChannelAcceptable parent.expectMsg(AcceptInterest) - // FIXME: ugly stuff here - selectorRouter.expectMsgType[WorkerForCommand] - selectorRouter.expectMsgType[WorkerForCommand] + expectWorkerForCommand + expectWorkerForCommand selectorRouter.expectNoMsg(100.millis) // and pick up the last remaining connection on the next ChannelAcceptable listener ! ChannelAcceptable - selectorRouter.expectMsgType[WorkerForCommand] + expectWorkerForCommand } "react to Unbind commands by replying with Unbound and stopping itself" in new TestSetup { @@ -61,15 +69,17 @@ class TcpListenerSpec extends AkkaSpec("akka.io.tcp.batch-accept-limit = 2") { attemptConnectionToEndpoint() listener ! ChannelAcceptable - val props = selectorRouter.expectMsgType[WorkerForCommand].childProps - // FIXME: need to instantiate propss - //selectorRouter.expectMsgType[RegisterChannel].channel.isOpen must be(true) + val channel = selectorRouter.expectMsgPF() { + case WorkerForCommand(RegisterIncoming(chan), commander, _) ⇒ + chan.isOpen must be(true) + commander must be === listener + chan + } - // FIXME: fix this - // EventFilter.warning(pattern = "selector capacity limit", occurrences = 1) intercept { - // //listener ! CommandFailed(RegisterIncomingConnection(channel, handler.ref, Nil)) - // awaitCond(!channel.isOpen) - // } + EventFilter.warning(pattern = "selector capacity limit", occurrences = 1) intercept { + listener ! FailedRegisterIncoming(channel) + awaitCond(!channel.isOpen) + } } } diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index dffec75307..44e7b29163 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -76,7 +76,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, pendingWrite = createWrite(write) doWrite(handler) - case ChannelWritable ⇒ doWrite(handler) + case ChannelWritable ⇒ if (writePending) doWrite(handler) case cmd: CloseCommand ⇒ handleClose(handler, Some(sender), closeResponse(cmd)) } From 74396246ce35e4c4c9be75080c4fcaa5201a6b07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Thu, 7 Feb 2013 17:54:42 +0100 Subject: [PATCH 14/18] Connection based UDP fixed - SelectionHandler unregisters only selected interests, not all. - Fixed tests to be properly ignored on Windows --- .../scala/akka/io/TcpConnectionSpec.scala | 179 +++++++++++++----- .../akka/io/UdpConnIntegrationSpec.scala | 2 - .../scala/akka/io/UdpFFIntegrationSpec.scala | 8 +- .../main/scala/akka/io/SelectionHandler.scala | 6 +- .../main/scala/akka/io/UdpConnection.scala | 15 +- 5 files changed, 146 insertions(+), 64 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index 1e80f84fa1..c7658d96dc 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -19,7 +19,7 @@ import akka.io.SelectionHandler._ import TestUtils._ import akka.actor.{ ActorRef, PoisonPill, Terminated } import akka.testkit.{ AkkaSpec, EventFilter, TestActorRef, TestProbe } -import akka.util.ByteString +import akka.util.{ Helpers, ByteString } import akka.actor.DeathPactException import java.nio.channels.SelectionKey._ import akka.io.Inet.SocketOption @@ -28,9 +28,11 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val serverAddress = temporaryServerAddress() // Helper to avoid Windows localization specific differences - def nonWindows(body: ⇒ Any): Unit = { - if (!System.getProperty("os.name").toLowerCase().contains("win")) body - else log.warning("Detected Windows: ignoring check") + def ignoreIfWindows(): Unit = { + if (Helpers.isWindows) { + info("Detected Windows: ignoring check") + pending + } } "An outgoing connection" must { @@ -166,49 +168,47 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") * SO_SNDBUF to 0." */ "stop writing in cases of backpressure and resume afterwards" in - nonWindows { - withEstablishedConnection( - clientSocketOptions = List(SO.ReceiveBufferSize(1000000))) { setup ⇒ - import setup._ - object Ack1 - object Ack2 + withEstablishedConnection(clientSocketOptions = List(SO.ReceiveBufferSize(1000000))) { setup ⇒ + ignoreIfWindows() + import setup._ + object Ack1 + object Ack2 - clientSideChannel.socket.setSendBufferSize(1024) + clientSideChannel.socket.setSendBufferSize(1024) - awaitCond(clientSideChannel.socket.getSendBufferSize == 1024) + awaitCond(clientSideChannel.socket.getSendBufferSize == 1024) - val writer = TestProbe() + val writer = TestProbe() - // producing backpressure by sending much more than currently fits into - // our send buffer - val firstWrite = writeCmd(Ack1) + // producing backpressure by sending much more than currently fits into + // our send buffer + val firstWrite = writeCmd(Ack1) - // try to write the buffer but since the SO_SNDBUF is too small - // it will have to keep the rest of the piece and send it - // when possible - writer.send(connectionActor, firstWrite) - selector.expectMsg(WriteInterest) + // try to write the buffer but since the SO_SNDBUF is too small + // it will have to keep the rest of the piece and send it + // when possible + writer.send(connectionActor, firstWrite) + selector.expectMsg(WriteInterest) - // send another write which should fail immediately - // because we don't store more than one piece in flight - val secondWrite = writeCmd(Ack2) - writer.send(connectionActor, secondWrite) - writer.expectMsg(CommandFailed(secondWrite)) + // send another write which should fail immediately + // because we don't store more than one piece in flight + val secondWrite = writeCmd(Ack2) + writer.send(connectionActor, secondWrite) + writer.expectMsg(CommandFailed(secondWrite)) - // reject even empty writes - writer.send(connectionActor, Write.Empty) - writer.expectMsg(CommandFailed(Write.Empty)) + // reject even empty writes + writer.send(connectionActor, Write.Empty) + writer.expectMsg(CommandFailed(Write.Empty)) - // there will be immediately more space in the send buffer because - // some data will have been sent by now, so we assume we can write - // again, but still it can't write everything - selector.send(connectionActor, ChannelWritable) + // there will be immediately more space in the send buffer because + // some data will have been sent by now, so we assume we can write + // again, but still it can't write everything + selector.send(connectionActor, ChannelWritable) - // both buffers should now be filled so no more writing - // is possible - pullFromServerSide(TestSize) - writer.expectMsg(Ack1) - } + // both buffers should now be filled so no more writing + // is possible + pullFromServerSide(TestSize) + writer.expectMsg(Ack1) } "respect StopReading and ResumeReading" in withEstablishedConnection() { setup ⇒ @@ -256,7 +256,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") connectionHandler.expectNoMsg(500.millis) } - "abort the connection and reply with `Aborted` upong reception of an `Abort` command" in withEstablishedConnection() { setup ⇒ + "abort the connection and reply with `Aborted` upong reception of an `Abort` command (simplified)" in withEstablishedConnection() { setup ⇒ import setup._ connectionHandler.send(connectionActor, Abort) @@ -266,7 +266,20 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") val buffer = ByteBuffer.allocate(1) val thrown = evaluating { serverSideChannel.read(buffer) } must produce[IOException] - nonWindows { thrown.getMessage must be("Connection reset by peer") } + } + + "abort the connection and reply with `Aborted` upong reception of an `Abort` command" in withEstablishedConnection() { setup ⇒ + ignoreIfWindows() + import setup._ + + connectionHandler.send(connectionActor, Abort) + connectionHandler.expectMsg(Aborted) + + assertThisConnectionActorTerminated() + + val buffer = ByteBuffer.allocate(1) + val thrown = evaluating { serverSideChannel.read(buffer) } must produce[IOException] + thrown.getMessage must be("Connection reset by peer") } /* @@ -281,7 +294,7 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") * has hit the network medium. The only exception is when you disable the Winsock buffering by setting * SO_SNDBUF to 0." */ - "close the connection and reply with `ConfirmedClosed` upong reception of an `ConfirmedClose` command" in withEstablishedConnection(setSmallRcvBuffer) { setup ⇒ + "close the connection and reply with `ConfirmedClosed` upong reception of an `ConfirmedClose` command (simplified)" in withEstablishedConnection(setSmallRcvBuffer) { setup ⇒ import setup._ // we should test here that a pending write command is properly finished first @@ -294,12 +307,42 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") connectionHandler.send(connectionActor, writeCmd(Ack)) connectionHandler.send(connectionActor, ConfirmedClose) - nonWindows { connectionHandler.expectNoMsg(100.millis) } pullFromServerSide(TestSize) connectionHandler.expectMsg(Ack) selector.send(connectionActor, ChannelReadable) - nonWindows { connectionHandler.expectNoMsg(100.millis) } // not yet + + val buffer = ByteBuffer.allocate(1) + serverSelectionKey must be(selectedAs(SelectionKey.OP_READ, 2.seconds)) + serverSideChannel.read(buffer) must be(-1) + serverSideChannel.close() + + selector.send(connectionActor, ChannelReadable) + connectionHandler.expectMsg(ConfirmedClosed) + + assertThisConnectionActorTerminated() + } + + "close the connection and reply with `ConfirmedClosed` upong reception of an `ConfirmedClose` command" in withEstablishedConnection(setSmallRcvBuffer) { setup ⇒ + ignoreIfWindows() + import setup._ + + // we should test here that a pending write command is properly finished first + object Ack + // set an artificially small send buffer size so that the write is queued + // inside the connection actor + clientSideChannel.socket.setSendBufferSize(1024) + + // we send a write and a close command directly afterwards + connectionHandler.send(connectionActor, writeCmd(Ack)) + connectionHandler.send(connectionActor, ConfirmedClose) + + connectionHandler.expectNoMsg(100.millis) + pullFromServerSide(TestSize) + connectionHandler.expectMsg(Ack) + + selector.send(connectionActor, ChannelReadable) + connectionHandler.expectNoMsg(100.millis) // not yet val buffer = ByteBuffer.allocate(1) serverSelectionKey must be(selectedAs(SelectionKey.OP_READ, 2.seconds)) @@ -321,14 +364,29 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") assertThisConnectionActorTerminated() } - "report when peer aborted the connection" in withEstablishedConnection() { setup ⇒ + "report when peer aborted the connection (simplified)" in withEstablishedConnection() { setup ⇒ import setup._ EventFilter[IOException](occurrences = 1) intercept { abortClose(serverSideChannel) selector.send(connectionActor, ChannelReadable) val err = connectionHandler.expectMsgType[ErrorClosed] - nonWindows { err.cause must be("Connection reset by peer") } + } + // wait a while + connectionHandler.expectNoMsg(200.millis) + + assertThisConnectionActorTerminated() + } + + "report when peer aborted the connection" in withEstablishedConnection() { setup ⇒ + import setup._ + ignoreIfWindows() + + EventFilter[IOException](occurrences = 1) intercept { + abortClose(serverSideChannel) + selector.send(connectionActor, ChannelReadable) + val err = connectionHandler.expectMsgType[ErrorClosed] + err.cause must be("Connection reset by peer") } // wait a while connectionHandler.expectNoMsg(200.millis) @@ -351,23 +409,25 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") assertThisConnectionActorTerminated() } - // error conditions - "report failed connection attempt while not accepted" ignore withUnacceptedConnection() { setup ⇒ + // This tets is disabled on windows, as the assumption that not calling accept on a server socket means that + // no TCP level connection has been established with the client does not hold. + "report failed connection attempt while not accepted" in withUnacceptedConnection() { setup ⇒ import setup._ + ignoreIfWindows() // close instead of accept localServer.close() EventFilter[SocketException](occurrences = 1) intercept { selector.send(connectionActor, ChannelConnectable) val err = userHandler.expectMsgType[ErrorClosed] - nonWindows { err.cause must be("Connection reset by peer") } + err.cause must be("Connection reset by peer") } verifyActorTermination(connectionActor) } val UnboundAddress = temporaryServerAddress() - "report failed connection attempt when target is unreachable" in + "report failed connection attempt when target is unreachable (simplified)" in withUnacceptedConnection(connectionActorCons = createConnectionActor(serverAddress = UnboundAddress)) { setup ⇒ import setup._ @@ -380,7 +440,26 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") EventFilter[ConnectException](occurrences = 1) intercept { selector.send(connectionActor, ChannelConnectable) val err = userHandler.expectMsgType[ErrorClosed] - nonWindows { err.cause must be("Connection refused") } + } + + verifyActorTermination(connectionActor) + } + + "report failed connection attempt when target is unreachable" in + withUnacceptedConnection(connectionActorCons = createConnectionActor(serverAddress = UnboundAddress)) { setup ⇒ + import setup._ + ignoreIfWindows() + + val sel = SelectorProvider.provider().openSelector() + val key = clientSideChannel.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_READ) + // This timeout should be large enough to work on Windows + sel.select(3000) + + key.isConnectable must be(true) + EventFilter[ConnectException](occurrences = 1) intercept { + selector.send(connectionActor, ChannelConnectable) + val err = userHandler.expectMsgType[ErrorClosed] + err.cause must be("Connection refused") } verifyActorTermination(connectionActor) diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala index ece503de33..91742b8860 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpConnIntegrationSpec.scala @@ -40,8 +40,6 @@ class UdpConnIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Impli a } - println(clientAddress) - server ! UdpFF.Send(data2, clientAddress) // FIXME: Currently this line fails diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala index a0f138f041..270711cc76 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala @@ -41,7 +41,7 @@ class UdpFFIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Implici } "be able to send with binding" in { - val (serverAddress, _) = bindUdp(testActor) + val (serverAddress, server) = bindUdp(testActor) val (clientAddress, client) = bindUdp(testActor) val data = ByteString("Fly little packet!") @@ -52,6 +52,12 @@ class UdpFFIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Implici d must be === data a must be === clientAddress } + server ! Send(data, clientAddress) + expectMsgPF() { + case Received(d, a) ⇒ + d must be === data + a must be === serverAddress + } } } diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index e7046d8b34..57c02f0d25 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -188,9 +188,11 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler while (iterator.hasNext) { val key = iterator.next if (key.isValid) { - key.interestOps(0) // prevent immediate reselection by always clearing + // Cache because the performance implications of calling this on different platforms are not clear + val readyOps = key.readyOps() + key.interestOps(key.interestOps & ~readyOps) // prevent immediate reselection by always clearing val connection = key.attachment.asInstanceOf[ActorRef] - key.readyOps match { + readyOps match { case OP_READ ⇒ connection ! ChannelReadable case OP_WRITE ⇒ connection ! ChannelWritable case OP_READ_AND_WRITE ⇒ connection ! ChannelWritable; connection ! ChannelReadable diff --git a/akka-actor/src/main/scala/akka/io/UdpConnection.scala b/akka-actor/src/main/scala/akka/io/UdpConnection.scala index 32e6d09bb6..ff91a464fa 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnection.scala @@ -4,17 +4,14 @@ package akka.io import akka.actor.{ Actor, ActorLogging, ActorRef } -import akka.io.Inet.SocketOption import akka.io.SelectionHandler._ import akka.io.UdpConn._ import akka.util.ByteString -import java.net.InetSocketAddress +import java.nio.ByteBuffer import java.nio.channels.DatagramChannel import java.nio.channels.SelectionKey._ -import scala.collection.immutable -import scala.util.control.NonFatal -import java.nio.ByteBuffer import scala.annotation.tailrec +import scala.util.control.NonFatal private[io] class UdpConnection(val udpConn: UdpConnExt, val commander: ActorRef, @@ -22,8 +19,8 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, def selector: ActorRef = context.parent - import udpConn._ import connect._ + import udpConn._ import udpConn.settings._ var pendingSend: (Send, ActorRef) = null @@ -36,7 +33,7 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, val socket = datagramChannel.socket options.foreach(_.beforeDatagramBind(socket)) try { - localAddress foreach { socket.bind } // will blow up the actor constructor if the bind fails + localAddress.foreach { socket.bind _ } // will blow up the actor constructor if the bind fails datagramChannel.connect(remoteAddress) } catch { case NonFatal(e) ⇒ @@ -52,14 +49,13 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, def receive = { case ChannelRegistered ⇒ commander ! Connected - selector ! ReadInterest context.become(connected, discardOld = true) } def connected: Receive = { case StopReading ⇒ selector ! DisableReadInterest case ResumeReading ⇒ selector ! ReadInterest - case ChannelReadable ⇒ println("read"); doRead(handler) + case ChannelReadable ⇒ doRead(handler) case Close ⇒ log.debug("Closing UDP connection to {}", remoteAddress) @@ -89,6 +85,7 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, buffer.limit(DirectBufferSize) if (channel.read(buffer) > 0) { + buffer.flip() handler ! Received(ByteString(buffer)) innerRead(readsLeft - 1, buffer) } From e9da097621105e72f098a77db50b1acef12d5604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Sun, 10 Feb 2013 13:52:52 +0100 Subject: [PATCH 15/18] Fixed according to revew comments --- .../scala/akka/io/TcpConnectionSpec.scala | 5 +++- .../scala/akka/io/UdpFFIntegrationSpec.scala | 6 ++--- akka-actor/src/main/resources/reference.conf | 12 ++++----- akka-actor/src/main/scala/akka/io/IO.scala | 2 +- .../main/scala/akka/io/SelectionHandler.scala | 27 ++++++++++--------- akka-actor/src/main/scala/akka/io/Tcp.scala | 8 +++--- .../main/scala/akka/io/TcpConnection.scala | 12 ++++----- .../src/main/scala/akka/io/TcpListener.scala | 2 +- .../src/main/scala/akka/io/TcpManager.scala | 2 +- .../scala/akka/io/TcpOutgoingConnection.scala | 2 +- akka-actor/src/main/scala/akka/io/Udp.scala | 4 +-- .../src/main/scala/akka/io/UdpConn.scala | 6 ++--- .../main/scala/akka/io/UdpConnManager.scala | 2 +- .../main/scala/akka/io/UdpConnection.scala | 13 ++++----- akka-actor/src/main/scala/akka/io/UdpFF.scala | 6 ++--- .../main/scala/akka/io/UdpFFListener.scala | 15 ++++++----- .../src/main/scala/akka/io/UdpFFManager.scala | 2 +- .../src/main/scala/akka/io/UdpFFSender.scala | 13 ++++++--- .../main/scala/akka/io/WithUdpFFSend.scala | 24 +++++++++-------- 19 files changed, 87 insertions(+), 76 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala index c7658d96dc..cfd46d77c6 100644 --- a/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/TcpConnectionSpec.scala @@ -14,7 +14,7 @@ import scala.collection.immutable import scala.concurrent.duration._ import scala.util.control.NonFatal import org.scalatest.matchers._ -import Tcp._ +import akka.io.Tcp._ import akka.io.SelectionHandler._ import TestUtils._ import akka.actor.{ ActorRef, PoisonPill, Terminated } @@ -169,6 +169,9 @@ class TcpConnectionSpec extends AkkaSpec("akka.io.tcp.register-timeout = 500ms") */ "stop writing in cases of backpressure and resume afterwards" in withEstablishedConnection(clientSocketOptions = List(SO.ReceiveBufferSize(1000000))) { setup ⇒ + info("Currently ignored as SO_SNDBUF is usually a lower bound on the send buffer so the test fails as no real " + + "backpressure present.") + pending ignoreIfWindows() import setup._ object Ack1 diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala index 270711cc76..6cb6042b2f 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala @@ -34,10 +34,8 @@ class UdpFFIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Implici val data = ByteString("To infinity and beyond!") simpleSender ! Send(data, serverAddress) - expectMsgPF() { - case Received(d, _) ⇒ - d must be === data - } + expectMsgType[Received].data must be === data + } "be able to send with binding" in { diff --git a/akka-actor/src/main/resources/reference.conf b/akka-actor/src/main/resources/reference.conf index c17594a307..fd5051deb8 100644 --- a/akka-actor/src/main/resources/reference.conf +++ b/akka-actor/src/main/resources/reference.conf @@ -416,7 +416,7 @@ akka { # The maximal number of direct buffers kept in the direct buffer pool for # reuse. - max-direct-buffer-pool-size = 1000 + direct-buffer-pool-limit = 1000 # The duration a connection actor waits for a `Register` message from # its commander before aborting the connection. @@ -425,7 +425,7 @@ akka { # The maximum number of bytes delivered by a `Received` message. Before # more data is read from the network the connection actor will try to # do other work. - received-message-size-limit = unlimited + max-received-message-size = unlimited # Enable fine grained logging of what goes on inside the implementation. # Be aware that this may log more than once per message sent to the actors @@ -473,7 +473,7 @@ akka { # The maximum number of datagrams that are read in one go, # higher numbers decrease latency, lower numbers increase fairness on # the worker-dispatcher - batch-receive-limit = 3 + receive-throughput = 3 # The number of bytes per direct buffer in the pool used to read or write # network data from the kernel. @@ -481,7 +481,7 @@ akka { # The maximal number of direct buffers kept in the direct buffer pool for # reuse. - max-direct-buffer-pool-size = 1000 + direct-buffer-pool-limit = 1000 # The maximum number of bytes delivered by a `Received` message. Before # more data is read from the network the connection actor will try to @@ -534,7 +534,7 @@ akka { # The maximum number of datagrams that are read in one go, # higher numbers decrease latency, lower numbers increase fairness on # the worker-dispatcher - batch-receive-limit = 3 + receive-throughput = 3 # The number of bytes per direct buffer in the pool used to read or write # network data from the kernel. @@ -542,7 +542,7 @@ akka { # The maximal number of direct buffers kept in the direct buffer pool for # reuse. - max-direct-buffer-pool-size = 1000 + direct-buffer-pool-limit = 1000 # The maximum number of bytes delivered by a `Received` message. Before # more data is read from the network the connection actor will try to diff --git a/akka-actor/src/main/scala/akka/io/IO.scala b/akka-actor/src/main/scala/akka/io/IO.scala index 5b10023990..e238ffbaf2 100644 --- a/akka-actor/src/main/scala/akka/io/IO.scala +++ b/akka-actor/src/main/scala/akka/io/IO.scala @@ -33,7 +33,7 @@ object IO { WorkerForCommand(cmd, commander, props) } - def workerForCommand(pf: PartialFunction[Any, Props]): Receive = { + def workerForCommandHandler(pf: PartialFunction[Any, Props]): Receive = { case cmd: HasFailureMessage if pf.isDefinedAt(cmd) ⇒ selectorPool ! createWorkerMessage(pf)(cmd) } } diff --git a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala index 57c02f0d25..0d1c0d439e 100644 --- a/akka-actor/src/main/scala/akka/io/SelectionHandler.scala +++ b/akka-actor/src/main/scala/akka/io/SelectionHandler.scala @@ -94,15 +94,16 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler override def postStop() { try { - val iterator = selector.keys.iterator - while (iterator.hasNext) { - val key = iterator.next() - try key.channel.close() - catch { - case NonFatal(e) ⇒ log.error(e, "Error closing channel") + try { + val iterator = selector.keys.iterator + while (iterator.hasNext) { + val key = iterator.next() + try key.channel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing channel") + } } - } - selector.close() + } finally selector.close() } catch { case NonFatal(e) ⇒ log.error(e, "Error closing selector") } @@ -112,11 +113,11 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler override def supervisorStrategy = SupervisorStrategy.stoppingStrategy def withCapacityProtection(cmd: WorkerForCommand, retriesLeft: Int)(body: ⇒ Unit): Unit = { - log.debug("Executing {}", cmd) + log.debug("Executing [{}]", cmd) if (MaxChannelsPerSelector == -1 || childrenKeys.size < MaxChannelsPerSelector) { body } else { - log.warning("Rejecting '{}' with {} retries left, retrying...", cmd, retriesLeft) + log.warning("Rejecting [{}] with [{}] retries left, retrying...", cmd, retriesLeft) context.parent forward Retry(cmd, retriesLeft - 1) } } @@ -198,9 +199,9 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler case OP_READ_AND_WRITE ⇒ connection ! ChannelWritable; connection ! ChannelReadable case x if (x & OP_ACCEPT) > 0 ⇒ connection ! ChannelAcceptable case x if (x & OP_CONNECT) > 0 ⇒ connection ! ChannelConnectable - case x ⇒ log.warning("Invalid readyOps: {}", x) + case x ⇒ log.warning("Invalid readyOps: [{}]", x) } - } else log.warning("Invalid selection key: {}", key) + } else log.warning("Invalid selection key: [{}]", key) } keys.clear() // we need to remove the selected keys from the set, otherwise they remain selected } @@ -217,7 +218,7 @@ private[io] class SelectionHandler(manager: ActorRef, settings: SelectionHandler try tryRun() catch { case _: java.nio.channels.ClosedSelectorException ⇒ // ok, expected during shutdown - case NonFatal(e) ⇒ log.error(e, "Error during selector management task: {}", e) + case NonFatal(e) ⇒ log.error(e, "Error during selector management task: [{}]", e) } } } diff --git a/akka-actor/src/main/scala/akka/io/Tcp.scala b/akka-actor/src/main/scala/akka/io/Tcp.scala index 95218f16cf..97076477cf 100644 --- a/akka-actor/src/main/scala/akka/io/Tcp.scala +++ b/akka-actor/src/main/scala/akka/io/Tcp.scala @@ -16,7 +16,7 @@ import akka.actor._ object Tcp extends ExtensionKey[TcpExt] { // Java API - override def get(system: ActorSystem): TcpExt = system.extension(this) + override def get(system: ActorSystem): TcpExt = super.get(system) // shared socket options object SO extends Inet.SoForwarders { @@ -124,12 +124,12 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { val BatchAcceptLimit = getInt("batch-accept-limit") val DirectBufferSize = getIntBytes("direct-buffer-size") - val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") + val MaxDirectBufferPoolSize = getInt("direct-buffer-pool-limit") val RegisterTimeout = getString("register-timeout") match { case "infinite" ⇒ Duration.Undefined case x ⇒ Duration(x) } - val ReceivedMessageSizeLimit = getString("received-message-size-limit") match { + val ReceivedMessageSizeLimit = getString("max-received-message-size") match { case "unlimited" ⇒ Int.MaxValue case x ⇒ getIntBytes("received-message-size-limit") } @@ -150,7 +150,7 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { } } - val manager = { + val manager: ActorRef = { system.asInstanceOf[ActorSystemImpl].systemActorOf( props = Props(new TcpManager(this)).withDispatcher(Settings.ManagementDispatcher), name = "IO-TCP") diff --git a/akka-actor/src/main/scala/akka/io/TcpConnection.scala b/akka-actor/src/main/scala/akka/io/TcpConnection.scala index 44e7b29163..12e73bdaa1 100644 --- a/akka-actor/src/main/scala/akka/io/TcpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpConnection.scala @@ -40,7 +40,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, /** connection established, waiting for registration from user handler */ def waitingForRegistration(commander: ActorRef): Receive = { case Register(handler) ⇒ - if (TraceLogging) log.debug("{} registered as connection handler", handler) + if (TraceLogging) log.debug("[{}] registered as connection handler", handler) doRead(handler, None) // immediately try reading context.setReceiveTimeout(Duration.Undefined) @@ -54,7 +54,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, case ReceiveTimeout ⇒ // after sending `Register` user should watch this actor to make sure // it didn't die because of the timeout - log.warning("Configured registration timeout of {} expired, stopping", RegisterTimeout) + log.warning("Configured registration timeout of [{}] expired, stopping", RegisterTimeout) context.stop(self) } @@ -145,12 +145,12 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, if (TraceLogging) log.debug("Read nothing.") selector ! ReadInterest case GotCompleteData(data) ⇒ - if (TraceLogging) log.debug("Read {} bytes.", data.length) + if (TraceLogging) log.debug("Read [{}] bytes.", data.length) handler ! Received(data) selector ! ReadInterest case MoreDataWaiting(data) ⇒ - if (TraceLogging) log.debug("Read {} bytes. More data waiting.", data.length) + if (TraceLogging) log.debug("Read [{}] bytes. More data waiting.", data.length) handler ! Received(data) self ! ChannelReadable @@ -167,7 +167,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, val toWrite = pendingWrite.buffer.remaining() require(toWrite != 0) val writtenBytes = channel.write(pendingWrite.buffer) - if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes) + if (TraceLogging) log.debug("Wrote [{}] bytes to channel", writtenBytes) pendingWrite = pendingWrite.consume(writtenBytes) @@ -248,7 +248,7 @@ private[io] abstract class TcpConnection(val channel: SocketChannel, case NonFatal(e) ⇒ // setSoLinger can fail due to http://bugs.sun.com/view_bug.do?bug_id=6799574 // (also affected: OS/X Java 1.6.0_37) - if (TraceLogging) log.debug("setSoLinger(true, 0) failed with {}", e) + if (TraceLogging) log.debug("setSoLinger(true, 0) failed with [{}]", e) } channel.close() } diff --git a/akka-actor/src/main/scala/akka/io/TcpListener.scala b/akka-actor/src/main/scala/akka/io/TcpListener.scala index 51419fa0a5..d806fe8490 100644 --- a/akka-actor/src/main/scala/akka/io/TcpListener.scala +++ b/akka-actor/src/main/scala/akka/io/TcpListener.scala @@ -45,7 +45,7 @@ private[io] class TcpListener(val selectorRouter: ActorRef, catch { case NonFatal(e) ⇒ bindCommander ! CommandFailed(bind) - log.error(e, "Bind failed for TCP channel") + log.error(e, "Bind failed for TCP channel on endpoint [{}]", endpoint) context.stop(self) } serverSocketChannel diff --git a/akka-actor/src/main/scala/akka/io/TcpManager.scala b/akka-actor/src/main/scala/akka/io/TcpManager.scala index 032bcfd6bc..aa80e96c10 100644 --- a/akka-actor/src/main/scala/akka/io/TcpManager.scala +++ b/akka-actor/src/main/scala/akka/io/TcpManager.scala @@ -45,7 +45,7 @@ import akka.io.IO.SelectorBasedManager */ private[io] class TcpManager(tcp: TcpExt) extends SelectorBasedManager(tcp.Settings, tcp.Settings.NrOfSelectors) with ActorLogging { - def receive = workerForCommand { + def receive = workerForCommandHandler { case c: Connect ⇒ val commander = sender Props(new TcpOutgoingConnection(tcp, commander, c)) diff --git a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala index 39817efe99..03d978293e 100644 --- a/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala +++ b/akka-actor/src/main/scala/akka/io/TcpOutgoingConnection.scala @@ -31,7 +31,7 @@ private[io] class TcpOutgoingConnection(_tcp: TcpExt, def receive: Receive = { case ChannelRegistered ⇒ - log.debug("Attempting connection to {}", remoteAddress) + log.debug("Attempting connection to [{}]", remoteAddress) if (channel.connect(remoteAddress)) completeConnect(commander, options) else { diff --git a/akka-actor/src/main/scala/akka/io/Udp.scala b/akka-actor/src/main/scala/akka/io/Udp.scala index 83e8b0d5f1..840dda666d 100644 --- a/akka-actor/src/main/scala/akka/io/Udp.scala +++ b/akka-actor/src/main/scala/akka/io/Udp.scala @@ -28,8 +28,8 @@ object Udp { val NrOfSelectors = getInt("nr-of-selectors") val DirectBufferSize = getIntBytes("direct-buffer-size") - val MaxDirectBufferPoolSize = getInt("max-direct-buffer-pool-size") - val BatchReceiveLimit = getInt("batch-receive-limit") + val MaxDirectBufferPoolSize = getInt("direct-buffer-pool-limit") + val BatchReceiveLimit = getInt("receive-throughput") val ManagementDispatcher = getString("management-dispatcher") diff --git a/akka-actor/src/main/scala/akka/io/UdpConn.scala b/akka-actor/src/main/scala/akka/io/UdpConn.scala index df6715d2c5..aee429a716 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConn.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConn.scala @@ -12,7 +12,7 @@ import scala.collection.immutable object UdpConn extends ExtensionKey[UdpConnExt] { // Java API - override def get(system: ActorSystem): UdpConnExt = system.extension(this) + override def get(system: ActorSystem): UdpConnExt = super.get(system) trait Command extends IO.HasFailureMessage { def failureMessage = CommandFailed(this) @@ -51,9 +51,9 @@ object UdpConn extends ExtensionKey[UdpConnExt] { class UdpConnExt(system: ExtendedActorSystem) extends IO.Extension { - val settings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-fire-and-forget")) + val settings: UdpSettings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-fire-and-forget")) - val manager = { + val manager: ActorRef = { system.asInstanceOf[ActorSystemImpl].systemActorOf( props = Props(new UdpConnManager(this)), name = "IO-UDP-CONN") diff --git a/akka-actor/src/main/scala/akka/io/UdpConnManager.scala b/akka-actor/src/main/scala/akka/io/UdpConnManager.scala index a93a21259d..3868289c6b 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnManager.scala @@ -9,7 +9,7 @@ import akka.io.UdpConn.Connect class UdpConnManager(udpConn: UdpConnExt) extends SelectorBasedManager(udpConn.settings, udpConn.settings.NrOfSelectors) { - def receive = workerForCommand { + def receive = workerForCommandHandler { case c: Connect ⇒ val commander = sender Props(new UdpConnection(udpConn, commander, c)) diff --git a/akka-actor/src/main/scala/akka/io/UdpConnection.scala b/akka-actor/src/main/scala/akka/io/UdpConnection.scala index ff91a464fa..6d52adfb3b 100644 --- a/akka-actor/src/main/scala/akka/io/UdpConnection.scala +++ b/akka-actor/src/main/scala/akka/io/UdpConnection.scala @@ -33,18 +33,19 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, val socket = datagramChannel.socket options.foreach(_.beforeDatagramBind(socket)) try { - localAddress.foreach { socket.bind _ } // will blow up the actor constructor if the bind fails + localAddress foreach socket.bind datagramChannel.connect(remoteAddress) } catch { case NonFatal(e) ⇒ - log.error(e, "Failure while connecting UDP channel") + log.error(e, "Failure while connecting UDP channel to remote address [{}] local address [{}]", + remoteAddress, localAddress.map { _.toString }.getOrElse("undefined")) commander ! CommandFailed(connect) context.stop(self) } datagramChannel } selector ! RegisterChannel(channel, OP_READ) - log.debug("Successfully connected to {}", remoteAddress) + log.debug("Successfully connected to [{}]", remoteAddress) def receive = { case ChannelRegistered ⇒ @@ -58,10 +59,10 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, case ChannelReadable ⇒ doRead(handler) case Close ⇒ - log.debug("Closing UDP connection to {}", remoteAddress) + log.debug("Closing UDP connection to [{}]", remoteAddress) channel.close() sender ! Disconnected - log.debug("Connection closed to {}, stopping listener", remoteAddress) + log.debug("Connection closed to [{}], stopping listener", remoteAddress) context.stop(self) case send: Send if writePending ⇒ @@ -106,7 +107,7 @@ private[io] class UdpConnection(val udpConn: UdpConnExt, send.payload.copyToBuffer(buffer) buffer.flip() val writtenBytes = channel.write(buffer) - if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes) + if (TraceLogging) log.debug("Wrote [{}] bytes to channel", writtenBytes) // Datagram channel either sends the whole message, or nothing if (writtenBytes == 0) commander ! CommandFailed(send) diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index f6d86f7053..df935ebbaa 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -13,7 +13,7 @@ import scala.collection.immutable object UdpFF extends ExtensionKey[UdpFFExt] { // Java API - override def get(system: ActorSystem): UdpFFExt = system.extension(this) + override def get(system: ActorSystem): UdpFFExt = super.get(system) trait Command extends IO.HasFailureMessage { def failureMessage = CommandFailed(this) @@ -53,9 +53,9 @@ object UdpFF extends ExtensionKey[UdpFFExt] { class UdpFFExt(system: ExtendedActorSystem) extends IO.Extension { - val settings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-fire-and-forget")) + val settings: UdpSettings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-fire-and-forget")) - val manager = { + val manager: ActorRef = { system.asInstanceOf[ActorSystemImpl].systemActorOf( props = Props(new UdpFFManager(this)), name = "IO-UDP-FF") diff --git a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala index 0edccefab3..add5775832 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFListener.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFListener.scala @@ -35,13 +35,13 @@ private[io] class UdpFFListener(val udpFF: UdpFFExt, catch { case NonFatal(e) ⇒ bindCommander ! CommandFailed(bind) - log.error(e, "Failed to bind UDP channel") + log.error(e, "Failed to bind UDP channel to endpoint [{}]", endpoint) context.stop(self) } datagramChannel } context.parent ! RegisterChannel(channel, OP_READ) - log.debug("Successfully bound to {}", endpoint) + log.debug("Successfully bound to [{}]", endpoint) def receive: Receive = { case ChannelRegistered ⇒ @@ -55,11 +55,12 @@ private[io] class UdpFFListener(val udpFF: UdpFFExt, case ChannelReadable ⇒ doReceive(handler) case Unbind ⇒ - log.debug("Unbinding endpoint {}", endpoint) - channel.close() - sender ! Unbound - log.debug("Unbound endpoint {}, stopping listener", endpoint) - context.stop(self) + log.debug("Unbinding endpoint [{}]", endpoint) + try { + channel.close() + sender ! Unbound + log.debug("Unbound endpoint [{}], stopping listener", endpoint) + } finally context.stop(self) } def doReceive(handler: ActorRef): Unit = { diff --git a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala index 8e3e03617f..16d835ae49 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFManager.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFManager.scala @@ -44,7 +44,7 @@ import akka.io.UdpFF._ */ private[io] class UdpFFManager(udpFF: UdpFFExt) extends SelectorBasedManager(udpFF.settings, udpFF.settings.NrOfSelectors) { - def receive = workerForCommand { + def receive = workerForCommandHandler { case b: Bind ⇒ val commander = sender Props(new UdpFFListener(udpFF, commander, b)) diff --git a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala index 5303aa79d9..1120efba33 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFFSender.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFFSender.scala @@ -9,6 +9,7 @@ import akka.io.UdpFF._ import akka.io.SelectionHandler.{ ChannelRegistered, RegisterChannel } import scala.collection.immutable import akka.io.Inet.SocketOption +import scala.util.control.NonFatal /** * Base class for TcpIncomingConnection and TcpOutgoingConnection. @@ -23,9 +24,7 @@ private[io] class UdpFFSender(val udpFF: UdpFFExt, options: immutable.Traversabl datagramChannel.configureBlocking(false) val socket = datagramChannel.socket - options foreach { o ⇒ - o.beforeDatagramBind(socket) - } + options foreach { _.beforeDatagramBind(socket) } datagramChannel } @@ -37,7 +36,13 @@ private[io] class UdpFFSender(val udpFF: UdpFFExt, options: immutable.Traversabl commander ! SimpleSendReady } - override def postStop(): Unit = if (channel.isOpen) channel.close() + override def postStop(): Unit = if (channel.isOpen) { + log.debug("Closing DatagramChannel after being stopped") + try channel.close() + catch { + case NonFatal(e) ⇒ log.error(e, "Error closing DatagramChannel") + } + } override def postRestart(reason: Throwable): Unit = throw new IllegalStateException("Restarting not supported for connection actors.") diff --git a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala index 09dd37666c..99ed9393e2 100644 --- a/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala +++ b/akka-actor/src/main/scala/akka/io/WithUdpFFSend.scala @@ -11,11 +11,12 @@ import java.nio.channels.DatagramChannel private[io] trait WithUdpFFSend { me: Actor with ActorLogging ⇒ - var pendingSend: (Send, ActorRef) = null + var pendingSend: Send = null + var pendingCommander: ActorRef = null // If send fails first, we allow a second go after selected writable, but no more. This flag signals that // pending send was already tried once. var retriedSend = false - def writePending = pendingSend ne null + def hasWritePending = pendingSend ne null def selector: ActorRef def channel: DatagramChannel @@ -26,7 +27,7 @@ private[io] trait WithUdpFFSend { def sendHandlers: Receive = { - case send: Send if writePending ⇒ + case send: Send if hasWritePending ⇒ if (TraceLogging) log.debug("Dropping write because queue is full") sender ! CommandFailed(send) @@ -35,10 +36,11 @@ private[io] trait WithUdpFFSend { sender ! send.ack case send: Send ⇒ - pendingSend = (send, sender) + pendingSend = send + pendingCommander = sender doSend() - case ChannelWritable ⇒ doSend() + case ChannelWritable ⇒ if (hasWritePending) doSend() } @@ -46,24 +48,24 @@ private[io] trait WithUdpFFSend { val buffer = udpFF.bufferPool.acquire() try { - val (send, commander) = pendingSend buffer.clear() - send.payload.copyToBuffer(buffer) + pendingSend.payload.copyToBuffer(buffer) buffer.flip() - val writtenBytes = channel.send(buffer, send.target) - if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes) + val writtenBytes = channel.send(buffer, pendingSend.target) + if (TraceLogging) log.debug("Wrote [{}] bytes to channel", writtenBytes) // Datagram channel either sends the whole message, or nothing if (writtenBytes == 0) { if (retriedSend) { - commander ! CommandFailed(send) + pendingCommander ! CommandFailed(pendingSend) retriedSend = false pendingSend = null + pendingCommander = null } else { selector ! WriteInterest retriedSend = true } - } else if (send.wantsAck) commander ! send.ack + } else if (pendingSend.wantsAck) pendingCommander ! pendingSend.ack } finally { udpFF.bufferPool.release(buffer) From bddcf9ba8caa94e06eaa9b66db3e208796a0aeb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Sun, 10 Feb 2013 16:46:59 +0100 Subject: [PATCH 16/18] First iteration of documentation --- akka-docs/rst/scala/io-old.rst | 248 ++++++++++++++++++++++++++++++++ akka-docs/rst/scala/io.rst | 253 +++++++++++---------------------- 2 files changed, 334 insertions(+), 167 deletions(-) create mode 100644 akka-docs/rst/scala/io-old.rst diff --git a/akka-docs/rst/scala/io-old.rst b/akka-docs/rst/scala/io-old.rst new file mode 100644 index 0000000000..697f38651d --- /dev/null +++ b/akka-docs/rst/scala/io-old.rst @@ -0,0 +1,248 @@ +.. _io-scala-old: + +.. warning:: + This is the documentation of the old IO implementation that is considered now deprecated. Please take a look + at new IO API: :ref:`io-scala` + +IO (Scala) +========== + + +Introduction +------------ + +This documentation is in progress and some sections may be incomplete. More will be coming. + +Components +---------- + +ByteString +^^^^^^^^^^ + +A primary goal of Akka's IO support is to only communicate between actors with immutable objects. When dealing with network IO on the jvm ``Array[Byte]`` and ``ByteBuffer`` are commonly used to represent collections of ``Byte``\s, but they are mutable. Scala's collection library also lacks a suitably efficient immutable collection for ``Byte``\s. Being able to safely and efficiently move ``Byte``\s around is very important for this IO support, so ``ByteString`` was developed. + +``ByteString`` is a `Rope-like `_ data structure that is immutable and efficient. When 2 ``ByteString``\s are concatenated together they are both stored within the resulting ``ByteString`` instead of copying both to a new ``Array``. Operations such as ``drop`` and ``take`` return ``ByteString``\s that still reference the original ``Array``, but just change the offset and length that is visible. Great care has also been taken to make sure that the internal ``Array`` cannot be modified. Whenever a potentially unsafe ``Array`` is used to create a new ``ByteString`` a defensive copy is created. If you require a ``ByteString`` that only blocks a much memory as necessary for it's content, use the ``compact`` method to get a ``CompactByteString`` instance. If the ``ByteString`` represented only a slice of the original array, this will result in copying all bytes in that slice. + +``ByteString`` inherits all methods from ``IndexedSeq``, and it also has some new ones. For more information, look up the ``akka.util.ByteString`` class and it's companion object in the ScalaDoc. + +``ByteString`` also comes with it's own optimized builder and iterator classes ``ByteStringBuilder`` and ``ByteIterator`` which provides special features in addition to the standard builder / iterator methods: + +Compatibility with java.io +.......................... + +A ``ByteStringBuilder`` can be wrapped in a `java.io.OutputStream` via the ``asOutputStream`` method. Likewise, ``ByteIterator`` can we wrapped in a ``java.io.InputStream`` via ``asInputStream``. Using these, ``akka.io`` applications can integrate legacy code based on ``java.io`` streams. + +Encoding and decoding of binary data +.................................... + +``ByteStringBuilder`` and ``ByteIterator`` support encoding and decoding of binary data. As an example, consider a stream of binary data frames with the following format: + +.. code-block:: text + + frameLen: Int + n: Int + m: Int + n times { + a: Short + b: Long + } + data: m times Double + +In this example, the data is to be stored in arrays of ``a``, ``b`` and ``data``. + +Decoding of such frames can be efficiently implemented in the following fashion: + +.. includecode:: code/docs/io/BinaryCoding.scala + :include: decoding + +This implementation naturally follows the example data format. In a true Scala application, one might, of course, want use specialized immutable Short/Long/Double containers instead of mutable Arrays. + +After extracting data from a ``ByteIterator``, the remaining content can also be turned back into a ``ByteString`` using the ``toSeq`` method + +.. includecode:: code/docs/io/BinaryCoding.scala + :include: rest-to-seq + +with no copying from bytes to rest involved. In general, conversions from ByteString to ByteIterator and vice versa are O(1) for non-chunked ByteStrings and (at worst) O(nChunks) for chunked ByteStrings. + +Encoding of data also is very natural, using ``ByteStringBuilder`` + +.. includecode:: code/docs/io/BinaryCoding.scala + :include: encoding + + +The encoded data then can be sent over socket (see ``IOManager``): + +.. includecode:: code/docs/io/BinaryCoding.scala + :include: sending + + +IO.Handle +^^^^^^^^^ + +``IO.Handle`` is an immutable reference to a Java NIO ``Channel``. Passing mutable ``Channel``\s between ``Actor``\s could lead to unsafe behavior, so instead subclasses of the ``IO.Handle`` trait are used. Currently there are 2 concrete subclasses: ``IO.SocketHandle`` (representing a ``SocketChannel``) and ``IO.ServerHandle`` (representing a ``ServerSocketChannel``). + +IOManager +^^^^^^^^^ + +The ``IOManager`` takes care of the low level IO details. Each ``ActorSystem`` has it's own ``IOManager``, which can be accessed calling ``IOManager(system: ActorSystem)``. ``Actor``\s communicate with the ``IOManager`` with specific messages. The messages sent from an ``Actor`` to the ``IOManager`` are handled automatically when using certain methods and the messages sent from an ``IOManager`` are handled within an ``Actor``\'s ``receive`` method. + +Connecting to a remote host: + +.. code-block:: scala + + val address = new InetSocketAddress("remotehost", 80) + val socket = IOManager(actorSystem).connect(address) + +.. code-block:: scala + + val socket = IOManager(actorSystem).connect("remotehost", 80) + +Creating a server: + +.. code-block:: scala + + val address = new InetSocketAddress("localhost", 80) + val serverSocket = IOManager(actorSystem).listen(address) + +.. code-block:: scala + + val serverSocket = IOManager(actorSystem).listen("localhost", 80) + +Receiving messages from the ``IOManager``: + +.. code-block:: scala + + def receive = { + + case IO.Listening(server, address) => + println("The server is listening on socket " + address) + + case IO.Connected(socket, address) => + println("Successfully connected to " + address) + + case IO.NewClient(server) => + println("New incoming connection on server") + val socket = server.accept() + println("Writing to new client socket") + socket.write(bytes) + println("Closing socket") + socket.close() + + case IO.Read(socket, bytes) => + println("Received incoming data from socket") + + case IO.Closed(socket: IO.SocketHandle, cause) => + println("Socket has closed, cause: " + cause) + + case IO.Closed(server: IO.ServerHandle, cause) => + println("Server socket has closed, cause: " + cause) + + } + +IO.Iteratee +^^^^^^^^^^^ + +Included with Akka's IO support is a basic implementation of ``Iteratee``\s. ``Iteratee``\s are an effective way of handling a stream of data without needing to wait for all the data to arrive. This is especially useful when dealing with non blocking IO since we will usually receive data in chunks which may not include enough information to process, or it may contain much more data than we currently need. + +This ``Iteratee`` implementation is much more basic than what is usually found. There is only support for ``ByteString`` input, and enumerators aren't used. The reason for this limited implementation is to reduce the amount of explicit type signatures needed and to keep things simple. It is important to note that Akka's ``Iteratee``\s are completely optional, incoming data can be handled in any way, including other ``Iteratee`` libraries. + +``Iteratee``\s work by processing the data that it is given and returning either the result (with any unused input) or a continuation if more input is needed. They are monadic, so methods like ``flatMap`` can be used to pass the result of an ``Iteratee`` to another. + +The basic ``Iteratee``\s included in the IO support can all be found in the ScalaDoc under ``akka.actor.IO``, and some of them are covered in the example below. + +Examples +-------- + +Http Server +^^^^^^^^^^^ + +This example will create a simple high performance HTTP server. We begin with our imports: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: imports + +Some commonly used constants: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: constants + +And case classes to hold the resulting request: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: request-class + +Now for our first ``Iteratee``. There are 3 main sections of a HTTP request: the request line, the headers, and an optional body. The main request ``Iteratee`` handles each section separately: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-request + +In the above code ``readRequest`` takes the results of 3 different ``Iteratees`` (``readRequestLine``, ``readHeaders``, ``readBody``) and combines them into a single ``Request`` object. ``readRequestLine`` actually returns a tuple, so we extract it's individual components. ``readBody`` depends on values contained within the header section, so we must pass those to the method. + +The request line has 3 parts to it: the HTTP method, the requested URI, and the HTTP version. The parts are separated by a single space, and the entire request line ends with a ``CRLF``. + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-request-line + +Reading the request method is simple as it is a single string ending in a space. The simple ``Iteratee`` that performs this is ``IO.takeUntil(delimiter: ByteString): Iteratee[ByteString]``. It keeps consuming input until the specified delimiter is found. Reading the HTTP version is also a simple string that ends with a ``CRLF``. + +The ``ascii`` method is a helper that takes a ``ByteString`` and parses it as a ``US-ASCII`` ``String``. + +Reading the request URI is a bit more complicated because we want to parse the individual components of the URI instead of just returning a simple string: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-request-uri + +For this example we are only interested in handling absolute paths. To detect if we the URI is an absolute path we use ``IO.peek(length: Int): Iteratee[ByteString]``, which returns a ``ByteString`` of the request length but doesn't actually consume the input. We peek at the next bit of input and see if it matches our ``PATH`` constant (defined above as ``ByteString("/")``). If it doesn't match we throw an error, but for a more robust solution we would want to handle other valid URIs. + +Next we handle the path itself: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-path + +The ``step`` method is a recursive method that takes a ``List`` of the accumulated path segments. It first checks if the remaining input starts with the ``PATH`` constant, and if it does, it drops that input, and returns the ``readUriPart`` ``Iteratee`` which has it's result added to the path segment accumulator and the ``step`` method is run again. + +If after reading in a path segment the next input does not start with a path, we reverse the accumulated segments and return it (dropping the last segment if it is blank). + +Following the path we read in the query (if it exists): + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-query + +It is much simpler than reading the path since we aren't doing any parsing of the query since there is no standard format of the query string. + +Both the path and query used the ``readUriPart`` ``Iteratee``, which is next: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-uri-part + +Here we have several ``Set``\s that contain valid characters pulled from the URI spec. The ``readUriPart`` method takes a ``Set`` of valid characters (already mapped to ``Byte``\s) and will continue to match characters until it reaches on that is not part of the ``Set``. If it is a percent encoded character then that is handled as a valid character and processing continues, or else we are done collecting this part of the URI. + +Headers are next: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-headers + +And if applicable, we read in the message body: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: read-body + +Finally we get to the actual ``Actor``: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: actor + +And it's companion object: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: actor-companion + +And the OKResponse: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: ok-response + +A ``main`` method to start everything up: + +.. includecode:: code/docs/io/HTTPServer.scala + :include: main diff --git a/akka-docs/rst/scala/io.rst b/akka-docs/rst/scala/io.rst index abeb6b729c..3ef25a4e08 100644 --- a/akka-docs/rst/scala/io.rst +++ b/akka-docs/rst/scala/io.rst @@ -3,14 +3,67 @@ IO (Scala) ========== - Introduction ------------ +The ``akka.io`` package has been developed in collaboration between the Akka +and `spray.io`_ teams. Its design incorporates the experiences with the +``spray-io`` module along with improvements that were jointly developed for +more general consumption as an actor-based service. + This documentation is in progress and some sections may be incomplete. More will be coming. -Components ----------- +.. note:: + The old IO implementation has been deprecated and its documentation has been moved: :ref:`io-scala-old` + +Terminology, Concepts +--------------------- +The I/O API is completely actor based, meaning that all operations are implemented as message passing instead of +direct method calls. Every I/O driver (TCP, UDP) has a special actor, called *manager* that serves +as the entry point for the API. The manager is accessible through an extension, for example the following code +looks up the TCP manager and returns its ``ActorRef``: + +.. code-block:: scala + + import akka.io.IO + import akka.io.Tcp + val tcpManager = IO(Tcp) + +For various I/O commands the manager instantiates worker actors that will expose themselves to the user of the +API by replying to the command. For example after a ``Connect`` command sent to the TCP manager the manager creates +an actor representing the TCP connection. All operations related to the given TCP connections can be invoked by sending +messages to the connection actor which announces itself by sending a ``Connected`` message. + +DeathWatch and Resource Management +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Worker actors usually need a user-side counterpart actor listening for events (such events could be inbound connections, +incoming bytes or acknowledgements for writes). These worker actors *watch* their listener counterparts, therefore the +resources assigned to them are automatically released when the listener stops. This design makes the API more robust +against resource leaks. + +Write models (Ack, Nack) +^^^^^^^^^^^^^^^^^^^^^^^^ + +Basically all of the I/O devices have a maximum throughput which limits the frequency and size of writes. When an +application tries to push more data then a device can handle, the driver has to buffer all bytes that the device has +not yet been able to write. With this approach it is possible to handle short bursts of intensive writes --- but no buffer is infinite. +Therefore, the driver has to notify the writer (a user-side actor) either that no further writes are possible, or by +explicitly notifying it when the next chunk is possible to be written or buffered. + +Both of these models are available in the TCP and UDP implementations of Akka IO. Ack based flow control can be enabled +by providing an ack object in the write message (``Write`` in the case of TCP and ``Send`` for UDP) that will be used by +the worker to notify the writer about the success. + +If a write (or any other command) fails, the driver notifies the commander with a special message (``CommandFailed`` in +the case of UDP and TCP). This message also serves as a means to notify the writer of a failed write. Please note, that +in a Nack based flow-control setting the writer has to buffer some of the writes as the failure notification for a +write ``W1`` might arrive after additional write commands ``W2`` ``W3`` has been sent. + +.. warning:: + An acknowledged write does not mean acknowledged delivery or storage. The Ack/Nack + protocol described here is a means of flow control not error handling: receiving an Ack for a write signals that the + I/O driver is ready to accept a new one. ByteString ^^^^^^^^^^ @@ -57,7 +110,7 @@ After extracting data from a ``ByteIterator``, the remaining content can also be .. includecode:: code/docs/io/BinaryCoding.scala :include: rest-to-seq - + with no copying from bytes to rest involved. In general, conversions from ByteString to ByteIterator and vice versa are O(1) for non-chunked ByteStrings and (at worst) O(nChunks) for chunked ByteStrings. Encoding of data also is very natural, using ``ByteStringBuilder`` @@ -65,180 +118,46 @@ Encoding of data also is very natural, using ``ByteStringBuilder`` .. includecode:: code/docs/io/BinaryCoding.scala :include: encoding - -The encoded data then can be sent over socket (see ``IOManager``): - -.. includecode:: code/docs/io/BinaryCoding.scala - :include: sending +Using TCP +--------- +TODO -IO.Handle -^^^^^^^^^ +Connecting +^^^^^^^^^^ -``IO.Handle`` is an immutable reference to a Java NIO ``Channel``. Passing mutable ``Channel``\s between ``Actor``\s could lead to unsafe behavior, so instead subclasses of the ``IO.Handle`` trait are used. Currently there are 2 concrete subclasses: ``IO.SocketHandle`` (representing a ``SocketChannel``) and ``IO.ServerHandle`` (representing a ``ServerSocketChannel``). +TODO -IOManager -^^^^^^^^^ +Accepting connections +^^^^^^^^^^^^^^^^^^^^^ -The ``IOManager`` takes care of the low level IO details. Each ``ActorSystem`` has it's own ``IOManager``, which can be accessed calling ``IOManager(system: ActorSystem)``. ``Actor``\s communicate with the ``IOManager`` with specific messages. The messages sent from an ``Actor`` to the ``IOManager`` are handled automatically when using certain methods and the messages sent from an ``IOManager`` are handled within an ``Actor``\'s ``receive`` method. +TODO -Connecting to a remote host: +Using UDP +--------- -.. code-block:: scala +TODO - val address = new InetSocketAddress("remotehost", 80) - val socket = IOManager(actorSystem).connect(address) +Connectionless UDP +^^^^^^^^^^^^^^^^^^^ + - Simple send + - Bind and send -.. code-block:: scala +Connection based UDP +^^^^^^^^^^^^^^^^^^^^ - val socket = IOManager(actorSystem).connect("remotehost", 80) +.. note:: + There is some performance benefit in using connection based UDP API over the connectionless one -- if its possible. + If there is a SecurityManager enabled on the system, every connectionless message send has to go through a security + check, while in the case of connection-based UDP the security check is cached after connection, thus writes does + not suffer an additional performance penalty. -Creating a server: +Integration with Iteratees +-------------------------- -.. code-block:: scala +Architecture in-depth +--------------------- - val address = new InetSocketAddress("localhost", 80) - val serverSocket = IOManager(actorSystem).listen(address) +For further details on the design and internal architecture see :ref:`io-layer`. -.. code-block:: scala - - val serverSocket = IOManager(actorSystem).listen("localhost", 80) - -Receiving messages from the ``IOManager``: - -.. code-block:: scala - - def receive = { - - case IO.Listening(server, address) => - println("The server is listening on socket " + address) - - case IO.Connected(socket, address) => - println("Successfully connected to " + address) - - case IO.NewClient(server) => - println("New incoming connection on server") - val socket = server.accept() - println("Writing to new client socket") - socket.write(bytes) - println("Closing socket") - socket.close() - - case IO.Read(socket, bytes) => - println("Received incoming data from socket") - - case IO.Closed(socket: IO.SocketHandle, cause) => - println("Socket has closed, cause: " + cause) - - case IO.Closed(server: IO.ServerHandle, cause) => - println("Server socket has closed, cause: " + cause) - - } - -IO.Iteratee -^^^^^^^^^^^ - -Included with Akka's IO support is a basic implementation of ``Iteratee``\s. ``Iteratee``\s are an effective way of handling a stream of data without needing to wait for all the data to arrive. This is especially useful when dealing with non blocking IO since we will usually receive data in chunks which may not include enough information to process, or it may contain much more data than we currently need. - -This ``Iteratee`` implementation is much more basic than what is usually found. There is only support for ``ByteString`` input, and enumerators aren't used. The reason for this limited implementation is to reduce the amount of explicit type signatures needed and to keep things simple. It is important to note that Akka's ``Iteratee``\s are completely optional, incoming data can be handled in any way, including other ``Iteratee`` libraries. - -``Iteratee``\s work by processing the data that it is given and returning either the result (with any unused input) or a continuation if more input is needed. They are monadic, so methods like ``flatMap`` can be used to pass the result of an ``Iteratee`` to another. - -The basic ``Iteratee``\s included in the IO support can all be found in the ScalaDoc under ``akka.actor.IO``, and some of them are covered in the example below. - -Examples --------- - -Http Server -^^^^^^^^^^^ - -This example will create a simple high performance HTTP server. We begin with our imports: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: imports - -Some commonly used constants: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: constants - -And case classes to hold the resulting request: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: request-class - -Now for our first ``Iteratee``. There are 3 main sections of a HTTP request: the request line, the headers, and an optional body. The main request ``Iteratee`` handles each section separately: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-request - -In the above code ``readRequest`` takes the results of 3 different ``Iteratees`` (``readRequestLine``, ``readHeaders``, ``readBody``) and combines them into a single ``Request`` object. ``readRequestLine`` actually returns a tuple, so we extract it's individual components. ``readBody`` depends on values contained within the header section, so we must pass those to the method. - -The request line has 3 parts to it: the HTTP method, the requested URI, and the HTTP version. The parts are separated by a single space, and the entire request line ends with a ``CRLF``. - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-request-line - -Reading the request method is simple as it is a single string ending in a space. The simple ``Iteratee`` that performs this is ``IO.takeUntil(delimiter: ByteString): Iteratee[ByteString]``. It keeps consuming input until the specified delimiter is found. Reading the HTTP version is also a simple string that ends with a ``CRLF``. - -The ``ascii`` method is a helper that takes a ``ByteString`` and parses it as a ``US-ASCII`` ``String``. - -Reading the request URI is a bit more complicated because we want to parse the individual components of the URI instead of just returning a simple string: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-request-uri - -For this example we are only interested in handling absolute paths. To detect if we the URI is an absolute path we use ``IO.peek(length: Int): Iteratee[ByteString]``, which returns a ``ByteString`` of the request length but doesn't actually consume the input. We peek at the next bit of input and see if it matches our ``PATH`` constant (defined above as ``ByteString("/")``). If it doesn't match we throw an error, but for a more robust solution we would want to handle other valid URIs. - -Next we handle the path itself: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-path - -The ``step`` method is a recursive method that takes a ``List`` of the accumulated path segments. It first checks if the remaining input starts with the ``PATH`` constant, and if it does, it drops that input, and returns the ``readUriPart`` ``Iteratee`` which has it's result added to the path segment accumulator and the ``step`` method is run again. - -If after reading in a path segment the next input does not start with a path, we reverse the accumulated segments and return it (dropping the last segment if it is blank). - -Following the path we read in the query (if it exists): - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-query - -It is much simpler than reading the path since we aren't doing any parsing of the query since there is no standard format of the query string. - -Both the path and query used the ``readUriPart`` ``Iteratee``, which is next: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-uri-part - -Here we have several ``Set``\s that contain valid characters pulled from the URI spec. The ``readUriPart`` method takes a ``Set`` of valid characters (already mapped to ``Byte``\s) and will continue to match characters until it reaches on that is not part of the ``Set``. If it is a percent encoded character then that is handled as a valid character and processing continues, or else we are done collecting this part of the URI. - -Headers are next: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-headers - -And if applicable, we read in the message body: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: read-body - -Finally we get to the actual ``Actor``: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: actor - -And it's companion object: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: actor-companion - -And the OKResponse: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: ok-response - -A ``main`` method to start everything up: - -.. includecode:: code/docs/io/HTTPServer.scala - :include: main +.. _spray.io: http://spray.io \ No newline at end of file From 63264e847af024653ad6f15d0474449e386ac3b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Sun, 10 Feb 2013 18:34:29 +0100 Subject: [PATCH 17/18] Second iteration of documentation - Added basic UDP and TCP sections --- akka-docs/rst/scala/io.rst | 250 ++++++++++++++++++++++++++++++++++--- 1 file changed, 236 insertions(+), 14 deletions(-) diff --git a/akka-docs/rst/scala/io.rst b/akka-docs/rst/scala/io.rst index 3ef25a4e08..631f7a4c69 100644 --- a/akka-docs/rst/scala/io.rst +++ b/akka-docs/rst/scala/io.rst @@ -1,6 +1,6 @@ .. _io-scala: -IO (Scala) +I/O (Scala) ========== Introduction @@ -14,7 +14,7 @@ more general consumption as an actor-based service. This documentation is in progress and some sections may be incomplete. More will be coming. .. note:: - The old IO implementation has been deprecated and its documentation has been moved: :ref:`io-scala-old` + The old I/O implementation has been deprecated and its documentation has been moved: :ref:`io-scala-old` Terminology, Concepts --------------------- @@ -25,8 +25,6 @@ looks up the TCP manager and returns its ``ActorRef``: .. code-block:: scala - import akka.io.IO - import akka.io.Tcp val tcpManager = IO(Tcp) For various I/O commands the manager instantiates worker actors that will expose themselves to the user of the @@ -42,6 +40,9 @@ incoming bytes or acknowledgements for writes). These worker actors *watch* thei resources assigned to them are automatically released when the listener stops. This design makes the API more robust against resource leaks. +Thanks to the completely actor based approach of the I/O API the opposite direction works as well: a user actor +responsible for handling a connection might watch the connection actor to be notified if it unexpectedly terminates. + Write models (Ack, Nack) ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -51,7 +52,7 @@ not yet been able to write. With this approach it is possible to handle short bu Therefore, the driver has to notify the writer (a user-side actor) either that no further writes are possible, or by explicitly notifying it when the next chunk is possible to be written or buffered. -Both of these models are available in the TCP and UDP implementations of Akka IO. Ack based flow control can be enabled +Both of these models are available in the TCP and UDP implementations of Akka I/O. Ack based flow control can be enabled by providing an ack object in the write message (``Write`` in the case of TCP and ``Send`` for UDP) that will be used by the worker to notify the writer about the success. @@ -68,7 +69,7 @@ write ``W1`` might arrive after additional write commands ``W2`` ``W3`` has been ByteString ^^^^^^^^^^ -A primary goal of Akka's IO support is to only communicate between actors with immutable objects. When dealing with network IO on the jvm ``Array[Byte]`` and ``ByteBuffer`` are commonly used to represent collections of ``Byte``\s, but they are mutable. Scala's collection library also lacks a suitably efficient immutable collection for ``Byte``\s. Being able to safely and efficiently move ``Byte``\s around is very important for this IO support, so ``ByteString`` was developed. +A primary goal of Akka's IO support is to only communicate between actors with immutable objects. When dealing with network I/O on the jvm ``Array[Byte]`` and ``ByteBuffer`` are commonly used to represent collections of ``Byte``\s, but they are mutable. Scala's collection library also lacks a suitably efficient immutable collection for ``Byte``\s. Being able to safely and efficiently move ``Byte``\s around is very important for this I/O support, so ``ByteString`` was developed. ``ByteString`` is a `Rope-like `_ data structure that is immutable and efficient. When 2 ``ByteString``\s are concatenated together they are both stored within the resulting ``ByteString`` instead of copying both to a new ``Array``. Operations such as ``drop`` and ``take`` return ``ByteString``\s that still reference the original ``Array``, but just change the offset and length that is visible. Great care has also been taken to make sure that the internal ``Array`` cannot be modified. Whenever a potentially unsafe ``Array`` is used to create a new ``ByteString`` a defensive copy is created. If you require a ``ByteString`` that only blocks a much memory as necessary for it's content, use the ``compact`` method to get a ``CompactByteString`` instance. If the ``ByteString`` represented only a slice of the original array, this will result in copying all bytes in that slice. @@ -121,40 +122,261 @@ Encoding of data also is very natural, using ``ByteStringBuilder`` Using TCP --------- -TODO +As with all of the Akka I/O APIs, everything starts with acquiring a reference to the appropriate manager: + +.. code-block:: scala + + import akka.io.IO + import akka.io.Tcp + val tcpManager = IO(Tcp) + +This is an actor that handles the underlying low level I/O resources (Selectors, channels) and instantiates workers for +specific tasks, like listening to incoming connections. Connecting ^^^^^^^^^^ -TODO +The first step of connecting to a remote address is sending a ``Connect`` message to the TCP manager: + +.. code-block:: scala + + import akka.io.Tcp._ + IO(Tcp) ! Connect(remoteSocketAddress) + // It is also possible to set various socket options or specify a local address: + IO(Tcp) ! Connect(remoteSocketAddress, Some(localSocketAddress), List(SO.KeepAlive(true))) + +After issuing the Connect command the TCP manager spawns a worker actor that will handle commands related to the +connection. This worker actor will reveal itself by replying with a ``Connected`` message to the actor who sent the +``Connect`` command. + +.. code-block:: scala + + case Connected(remoteAddress, localAddress) => + connectionActor = sender + +At this point, there is still no listener associated with the connection. To finish the connection setup a ``Register`` +has to be sent to the connection actor with the listener ``ActorRef`` as a parameter. + +.. code-block:: scala + + connectionActor ! Register(listener) + +After registration, the listener actor provided in the ``listener`` parameter will be watched by the connection actor. +If the listener stops, the connection is closed, and all resources allocated for the connection released. During the +lifetime the listener may receive various event notifications: + +.. code-block:: scala + + case Received(dataByteString) => // handle incoming chunk of data + case CommandFailed(cmd) => // handle failure of command: cmd + case _: ConnectionClosed => // handle closed connections + +The last line handles all connection close events in the same way. It is possible to listen for more fine-grained +connection events, see the appropriate section below. + Accepting connections ^^^^^^^^^^^^^^^^^^^^^ +To create a TCP server and listen for inbound connection, a ``Bind`` command has to be sent to the TCP manager: + +.. code-block:: scala + + import akka.io.IO + import akka.io.Tcp + IO(Tcp) ! Bind(handler, localAddress) + +The actor sending the ``Bind`` message will receive a ``Bound`` message signalling that the server is ready to accept +incoming connections. Accepting connections is very similar to the last two steps of opening outbound connections: when +an incoming connection is established, the actor provided in ``handler`` will receive a ``Connected`` message whose +sender is the connection actor: + +.. code-block:: scala + + case Connected(remoteAddress, localAddress) => + connectionActor = sender + +At this point, there is still no listener associated with the connection. To finish the connection setup a ``Register`` +has to be sent to the connection actor with the listener ``ActorRef`` as a parameter. + +.. code-block:: scala + + connectionActor ! Register(listener) + +After registration, the listener actor provided in the ``listener`` parameter will be watched by the connection actor. +If the listener stops, the connection is closed, and all resources allocated for the connection released. During the +lifetime the listener will receive various event notifications in the same way as we has seen in the outbound +connection case. + +Closing connections +^^^^^^^^^^^^^^^^^^^ + +A connection can be closed by sending one of the commands ``Close``, ``ConfirmedClose`` or ``Abort`` to the connection +actor. + +``Close`` will close the connection by sending a ``FIN`` message, but without waiting for confirmation from +the remote endpoint. Pending writes will be flushed. If the close is successful, the listener will be notified with +``Closed`` + +``ConfirmedClose`` will close the sending direction of the connection by sending a ``FIN`` message, but receives +will continue until the remote endpoint closes the connection, too. Pending writes will be flushed. If the close is +successful, the listener will be notified with ``ConfirmedClosed`` + +``Abort`` will immediately terminate the connection by sending a ``RST`` message to the remote endpoint. Pending +writes will be not flushed. If the close is successful, the listener will be notified with ``Aborted`` + +``PeerClosed`` will be sent to the listener if the connection has been closed by the remote endpoint. + +``ErrorClosed`` will be sent to the listener whenever an error happened that forced the connection to be closed. + +All close notifications are subclasses of ``ConnectionClosed`` so listeners who do not need fine-grained close events +may handle all close events in the same way. + +Throttling Reads and Writes +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + TODO Using UDP --------- -TODO +UDP support comes in two flavors: connectionless, and connection based: + +.. code-block:: scala + + import akka.io.IO + import akka.io.UdpFF + val connectionLessUdp = IO(UdpFF) + // ... or ... + import akka.io.UdpConn + val connectionBasedUdp = IO(UdpConn) + +UDP servers can be only implemented by the connectionless API, but clients can use both. Connectionless UDP -^^^^^^^^^^^^^^^^^^^ - - Simple send - - Bind and send +^^^^^^^^^^^^^^^^^^ + +Simple Send +............ + +To simply send a UDP datagram without listening to an answer one needs to send the ``SimpleSender`` command to the +manager: + +.. code-block:: scala + + IO(UdpFF) ! SimpleSender() + // or with socket options: + import akka.io.Udp._ + IO(UdpFF) ! SimpleSender(List(SO.Broadcast(true))) + +The manager will create a worker for sending, and the worker will reply with a ``SimpleSendReady`` message: + +.. code-block:: scala + + case SimpleSendReady => + simpleSender = sender + +After saving the sender of the ``SimpleSendReady`` message it is possible to send out UDP datagrams with a simple +message send: + +.. code-block:: scala + + simpleSender ! Send(data, serverAddress) + + +Bind (and Send) +............... + +To listen for UDP datagrams arriving on a given port, the ``Bind`` command has to be sent to the connectionless UDP +manager + +.. code-block:: scala + + IO(UdpFF) ! Bind(handler, localAddress) + +After the bind succeeds, the sender of the ``Bind`` command will be notified with a ``Bound`` message. The sender of +this message is the worker for the UDP channel bound to the local address. + +.. code-block:: scala + + case Bound => + udpWorker = sender // Save the worker ref for later use + +The actor passed in the ``handler`` parameter will receive inbound UDP datagrams sent to the bound address: + +.. code-block:: scala + + case Received(dataByteString, remoteAddress) => // Do something with the data + +The ``Received`` message contains the payload of the datagram and the address of the sender. + +It is also possible to send UDP datagrams using the ``ActorRef`` of the worker saved in ``udpWorker``: + +.. code-block:: scala + + udpWorker ! Send(data, serverAddress) + +.. note:: + The difference between using a bound UDP worker to send instead of a simple-send worker is that in the former case + the sender field of the UDP datagram will be the bound local address, while in the latter it will be an undetermined + ephemeral port. Connection based UDP ^^^^^^^^^^^^^^^^^^^^ +The service provided by the connection based UDP API is similar to the bind-and-send service we have seen earlier, but +the main difference is that a connection is only able to send to the remoteAddress it was connected to, and will +receive datagrams only from that address. + +Connecting is similar to what we have seen in the previous section: + +.. code-block:: scala + + IO(UdpConn) ! Connect(handler, remoteAddress) + // or, with more options: + IO(UdpConn) ! Connect(handler, Some(localAddress), remoteAddress, List(SO.Broadcast(true))) + +After the connect succeeds, the sender of the ``Connect`` command will be notified with a ``Connected`` message. The sender of +this message is the worker for the UDP connection. + +.. code-block:: scala + + case Connected => + udpConnectionActor = sender // Save the worker ref for later use + +The actor passed in the ``handler`` parameter will receive inbound UDP datagrams sent to the bound address: + +.. code-block:: scala + + case Received(dataByteString) => // Do something with the data + +The ``Received`` message contains the payload of the datagram but unlike in the connectionless case, no sender address +will be provided, as an UDP connection only receives messages from the endpoint it has been connected to. + +It is also possible to send UDP datagrams using the ``ActorRef`` of the worker saved in ``udpWorker``: + +.. code-block:: scala + + udpConnectionActor ! Send(data) + +Again, the send does not contain a remote address, as it is always the endpoint we have been connected to. + .. note:: - There is some performance benefit in using connection based UDP API over the connectionless one -- if its possible. + There is a small performance benefit in using connection based UDP API over the connectionless one. If there is a SecurityManager enabled on the system, every connectionless message send has to go through a security - check, while in the case of connection-based UDP the security check is cached after connection, thus writes does + check, while in the case of connection-based UDP the security check is cached after connect, thus writes does not suffer an additional performance penalty. +Throttling Reads and Writes +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +TODO + Integration with Iteratees -------------------------- +TODO + Architecture in-depth --------------------- From 32d1a0072bd4b4f7142a153eb490d6c9089cb343 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20S=C3=A1ndor=20Varga?= Date: Tue, 12 Feb 2013 13:08:41 +0100 Subject: [PATCH 18/18] SimpleSender now works with the companion object --- .../src/test/scala/akka/io/UdpFFIntegrationSpec.scala | 2 +- akka-actor/src/main/scala/akka/io/UdpFF.scala | 1 + akka-docs/rst/scala/io.rst | 10 +++------- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala index 6cb6042b2f..88d41a21c4 100644 --- a/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/io/UdpFFIntegrationSpec.scala @@ -22,7 +22,7 @@ class UdpFFIntegrationSpec extends AkkaSpec("akka.loglevel = INFO") with Implici val simpleSender: ActorRef = { val commander = TestProbe() - commander.send(IO(UdpFF), SimpleSender(Nil)) + commander.send(IO(UdpFF), SimpleSender) commander.expectMsg(SimpleSendReady) commander.sender } diff --git a/akka-actor/src/main/scala/akka/io/UdpFF.scala b/akka-actor/src/main/scala/akka/io/UdpFF.scala index df935ebbaa..838f53a88d 100644 --- a/akka-actor/src/main/scala/akka/io/UdpFF.scala +++ b/akka-actor/src/main/scala/akka/io/UdpFF.scala @@ -35,6 +35,7 @@ object UdpFF extends ExtensionKey[UdpFFExt] { case object Unbind extends Command case class SimpleSender(options: immutable.Traversable[SocketOption] = Nil) extends Command + object SimpleSender extends SimpleSender(Nil) case object StopReading extends Command case object ResumeReading extends Command diff --git a/akka-docs/rst/scala/io.rst b/akka-docs/rst/scala/io.rst index 631f7a4c69..5f0331d8a2 100644 --- a/akka-docs/rst/scala/io.rst +++ b/akka-docs/rst/scala/io.rst @@ -235,7 +235,7 @@ may handle all close events in the same way. Throttling Reads and Writes ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -TODO +*This section is not yet ready. More coming soon* Using UDP --------- @@ -264,7 +264,7 @@ manager: .. code-block:: scala - IO(UdpFF) ! SimpleSender() + IO(UdpFF) ! SimpleSender // or with socket options: import akka.io.Udp._ IO(UdpFF) ! SimpleSender(List(SO.Broadcast(true))) @@ -370,12 +370,8 @@ Again, the send does not contain a remote address, as it is always the endpoint Throttling Reads and Writes ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -TODO +*This section is not yet ready. More coming soon* -Integration with Iteratees --------------------------- - -TODO Architecture in-depth ---------------------