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
|
2013-05-06 17:01:01 +02:00
|
|
|
import java.nio.channels.SelectionKey._
|
2013-04-09 14:22:20 +02:00
|
|
|
import java.io.{ FileInputStream, IOException }
|
|
|
|
|
import java.nio.channels.{ FileChannel, 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
|
2013-02-05 11:48:47 +01:00
|
|
|
import akka.io.Inet.SocketOption
|
|
|
|
|
import akka.io.Tcp._
|
2013-02-01 13:11:17 +01:00
|
|
|
import akka.io.SelectionHandler._
|
2013-04-26 12:18:01 +02:00
|
|
|
import akka.dispatch.{ UnboundedMessageQueueSemantics, RequiresMessageQueue }
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Base class for TcpIncomingConnection and TcpOutgoingConnection.
|
2013-02-15 11:59:01 +01:00
|
|
|
*
|
|
|
|
|
* INTERNAL API
|
2013-01-15 18:08:45 +01:00
|
|
|
*/
|
2013-05-06 17:01:01 +02:00
|
|
|
private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketChannel)
|
2013-04-26 12:18:01 +02:00
|
|
|
extends Actor with ActorLogging with RequiresMessageQueue[UnboundedMessageQueueSemantics] {
|
2013-05-06 17:01:01 +02:00
|
|
|
|
2013-01-17 17:29:44 +01:00
|
|
|
import tcp.Settings._
|
2013-02-04 16:24:34 +01:00
|
|
|
import tcp.bufferPool
|
2013-01-24 15:08:42 +01:00
|
|
|
import TcpConnection._
|
2013-01-17 14:45:50 +01:00
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
private[this] var pendingWrite: PendingWrite = _
|
2013-04-11 14:28:14 +02:00
|
|
|
private[this] var peerClosed = false
|
2013-05-06 17:01:01 +02:00
|
|
|
private[this] var writingSuspended = false
|
|
|
|
|
private[this] var interestedInResume: Option[ActorRef] = None
|
|
|
|
|
var closedMessage: CloseInformation = _ // for ConnectionClosed message in postStop
|
2013-04-07 17:05:22 +02:00
|
|
|
|
2013-01-17 14:31:35 +01:00
|
|
|
def writePending = pendingWrite ne null
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
// STATES
|
|
|
|
|
|
|
|
|
|
/** connection established, waiting for registration from user handler */
|
2013-05-06 17:01:01 +02:00
|
|
|
def waitingForRegistration(registration: ChannelRegistration, commander: ActorRef): Receive = {
|
2013-04-16 22:31:09 +02:00
|
|
|
case Register(handler, keepOpenOnPeerClosed, useResumeWriting) ⇒
|
2013-04-11 14:31:01 +02:00
|
|
|
// up to this point we've been watching the commander,
|
|
|
|
|
// but since registration is now complete we only need to watch the handler from here on
|
|
|
|
|
if (handler != commander) {
|
|
|
|
|
context.unwatch(commander)
|
|
|
|
|
context.watch(handler)
|
|
|
|
|
}
|
2013-02-10 13:52:52 +01:00
|
|
|
if (TraceLogging) log.debug("[{}] registered as connection handler", handler)
|
2013-04-07 17:05:22 +02:00
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
val info = ConnectionInfo(registration, handler, keepOpenOnPeerClosed, useResumeWriting)
|
|
|
|
|
doRead(info, None) // immediately try reading
|
2013-01-15 18:08:45 +01:00
|
|
|
context.setReceiveTimeout(Duration.Undefined)
|
2013-05-06 17:01:01 +02:00
|
|
|
context.become(connected(info))
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
case cmd: CloseCommand ⇒
|
2013-05-06 17:01:01 +02:00
|
|
|
val info = ConnectionInfo(registration, commander, keepOpenOnPeerClosed = false, useResumeWriting = false)
|
|
|
|
|
handleClose(info, Some(sender), cmd.event)
|
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-02-10 13:52:52 +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 */
|
2013-05-06 17:01:01 +02:00
|
|
|
def connected(info: ConnectionInfo): Receive =
|
|
|
|
|
handleWriteMessages(info) orElse {
|
|
|
|
|
case SuspendReading ⇒ info.registration.disableInterest(OP_READ)
|
|
|
|
|
case ResumeReading ⇒ info.registration.enableInterest(OP_READ)
|
|
|
|
|
case ChannelReadable ⇒ doRead(info, None)
|
|
|
|
|
case cmd: CloseCommand ⇒ handleClose(info, Some(sender), cmd.event)
|
|
|
|
|
}
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-04-02 15:17:48 +02:00
|
|
|
/** the peer sent EOF first, but we may still want to send */
|
2013-05-06 17:01:01 +02:00
|
|
|
def peerSentEOF(info: ConnectionInfo): Receive =
|
|
|
|
|
handleWriteMessages(info) orElse {
|
|
|
|
|
case cmd: CloseCommand ⇒ handleClose(info, Some(sender), cmd.event)
|
|
|
|
|
}
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
/** connection is closing but a write has to be finished first */
|
2013-05-06 17:01:01 +02:00
|
|
|
def closingWithPendingWrite(info: ConnectionInfo, closeCommander: Option[ActorRef],
|
|
|
|
|
closedEvent: ConnectionClosed): Receive = {
|
|
|
|
|
case SuspendReading ⇒ info.registration.disableInterest(OP_READ)
|
|
|
|
|
case ResumeReading ⇒ info.registration.enableInterest(OP_READ)
|
|
|
|
|
case ChannelReadable ⇒ doRead(info, closeCommander)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
case ChannelWritable ⇒
|
2013-05-06 17:01:01 +02:00
|
|
|
doWrite(info)
|
2013-01-15 18:08:45 +01:00
|
|
|
if (!writePending) // writing is now finished
|
2013-05-06 17:01:01 +02:00
|
|
|
handleClose(info, closeCommander, closedEvent)
|
|
|
|
|
case SendBufferFull(remaining) ⇒ { pendingWrite = remaining; info.registration.enableInterest(OP_WRITE) }
|
|
|
|
|
case WriteFileFinished ⇒ { pendingWrite = null; handleClose(info, closeCommander, closedEvent) }
|
|
|
|
|
case WriteFileFailed(e) ⇒ handleError(info.handler, e) // rethrow exception from dispatcher task
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
case Abort ⇒ handleClose(info, 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-05-06 17:01:01 +02:00
|
|
|
def closing(info: ConnectionInfo, closeCommander: Option[ActorRef]): Receive = {
|
|
|
|
|
case SuspendReading ⇒ info.registration.disableInterest(OP_READ)
|
|
|
|
|
case ResumeReading ⇒ info.registration.enableInterest(OP_READ)
|
|
|
|
|
case ChannelReadable ⇒ doRead(info, closeCommander)
|
|
|
|
|
case Abort ⇒ handleClose(info, Some(sender), Aborted)
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
def handleWriteMessages(info: ConnectionInfo): Receive = {
|
2013-04-16 22:31:09 +02:00
|
|
|
case ChannelWritable ⇒
|
|
|
|
|
if (writePending) {
|
2013-05-06 17:01:01 +02:00
|
|
|
doWrite(info)
|
2013-04-16 22:31:09 +02:00
|
|
|
if (!writePending && interestedInResume.nonEmpty) {
|
|
|
|
|
interestedInResume.get ! WritingResumed
|
|
|
|
|
interestedInResume = None
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-04-02 15:17:48 +02:00
|
|
|
|
2013-04-09 12:25:43 +02:00
|
|
|
case write: WriteCommand ⇒
|
2013-04-16 22:31:09 +02:00
|
|
|
if (writingSuspended) {
|
|
|
|
|
if (TraceLogging) log.debug("Dropping write because writing is suspended")
|
|
|
|
|
sender ! write.failureMessage
|
|
|
|
|
|
|
|
|
|
} else if (writePending) {
|
|
|
|
|
if (TraceLogging) log.debug("Dropping write because queue is full")
|
|
|
|
|
sender ! write.failureMessage
|
2013-05-06 17:01:01 +02:00
|
|
|
if (info.useResumeWriting) writingSuspended = true
|
2013-04-16 22:31:09 +02:00
|
|
|
|
|
|
|
|
} else write match {
|
|
|
|
|
case Write(data, ack) if data.isEmpty ⇒
|
|
|
|
|
if (ack != NoAck) sender ! ack
|
|
|
|
|
|
|
|
|
|
case _ ⇒
|
|
|
|
|
pendingWrite = createWrite(write)
|
2013-05-06 17:01:01 +02:00
|
|
|
doWrite(info)
|
2013-04-16 22:31:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
case ResumeWriting ⇒
|
|
|
|
|
/*
|
|
|
|
|
* If more than one actor sends Writes then the first to send this
|
|
|
|
|
* message might resume too early for the second, leading to a Write of
|
|
|
|
|
* the second to go through although it has not been resumed yet; there
|
|
|
|
|
* is nothing we can do about this apart from all actors needing to
|
|
|
|
|
* register themselves and us keeping track of them, which sounds bad.
|
|
|
|
|
*
|
|
|
|
|
* Thus it is documented that useResumeWriting is incompatible with
|
|
|
|
|
* multiple writers. But we fail as gracefully as we can.
|
|
|
|
|
*/
|
|
|
|
|
writingSuspended = false
|
|
|
|
|
if (writePending) {
|
|
|
|
|
if (interestedInResume.isEmpty) interestedInResume = Some(sender)
|
|
|
|
|
else sender ! CommandFailed(ResumeWriting)
|
|
|
|
|
} else sender ! WritingResumed
|
2013-04-09 14:22:20 +02:00
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
case SendBufferFull(remaining) ⇒ { pendingWrite = remaining; info.registration.enableInterest(OP_WRITE) }
|
2013-04-09 14:22:20 +02:00
|
|
|
case WriteFileFinished ⇒ pendingWrite = null
|
2013-05-06 17:01:01 +02:00
|
|
|
case WriteFileFailed(e) ⇒ handleError(info.handler, e) // rethrow exception from dispatcher task
|
2013-04-02 15:17:48 +02:00
|
|
|
}
|
|
|
|
|
|
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-05-06 17:01:01 +02:00
|
|
|
def completeConnect(registration: ChannelRegistration, commander: ActorRef,
|
|
|
|
|
options: immutable.Traversable[SocketOption]): Unit = {
|
2013-03-05 14:22:21 +01:00
|
|
|
// Turn off Nagle's algorithm by default
|
|
|
|
|
channel.socket.setTcpNoDelay(true)
|
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-05-06 17:01:01 +02:00
|
|
|
context.become(waitingForRegistration(registration, commander))
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
def doRead(info: ConnectionInfo, closeCommander: Option[ActorRef]): Unit = {
|
2013-04-03 16:10:49 +02:00
|
|
|
@tailrec def innerRead(buffer: ByteBuffer, remainingLimit: Int): ReadResult =
|
2013-01-24 15:08:42 +01:00
|
|
|
if (remainingLimit > 0) {
|
|
|
|
|
// never read more than the configured limit
|
|
|
|
|
buffer.clear()
|
2013-01-26 10:44:44 +01:00
|
|
|
val maxBufferSpace = math.min(DirectBufferSize, remainingLimit)
|
|
|
|
|
buffer.limit(maxBufferSpace)
|
2013-01-24 15:08:42 +01:00
|
|
|
val readBytes = channel.read(buffer)
|
|
|
|
|
buffer.flip()
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-04-03 16:10:49 +02:00
|
|
|
if (TraceLogging) log.debug("Read [{}] bytes.", readBytes)
|
2013-05-06 17:01:01 +02:00
|
|
|
if (readBytes > 0) info.handler ! Received(ByteString(buffer))
|
2013-01-15 18:08:45 +01:00
|
|
|
|
2013-01-24 15:08:42 +01:00
|
|
|
readBytes match {
|
2013-04-03 16:10:49 +02:00
|
|
|
case `maxBufferSpace` ⇒ innerRead(buffer, remainingLimit - maxBufferSpace)
|
|
|
|
|
case x if x >= 0 ⇒ AllRead
|
|
|
|
|
case -1 ⇒ EndOfStream
|
2013-01-24 15:08:42 +01:00
|
|
|
case _ ⇒
|
|
|
|
|
throw new IllegalStateException("Unexpected value returned from read: " + readBytes)
|
|
|
|
|
}
|
2013-04-03 16:10:49 +02:00
|
|
|
} else MoreDataWaiting
|
2013-01-24 15:08:42 +01:00
|
|
|
|
2013-02-04 16:24:34 +01:00
|
|
|
val buffer = bufferPool.acquire()
|
2013-04-03 16:10:49 +02:00
|
|
|
try innerRead(buffer, ReceivedMessageSizeLimit) match {
|
2013-05-06 17:01:01 +02:00
|
|
|
case AllRead ⇒ info.registration.enableInterest(OP_READ)
|
2013-04-03 16:10:49 +02:00
|
|
|
case MoreDataWaiting ⇒ self ! ChannelReadable
|
2013-04-02 15:17:48 +02:00
|
|
|
case EndOfStream if channel.socket.isOutputShutdown ⇒
|
|
|
|
|
if (TraceLogging) log.debug("Read returned end-of-stream, our side already closed")
|
2013-05-06 17:01:01 +02:00
|
|
|
doCloseConnection(info.handler, closeCommander, ConfirmedClosed)
|
2013-01-24 15:08:42 +01:00
|
|
|
case EndOfStream ⇒
|
2013-04-02 15:17:48 +02:00
|
|
|
if (TraceLogging) log.debug("Read returned end-of-stream, our side not yet closed")
|
2013-05-06 17:01:01 +02:00
|
|
|
handleClose(info, closeCommander, PeerClosed)
|
2013-01-15 18:08:45 +01:00
|
|
|
} catch {
|
2013-05-06 17:01:01 +02:00
|
|
|
case e: IOException ⇒ handleError(info.handler, e)
|
2013-02-04 16:24:34 +01:00
|
|
|
} finally bufferPool.release(buffer)
|
2013-01-15 18:08:45 +01:00
|
|
|
}
|
|
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
def doWrite(info: ConnectionInfo): Unit = pendingWrite = pendingWrite.doWrite(info)
|
2013-01-15 18:08:45 +01:00
|
|
|
|
|
|
|
|
def closeReason =
|
|
|
|
|
if (channel.socket.isOutputShutdown) ConfirmedClosed
|
|
|
|
|
else PeerClosed
|
|
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
def handleClose(info: ConnectionInfo, closeCommander: Option[ActorRef],
|
|
|
|
|
closedEvent: ConnectionClosed): Unit = closedEvent match {
|
2013-04-02 15:22:11 +02:00
|
|
|
case Aborted ⇒
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Got Abort command. RESETing connection.")
|
2013-05-06 17:01:01 +02:00
|
|
|
doCloseConnection(info.handler, closeCommander, closedEvent)
|
|
|
|
|
case PeerClosed if info.keepOpenOnPeerClosed ⇒
|
2013-04-02 15:17:48 +02:00
|
|
|
// report that peer closed the connection
|
2013-05-06 17:01:01 +02:00
|
|
|
info.handler ! PeerClosed
|
2013-04-02 15:17:48 +02:00
|
|
|
// used to check if peer already closed its side later
|
2013-04-11 14:28:14 +02:00
|
|
|
peerClosed = true
|
2013-05-06 17:01:01 +02:00
|
|
|
context.become(peerSentEOF(info))
|
2013-04-02 15:22:11 +02:00
|
|
|
case _ 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-05-06 17:01:01 +02:00
|
|
|
context.become(closingWithPendingWrite(info, closeCommander, closedEvent))
|
2013-04-02 15:22:11 +02:00
|
|
|
case 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-04-11 14:28:14 +02:00
|
|
|
if (peerClosed) // if peer closed first, the socket is now fully closed
|
2013-05-06 17:01:01 +02:00
|
|
|
doCloseConnection(info.handler, closeCommander, closedEvent)
|
|
|
|
|
else context.become(closing(info, closeCommander))
|
2013-04-02 15:22:11 +02:00
|
|
|
case _ ⇒ // close now
|
2013-01-17 17:29:44 +01:00
|
|
|
if (TraceLogging) log.debug("Got Close command, closing connection.")
|
2013-05-06 17:01:01 +02:00
|
|
|
doCloseConnection(info.handler, closeCommander, closedEvent)
|
2013-04-02 15:22:11 +02:00
|
|
|
}
|
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-15 18:08:45 +01:00
|
|
|
context.stop(self)
|
|
|
|
|
}
|
|
|
|
|
|
2013-04-09 12:25:04 +02:00
|
|
|
def handleError(handler: ActorRef, exception: IOException): Nothing = {
|
2013-01-23 11:47:12 +01:00
|
|
|
closedMessage = CloseInformation(Set(handler), ErrorClosed(extractMsg(exception)))
|
2013-01-15 18:08:45 +01:00
|
|
|
throw exception
|
|
|
|
|
}
|
2013-05-06 17:01:01 +02:00
|
|
|
|
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-02-10 13:52:52 +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()
|
|
|
|
|
|
2013-04-09 12:25:04 +02:00
|
|
|
if (writePending) pendingWrite.release()
|
2013-01-22 17:32:46 +01:00
|
|
|
|
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-04-09 14:22:20 +02:00
|
|
|
/** Create a pending write from a WriteCommand */
|
|
|
|
|
private[io] def createWrite(write: WriteCommand): PendingWrite = write match {
|
|
|
|
|
case write: Write ⇒
|
|
|
|
|
val buffer = bufferPool.acquire()
|
|
|
|
|
|
2013-04-15 14:54:46 +02:00
|
|
|
try {
|
|
|
|
|
val copied = write.data.copyToBuffer(buffer)
|
|
|
|
|
buffer.flip()
|
|
|
|
|
|
|
|
|
|
PendingBufferWrite(sender, write.ack, write.data.drop(copied), buffer)
|
|
|
|
|
} catch {
|
|
|
|
|
case NonFatal(e) ⇒
|
|
|
|
|
bufferPool.release(buffer)
|
|
|
|
|
throw e
|
|
|
|
|
}
|
2013-04-09 14:22:20 +02:00
|
|
|
case write: WriteFile ⇒
|
|
|
|
|
PendingWriteFile(sender, write, new FileInputStream(write.filePath).getChannel, 0L)
|
|
|
|
|
}
|
|
|
|
|
|
2013-04-09 12:25:04 +02:00
|
|
|
private[io] case class PendingBufferWrite(
|
2013-01-21 14:45:19 +01:00
|
|
|
commander: ActorRef,
|
|
|
|
|
ack: Any,
|
|
|
|
|
remainingData: ByteString,
|
2013-04-09 12:25:04 +02:00
|
|
|
buffer: ByteBuffer) extends PendingWrite {
|
|
|
|
|
|
|
|
|
|
def release(): Unit = bufferPool.release(buffer)
|
|
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
def doWrite(info: ConnectionInfo): PendingWrite = {
|
2013-04-09 12:25:04 +02:00
|
|
|
@tailrec def innerWrite(pendingWrite: PendingBufferWrite): PendingWrite = {
|
|
|
|
|
val toWrite = pendingWrite.buffer.remaining()
|
|
|
|
|
require(toWrite != 0)
|
|
|
|
|
val writtenBytes = channel.write(pendingWrite.buffer)
|
|
|
|
|
if (TraceLogging) log.debug("Wrote [{}] bytes to channel", writtenBytes)
|
|
|
|
|
|
|
|
|
|
val nextWrite = pendingWrite.consume(writtenBytes)
|
|
|
|
|
|
|
|
|
|
if (pendingWrite.hasData)
|
|
|
|
|
if (writtenBytes == toWrite) innerWrite(nextWrite) // wrote complete buffer, try again now
|
|
|
|
|
else {
|
2013-05-06 17:01:01 +02:00
|
|
|
info.registration.enableInterest(OP_WRITE)
|
2013-04-09 12:25:04 +02:00
|
|
|
nextWrite
|
|
|
|
|
} // try again later
|
|
|
|
|
else { // everything written
|
|
|
|
|
if (pendingWrite.wantsAck)
|
|
|
|
|
pendingWrite.commander ! pendingWrite.ack
|
|
|
|
|
|
|
|
|
|
pendingWrite.release()
|
|
|
|
|
null
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-01-21 14:45:19 +01:00
|
|
|
|
2013-04-09 12:25:04 +02:00
|
|
|
try innerWrite(this)
|
2013-05-06 17:01:01 +02:00
|
|
|
catch { case e: IOException ⇒ handleError(info.handler, e) }
|
2013-04-09 12:25:04 +02:00
|
|
|
}
|
2013-04-10 14:56:51 +02:00
|
|
|
def hasData = buffer.hasRemaining || remainingData.nonEmpty
|
2013-04-09 12:25:04 +02:00
|
|
|
def consume(writtenBytes: Int): PendingBufferWrite =
|
2013-04-10 14:56:51 +02:00
|
|
|
if (buffer.hasRemaining) this
|
|
|
|
|
else {
|
2013-01-21 14:45:19 +01:00
|
|
|
buffer.clear()
|
|
|
|
|
val copied = remainingData.copyToBuffer(buffer)
|
|
|
|
|
buffer.flip()
|
|
|
|
|
copy(remainingData = remainingData.drop(copied))
|
2013-04-10 14:56:51 +02:00
|
|
|
}
|
2013-01-17 14:31:35 +01:00
|
|
|
}
|
|
|
|
|
|
2013-04-09 14:22:20 +02:00
|
|
|
private[io] case class PendingWriteFile(
|
|
|
|
|
commander: ActorRef,
|
|
|
|
|
write: WriteFile,
|
|
|
|
|
fileChannel: FileChannel,
|
|
|
|
|
alreadyWritten: Long) extends PendingWrite {
|
2013-04-10 14:56:51 +02:00
|
|
|
|
2013-05-06 17:01:01 +02:00
|
|
|
def doWrite(info: ConnectionInfo): PendingWrite = {
|
2013-04-09 14:22:20 +02:00
|
|
|
tcp.fileIoDispatcher.execute(writeFileRunnable(this))
|
|
|
|
|
this
|
|
|
|
|
}
|
2013-01-17 14:31:35 +01:00
|
|
|
|
2013-04-09 14:22:20 +02:00
|
|
|
def ack: Any = write.ack
|
|
|
|
|
|
|
|
|
|
/** Release any open resources */
|
|
|
|
|
def release() { fileChannel.close() }
|
|
|
|
|
|
|
|
|
|
def updatedWrite(nowWritten: Long): PendingWriteFile = {
|
|
|
|
|
require(nowWritten < write.count)
|
|
|
|
|
copy(alreadyWritten = nowWritten)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def remainingBytes = write.count - alreadyWritten
|
|
|
|
|
def currentPosition = write.position + alreadyWritten
|
2013-01-17 14:31:35 +01:00
|
|
|
}
|
2013-05-06 17:01:01 +02:00
|
|
|
|
2013-04-09 14:22:20 +02:00
|
|
|
private[io] def writeFileRunnable(pendingWrite: PendingWriteFile): Runnable =
|
|
|
|
|
new Runnable {
|
2013-04-15 15:03:02 +02:00
|
|
|
def run(): Unit = try {
|
2013-04-09 14:22:20 +02:00
|
|
|
import pendingWrite._
|
2013-04-15 14:53:41 +02:00
|
|
|
val toWrite = math.min(remainingBytes, tcp.Settings.TransferToLimit)
|
|
|
|
|
val writtenBytes = fileChannel.transferTo(currentPosition, toWrite, channel)
|
2013-04-09 14:22:20 +02:00
|
|
|
|
|
|
|
|
if (writtenBytes < remainingBytes) self ! SendBufferFull(pendingWrite.updatedWrite(alreadyWritten + writtenBytes))
|
|
|
|
|
else { // finished
|
|
|
|
|
if (wantsAck) commander ! write.ack
|
|
|
|
|
self ! WriteFileFinished
|
|
|
|
|
|
|
|
|
|
pendingWrite.release()
|
|
|
|
|
}
|
2013-04-15 15:03:02 +02:00
|
|
|
} catch {
|
|
|
|
|
case e: IOException ⇒ self ! WriteFileFailed(e)
|
2013-04-09 14:22:20 +02:00
|
|
|
}
|
|
|
|
|
}
|
2013-01-24 15:08:42 +01:00
|
|
|
}
|
|
|
|
|
|
2013-02-15 11:59:01 +01:00
|
|
|
/**
|
|
|
|
|
* INTERNAL API
|
|
|
|
|
*/
|
2013-01-24 15:08:42 +01:00
|
|
|
private[io] object TcpConnection {
|
|
|
|
|
sealed trait ReadResult
|
|
|
|
|
object EndOfStream extends ReadResult
|
2013-04-03 16:10:49 +02:00
|
|
|
object AllRead extends ReadResult
|
|
|
|
|
object MoreDataWaiting extends ReadResult
|
2013-01-21 14:45:19 +01:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Used to transport information to the postStop method to notify
|
|
|
|
|
* interested party about a connection close.
|
|
|
|
|
*/
|
2013-05-06 17:01:01 +02:00
|
|
|
case class CloseInformation(notificationsTo: Set[ActorRef], closedEvent: Event)
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Groups required connection-related data that are only available once the connection has been fully established.
|
|
|
|
|
*/
|
|
|
|
|
case class ConnectionInfo(registration: ChannelRegistration,
|
|
|
|
|
handler: ActorRef,
|
|
|
|
|
keepOpenOnPeerClosed: Boolean,
|
|
|
|
|
useResumeWriting: Boolean)
|
2013-04-09 12:25:04 +02:00
|
|
|
|
2013-04-09 14:22:20 +02:00
|
|
|
// INTERNAL MESSAGES
|
|
|
|
|
|
|
|
|
|
/** Informs actor that no writing was possible but there is still work remaining */
|
|
|
|
|
case class SendBufferFull(remainingWrite: PendingWrite)
|
|
|
|
|
/** Informs actor that a pending file write has finished */
|
|
|
|
|
case object WriteFileFinished
|
2013-04-15 15:03:02 +02:00
|
|
|
/** Informs actor that a pending WriteFile failed */
|
|
|
|
|
case class WriteFileFailed(e: IOException)
|
2013-04-09 14:22:20 +02:00
|
|
|
|
2013-04-09 12:25:04 +02:00
|
|
|
/** Abstraction over pending writes */
|
|
|
|
|
trait PendingWrite {
|
|
|
|
|
def commander: ActorRef
|
|
|
|
|
def ack: Any
|
|
|
|
|
|
|
|
|
|
def wantsAck = !ack.isInstanceOf[NoAck]
|
2013-05-06 17:01:01 +02:00
|
|
|
def doWrite(info: ConnectionInfo): PendingWrite
|
2013-04-09 12:25:04 +02:00
|
|
|
|
|
|
|
|
/** Release any open resources */
|
|
|
|
|
def release(): Unit
|
|
|
|
|
}
|
2013-01-22 15:51:21 +01:00
|
|
|
}
|