2013-01-15 18:08:45 +01:00
|
|
|
/**
|
|
|
|
|
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
package akka.io
|
|
|
|
|
|
|
|
|
|
import java.net.InetSocketAddress
|
|
|
|
|
import java.io.IOException
|
|
|
|
|
import java.nio.channels.SocketChannel
|
2013-01-22 14:10:36 +01:00
|
|
|
import java.nio.ByteBuffer
|
|
|
|
|
import scala.annotation.tailrec
|
2013-01-22 16:03:22 +01:00
|
|
|
import scala.collection.immutable
|
2013-01-15 18:08:45 +01:00
|
|
|
import scala.util.control.NonFatal
|
|
|
|
|
import scala.concurrent.duration._
|
|
|
|
|
import akka.actor._
|
|
|
|
|
import akka.util.ByteString
|
|
|
|
|
import Tcp._
|
2013-01-22 14:10:36 +01:00
|
|
|
import TcpSelector._
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Base class for TcpIncomingConnection and TcpOutgoingConnection.
|
|
|
|
|
*/
|
2013-01-22 15:51:21 +01:00
|
|
|
private[io] abstract class TcpConnection(val channel: SocketChannel,
|
2013-01-22 14:10:36 +01:00
|
|
|
val tcp: TcpExt) extends Actor with ActorLogging with WithBufferPool {
|
2013-01-17 17:29:44 +01:00
|
|
|
import tcp.Settings._
|
2013-01-17 14:31:35 +01:00
|
|
|
var pendingWrite: PendingWrite = null
|
2013-01-17 14:45:50 +01:00
|
|
|
|
|
|
|
|
// Needed to send the ConnectionClosed message in the postStop handler.
|
2013-01-21 14:45:19 +01:00
|
|
|
var closedMessage: CloseInformation = null
|
2013-01-17 14:45:50 +01:00
|
|
|
|
2013-01-17 14:31:35 +01:00
|
|
|
def writePending = pendingWrite ne null
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-01-22 15:51:21 +01:00
|
|
|
def selector = context.parent
|
|
|
|
|
|
2013-01-15 18:08:45 +01:00
|
|
|
// STATES
|
|
|
|
|
|
|
|
|
|
/** connection established, waiting for registration from user handler */
|
|
|
|
|
def waitingForRegistration(commander: ActorRef): Receive = {
|
|
|
|
|
case Register(handler) ⇒
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("{} registered as connection handler", handler)
|
2013-01-15 18:08:45 +01:00
|
|
|
selector ! ReadInterest
|
|
|
|
|
|
|
|
|
|
context.setReceiveTimeout(Duration.Undefined)
|
|
|
|
|
context.watch(handler) // sign death pact
|
|
|
|
|
|
|
|
|
|
context.become(connected(handler))
|
|
|
|
|
|
|
|
|
|
case cmd: CloseCommand ⇒
|
2013-01-21 14:45:19 +01:00
|
|
|
handleClose(commander, Some(sender), closeResponse(cmd))
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
case ReceiveTimeout ⇒
|
2013-01-17 14:45:50 +01:00
|
|
|
// after sending `Register` user should watch this actor to make sure
|
|
|
|
|
// it didn't die because of the timeout
|
2013-01-17 17:29:44 +01:00
|
|
|
log.warning("Configured registration timeout of {} expired, stopping", RegisterTimeout)
|
2013-01-15 18:08:45 +01:00
|
|
|
context.stop(self)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** normal connected state */
|
|
|
|
|
def connected(handler: ActorRef): Receive = {
|
|
|
|
|
case StopReading ⇒ selector ! StopReading
|
|
|
|
|
case ResumeReading ⇒ selector ! ReadInterest
|
2013-01-21 14:45:19 +01:00
|
|
|
case ChannelReadable ⇒ doRead(handler, None)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
case write: Write if writePending ⇒
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Dropping write because queue is full")
|
2013-01-17 14:45:50 +01:00
|
|
|
sender ! CommandFailed(write)
|
|
|
|
|
|
|
|
|
|
case write: Write if write.data.isEmpty ⇒
|
|
|
|
|
if (write.wantsAck)
|
|
|
|
|
sender ! write.ack
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-01-17 14:45:50 +01:00
|
|
|
case write: Write ⇒
|
2013-01-17 14:31:35 +01:00
|
|
|
pendingWrite = createWrite(write)
|
|
|
|
|
|
2013-01-17 14:45:50 +01:00
|
|
|
doWrite(handler)
|
|
|
|
|
case ChannelWritable ⇒ doWrite(handler)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
case cmd: CloseCommand ⇒ handleClose(handler, Some(sender), closeResponse(cmd))
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** connection is closing but a write has to be finished first */
|
2013-01-21 14:45:19 +01:00
|
|
|
def closingWithPendingWrite(handler: ActorRef, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Receive = {
|
2013-01-15 18:08:45 +01:00
|
|
|
case StopReading ⇒ selector ! StopReading
|
|
|
|
|
case ResumeReading ⇒ selector ! ReadInterest
|
2013-01-21 14:45:19 +01:00
|
|
|
case ChannelReadable ⇒ doRead(handler, closeCommander)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
case ChannelWritable ⇒
|
2013-01-17 14:45:50 +01:00
|
|
|
doWrite(handler)
|
2013-01-15 18:08:45 +01:00
|
|
|
if (!writePending) // writing is now finished
|
2013-01-21 14:45:19 +01:00
|
|
|
handleClose(handler, closeCommander, closedEvent)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
case Abort ⇒ handleClose(handler, Some(sender), Aborted)
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** connection is closed on our side and we're waiting from confirmation from the other side */
|
2013-01-21 14:45:19 +01:00
|
|
|
def closing(handler: ActorRef, closeCommander: Option[ActorRef]): Receive = {
|
2013-01-15 18:08:45 +01:00
|
|
|
case StopReading ⇒ selector ! StopReading
|
|
|
|
|
case ResumeReading ⇒ selector ! ReadInterest
|
2013-01-21 14:45:19 +01:00
|
|
|
case ChannelReadable ⇒ doRead(handler, closeCommander)
|
|
|
|
|
case Abort ⇒ handleClose(handler, Some(sender), Aborted)
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// AUXILIARIES and IMPLEMENTATION
|
|
|
|
|
|
2013-01-21 17:02:20 +01:00
|
|
|
/** used in subclasses to start the common machinery above once a channel is connected */
|
2013-01-22 16:03:22 +01:00
|
|
|
def completeConnect(commander: ActorRef, options: immutable.Traversable[SocketOption]): Unit = {
|
2013-01-15 18:08:45 +01:00
|
|
|
options.foreach(_.afterConnect(channel.socket))
|
|
|
|
|
|
|
|
|
|
commander ! Connected(
|
|
|
|
|
channel.socket.getRemoteSocketAddress.asInstanceOf[InetSocketAddress],
|
|
|
|
|
channel.socket.getLocalSocketAddress.asInstanceOf[InetSocketAddress])
|
|
|
|
|
|
2013-01-17 17:29:44 +01:00
|
|
|
context.setReceiveTimeout(RegisterTimeout)
|
2013-01-15 18:08:45 +01:00
|
|
|
context.become(waitingForRegistration(commander))
|
|
|
|
|
}
|
|
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
def doRead(handler: ActorRef, closeCommander: Option[ActorRef]): Unit = {
|
2013-01-17 14:31:35 +01:00
|
|
|
val buffer = acquireBuffer()
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
val readBytes = channel.read(buffer)
|
|
|
|
|
buffer.flip()
|
|
|
|
|
|
|
|
|
|
if (readBytes > 0) {
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Read {} bytes", readBytes)
|
2013-01-17 14:45:50 +01:00
|
|
|
handler ! Received(ByteString(buffer))
|
2013-01-17 14:31:35 +01:00
|
|
|
releaseBuffer(buffer)
|
|
|
|
|
|
2013-01-15 18:08:45 +01:00
|
|
|
if (readBytes == buffer.capacity())
|
|
|
|
|
// directly try reading more because we exhausted our buffer
|
|
|
|
|
self ! ChannelReadable
|
|
|
|
|
else selector ! ReadInterest
|
|
|
|
|
} else if (readBytes == 0) {
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Read nothing. Registering read interest with selector")
|
2013-01-15 18:08:45 +01:00
|
|
|
selector ! ReadInterest
|
|
|
|
|
} else if (readBytes == -1) {
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Read returned end-of-stream")
|
2013-01-21 14:45:19 +01:00
|
|
|
doCloseConnection(handler, closeCommander, closeReason)
|
2013-01-15 18:08:45 +01:00
|
|
|
} else throw new IllegalStateException("Unexpected value returned from read: " + readBytes)
|
|
|
|
|
|
|
|
|
|
} catch {
|
|
|
|
|
case e: IOException ⇒ handleError(handler, e)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
final def doWrite(handler: ActorRef): Unit = {
|
|
|
|
|
@tailrec def innerWrite(): Unit = {
|
|
|
|
|
val toWrite = pendingWrite.buffer.remaining()
|
|
|
|
|
require(toWrite != 0)
|
2013-01-17 14:31:35 +01:00
|
|
|
val writtenBytes = channel.write(pendingWrite.buffer)
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Wrote {} bytes to channel", writtenBytes)
|
2013-01-17 14:31:35 +01:00
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
pendingWrite = pendingWrite.consume(writtenBytes)
|
|
|
|
|
|
|
|
|
|
if (pendingWrite.hasData)
|
2013-01-22 17:32:46 +01:00
|
|
|
if (writtenBytes == toWrite) innerWrite() // wrote complete buffer, try again now
|
2013-01-21 14:45:19 +01:00
|
|
|
else selector ! WriteInterest // try again later
|
2013-01-22 17:32:46 +01:00
|
|
|
else { // everything written
|
|
|
|
|
if (pendingWrite.wantsAck)
|
|
|
|
|
pendingWrite.commander ! pendingWrite.ack
|
|
|
|
|
|
|
|
|
|
val buffer = pendingWrite.buffer
|
2013-01-17 14:31:35 +01:00
|
|
|
pendingWrite = null
|
2013-01-22 17:32:46 +01:00
|
|
|
|
|
|
|
|
releaseBuffer(buffer)
|
2013-01-17 14:31:35 +01:00
|
|
|
}
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
2013-01-21 14:45:19 +01:00
|
|
|
|
|
|
|
|
try innerWrite()
|
|
|
|
|
catch { case e: IOException ⇒ handleError(handler, e) }
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def closeReason =
|
|
|
|
|
if (channel.socket.isOutputShutdown) ConfirmedClosed
|
|
|
|
|
else PeerClosed
|
|
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
def handleClose(handler: ActorRef, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Unit =
|
2013-01-15 18:08:45 +01:00
|
|
|
if (closedEvent == Aborted) { // close instantly
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Got Abort command. RESETing connection.")
|
2013-01-21 14:45:19 +01:00
|
|
|
doCloseConnection(handler, closeCommander, closedEvent)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
} else if (writePending) { // finish writing first
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Got Close command but write is still pending.")
|
2013-01-21 14:45:19 +01:00
|
|
|
context.become(closingWithPendingWrite(handler, closeCommander, closedEvent))
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
} else if (closedEvent == ConfirmedClosed) { // shutdown output and wait for confirmation
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Got ConfirmedClose command, sending FIN.")
|
2013-01-15 18:08:45 +01:00
|
|
|
channel.socket.shutdownOutput()
|
2013-01-21 14:45:19 +01:00
|
|
|
context.become(closing(handler, closeCommander))
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
} else { // close now
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Got Close command, closing connection.")
|
2013-01-21 14:45:19 +01:00
|
|
|
doCloseConnection(handler, closeCommander, closedEvent)
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
def doCloseConnection(handler: ActorRef, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Unit = {
|
2013-01-15 18:08:45 +01:00
|
|
|
if (closedEvent == Aborted) abort()
|
|
|
|
|
else channel.close()
|
|
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
closedMessage = CloseInformation(Set(handler) ++ closeCommander, closedEvent)
|
2013-01-17 14:45:50 +01:00
|
|
|
|
2013-01-15 18:08:45 +01:00
|
|
|
context.stop(self)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def closeResponse(closeCommand: CloseCommand): ConnectionClosed =
|
|
|
|
|
closeCommand match {
|
|
|
|
|
case Close ⇒ Closed
|
|
|
|
|
case Abort ⇒ Aborted
|
|
|
|
|
case ConfirmedClose ⇒ ConfirmedClosed
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def handleError(handler: ActorRef, exception: IOException): Unit = {
|
2013-01-21 14:45:19 +01:00
|
|
|
closedMessage = CloseInformation(Set(handler), ErrorClose(extractMsg(exception)))
|
2013-01-17 14:45:50 +01:00
|
|
|
|
2013-01-15 18:08:45 +01:00
|
|
|
throw exception
|
|
|
|
|
}
|
2013-01-17 14:45:50 +01:00
|
|
|
@tailrec private[this] def extractMsg(t: Throwable): String =
|
|
|
|
|
if (t == null) "unknown"
|
|
|
|
|
else {
|
|
|
|
|
t.getMessage match {
|
|
|
|
|
case null | "" ⇒ extractMsg(t.getCause)
|
|
|
|
|
case msg ⇒ msg
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
def abort(): Unit = {
|
|
|
|
|
try channel.socket.setSoLinger(true, 0) // causes the following close() to send TCP RST
|
|
|
|
|
catch {
|
|
|
|
|
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)
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("setSoLinger(true, 0) failed with {}", e)
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
channel.close()
|
|
|
|
|
}
|
|
|
|
|
|
2013-01-17 14:45:50 +01:00
|
|
|
override def postStop(): Unit = {
|
2013-01-22 17:32:46 +01:00
|
|
|
if (channel.isOpen)
|
|
|
|
|
abort()
|
|
|
|
|
|
|
|
|
|
if (writePending)
|
|
|
|
|
releaseBuffer(pendingWrite.buffer)
|
|
|
|
|
|
2013-01-17 14:45:50 +01:00
|
|
|
if (closedMessage != null) {
|
2013-01-21 14:45:19 +01:00
|
|
|
val interestedInClose =
|
|
|
|
|
if (writePending) closedMessage.notificationsTo + pendingWrite.commander
|
|
|
|
|
else closedMessage.notificationsTo
|
2013-01-17 14:45:50 +01:00
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
interestedInClose.foreach(_ ! closedMessage.closedEvent)
|
2013-01-17 14:45:50 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
override def postRestart(reason: Throwable): Unit =
|
|
|
|
|
throw new IllegalStateException("Restarting not supported for connection actors.")
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
private[TcpConnection] case class PendingWrite(
|
|
|
|
|
commander: ActorRef,
|
|
|
|
|
ack: Any,
|
|
|
|
|
remainingData: ByteString,
|
|
|
|
|
buffer: ByteBuffer) {
|
|
|
|
|
|
|
|
|
|
def consume(writtenBytes: Int): PendingWrite =
|
|
|
|
|
if (buffer.remaining() == 0) {
|
|
|
|
|
buffer.clear()
|
|
|
|
|
val copied = remainingData.copyToBuffer(buffer)
|
|
|
|
|
buffer.flip()
|
|
|
|
|
copy(remainingData = remainingData.drop(copied))
|
|
|
|
|
} else this
|
|
|
|
|
|
|
|
|
|
def hasData = buffer.remaining() > 0 || remainingData.size > 0
|
2013-01-18 13:20:17 +01:00
|
|
|
def wantsAck = ack != NoAck
|
2013-01-17 14:31:35 +01:00
|
|
|
}
|
|
|
|
|
def createWrite(write: Write): PendingWrite = {
|
2013-01-21 14:45:19 +01:00
|
|
|
val buffer = acquireBuffer()
|
|
|
|
|
val copied = write.data.copyToBuffer(buffer)
|
2013-01-17 14:31:35 +01:00
|
|
|
buffer.flip()
|
|
|
|
|
|
2013-01-21 14:45:19 +01:00
|
|
|
PendingWrite(sender, write.ack, write.data.drop(copied), buffer)
|
2013-01-17 14:31:35 +01:00
|
|
|
}
|
2013-01-21 14:45:19 +01:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Used to transport information to the postStop method to notify
|
|
|
|
|
* interested party about a connection close.
|
|
|
|
|
*/
|
|
|
|
|
private[TcpConnection] case class CloseInformation(
|
|
|
|
|
notificationsTo: Set[ActorRef],
|
|
|
|
|
closedEvent: ConnectionClosed)
|
2013-01-22 15:51:21 +01:00
|
|
|
}
|