-
Notifications
You must be signed in to change notification settings - Fork 4
/
IdempotentReceiver.scala
271 lines (249 loc) · 10.4 KB
/
IdempotentReceiver.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package eip.idempotent
import akka.actor.Actor._
import akka.remoteinterface._
import akka.actor.{ActorRef, Actor}
import java.lang.String
import eip.idempotent.IdempotentProtocol._
import collection.JavaConversions.JConcurrentMapWrapper
import java.util.concurrent.ConcurrentHashMap
import java.net.{InetSocketAddress}
import akka.event.slf4j.Logging
/**
* Idempotent server. wraps Actors into IdempotentReceiver Actors so that they can be accessed with the RepeaterClient.
*/
class IdempotentServer(envelopes: Envelopes, timeout: Int) {
private val idempotentActors = new JConcurrentMapWrapper(new ConcurrentHashMap[String, ActorRef]())
private var _host = "localhost"
private var _port = 0
var remoteModule = remote
private val repeatFrameRequester = actorOf(new RepeatFrameRequester(envelopes, timeout))
repeatFrameRequester.start
private val listener = actorOf(new ReceiverConnectionListener(repeatFrameRequester, envelopes, timeout))
listener.start
envelopes.setServer(this)
def start(host: String, port: Int) = {
if (!remoteModule.isRunning) {
remoteModule.addListener(listener)
remoteModule.start(host, port)
_host = host
_port = port
}
}
def start(host: String, port: Int, loader: ClassLoader) = {
if (!remoteModule.isRunning) {
remoteModule.addListener(listener)
remoteModule.start(host, port, loader)
_host = host
_port = port
}
}
def idempotentActorRef(remoteActorName: String): Option[ActorRef] = {
idempotentActors.get(remoteActorName)
}
def register(remoteActorName: String, actorRef: ActorRef): ActorRef = {
if (!idempotentActors.contains(remoteActorName)) {
if (!actorRef.isRunning) {
actorRef.start
}
val idempotentActorRef = actorOf(new IdempotentReceiver(Set(actorRef), envelopes, _host, _port))
idempotentActorRef.start
remote.register(remoteActorName, idempotentActorRef)
idempotentActors += remoteActorName -> idempotentActorRef
idempotentActorRef
} else {
throw new Exception("Remote Actor " + remoteActorName + " is already active as Idempotent Receiver")
}
}
def unregister(remoteActorName: String) = {
remoteModule.unregister(remoteActorName);
idempotentActors.remove(remoteActorName)
}
def shutdown = {
try {
envelopes.close
remoteModule.removeListener(listener)
} finally {
remoteModule.shutdown
}
}
}
/**
* Connection Listener that triggers requests to the repeater, to repeat frame because an error has occurred.
*/
class ReceiverConnectionListener(repeatFrameRequester: ActorRef, envelopes: Envelopes, timeout: Int) extends Actor with Logging {
private var serverError = false
private var serverDisconnected = false
private var clientDisconnected = false
private var clientError = false
def receive = {
case RemoteClientError(cause, client: RemoteClientModule, remoteAddress) => {
clientError = true;
}
case RemoteClientDisconnected(client: RemoteClientModule, remoteAddress: InetSocketAddress) => {
log.debug("Remote client %s:%d disconnected from receiver", remoteAddress.getHostName, remoteAddress.getPort)
clientDisconnected = true
}
case RemoteClientConnected(client: RemoteClientModule, remoteAddress: InetSocketAddress) => {
if (clientDisconnected || clientError) {
log.debug("Remote client %s:%d reconnected to receiver", remoteAddress.getHostName, remoteAddress.getPort)
// connected after disconnect or error
repeatFrameRequester ! ReconnectClient(self, client)
clientError = false
clientDisconnected = false
}
}
case RemoteClientShutdown(client, remoteAddress) => {
}
case RemoteClientWriteFailed(request, error: Throwable, client: RemoteClientModule, address: InetSocketAddress) => {
clientError = true
}
case RemoteServerError(cause, server: RemoteServerModule) => {
log.debug("Remote Server error on receiver %s", server.name)
serverError = true
}
case RemoteServerShutdown(server) => {
}
case RemoteServerStarted(server) => {
log.debug("Remote Server started %s", server.name)
// start handling incomplete requests at startup (if envelopes are persistent)
repeatFrameRequester ! ReconnectServer(self, server)
}
case RemoteServerClientConnected(server, address: Option[InetSocketAddress]) => {
log.debug("Remote Server Client connected to server %s", server.name)
if (serverDisconnected || serverError) {
// connected after disconnected
repeatFrameRequester ! ReconnectServer(self, server)
serverDisconnected = false
serverError = false
}
}
case RemoteServerClientClosed(server: RemoteServerModule, clientAddress: Option[InetSocketAddress]) => {
}
case RemoteServerClientDisconnected(server: RemoteServerModule, clientAddress: Option[InetSocketAddress]) => {
log.debug("Remote Server Client disconnected to server %s", server.name)
// set flag for disconnect of clients
serverDisconnected = true
}
}
}
case class ReconnectServer(listener: ActorRef, server: RemoteServerModule)
case class ReconnectClient(listener: ActorRef, client: RemoteClientModule)
/**
* Requests the repeater to repeat frames when there is a reconnect
*/
class RepeatFrameRequester(envelopes: Envelopes, timeout: Int) extends Actor with Logging {
private var clients = Set[Address]()
def receive = {
case msg: ReconnectServer => {
reconnect(msg.listener)
}
case msg: ReconnectClient => {
reconnect(msg.listener)
}
}
def reconnect(listener: ActorRef) = {
val frames = envelopes.getIncompleteFrames
for (frame <- frames) {
log.info("reconnecting for frame %d, to client host: %s, port %d, %s".format(frame.id, frame.returnAddress.host, frame.returnAddress.port, frame.returnAddress.actor))
val envelopeIds = envelopes.getEnvelopeIds(frame.id)
val frameProtocol = EnvelopeSerializer.toProtocol(frame)
//sender in frame should always be the same one
val builder = RepeatFrameRequestProtocol.newBuilder
for (envelopeId <- envelopeIds) {
builder.addEnvelope(envelopeId)
}
val repeatFrame = builder.setFrame(frameProtocol).build
if (!clients.contains(frame.returnAddress)) {
clients = clients + frame.returnAddress
remote.addListener(listener)
}
var actorRef = remote.actorFor(frame.returnAddress.actor, frame.returnAddress.host, frame.returnAddress.port)
var success = false
while (!success) {
if (actorRef.isShutdown) {
actorRef = remote.actorFor(frame.returnAddress.actor, frame.returnAddress.host, frame.returnAddress.port)
}
val reply = actorRef !! (repeatFrame, timeout)
reply match {
case Some(response: RepeatFrameResponseProtocol) => {
success = true
// keep track of frame amount handled, and remove envelopeIds from buffer
}
case None => {
log.info("Timeout on RepeatFrameRequest for frame %s", frame.id)
}
}
}
}
}
}
/**
* Idempotent Receiver. ignores duplicate messages, handles frame requests and communicates with
* the repeater when frames are completed. Only works for oneway messages at the moment.
*/
class IdempotentReceiver(actors: Set[ActorRef], envelopes: Envelopes, host: String, port: Int) extends Actor with Logging {
def completeFrame(envelope: Envelope): Unit = {
val someFrame = envelopes.getFrame(envelope.frameId)
someFrame match {
case Some(frame) => {
spawn {
log.debug("Completing frame %d to %s,%s,%d".format(frame.id, frame.returnAddress.actor, frame.returnAddress.host, frame.returnAddress.port))
var repeater = remote.actorFor(frame.returnAddress.actor, frame.returnAddress.host, frame.returnAddress.port)
val completeFrameMsg = CompleteFrameRequestProtocol.newBuilder.setFrame(frame.toProtocol).build
var success = false
while (!success) {
if (repeater.isShutdown) {
repeater = remote.actorFor(frame.returnAddress.actor, frame.returnAddress.host, frame.returnAddress.port)
}
val reply = repeater !! completeFrameMsg
reply match {
case Some(response: CompleteFrameResponseProtocol) => {
success = true
// keep track of frame amount handled, and remove envelopeIds from buffer
envelopes.removeFrame(envelope.frameId)
}
case None => {
log.info("Timeout on CompleteFrameRequest for frame %s".format(frame.id))
}
}
}
}
}
case None => log.error("Frame %d for envelope %d not known when trying to complete frame", envelope.frameId, envelope.id)
}
}
def receive = {
case msg: EnvelopeProtocol => {
// TODO check if sender sent this with !, !!, or !!!
val protomsg: (Envelope, Any) = EnvelopeSerializer.deserialize(msg)
val envelope = protomsg._1
val payload = protomsg._2
val someValue = envelopes.get(envelope.frameId, envelope.id, payload)
someValue match {
case Some(envelope: Envelope) => {
log.debug("Ignored envelope %d, frame %d, on %s:%d".format(envelope.id, envelope.frameId, host, port))
// repeat the previous response, if it is a !! or !!!
}
case None => {
log.debug("Received new envelope %d, frame %d, on %s:%d".format(envelope.id, envelope.frameId, host, port))
val complete = envelopes.put(envelope)
for (actor <- actors) {
actor ! payload
}
if (complete) {
completeFrame(envelope)
}
}
}
}
case msg: FrameRequestProtocol => {
log.debug("Received FrameRequest from %s@%s:%d.".format(msg.getReturnAddress.getActor, msg.getReturnAddress.getHost, msg.getReturnAddress.getPort))
val returnAddress = EnvelopeSerializer.fromProtocol(msg.getReturnAddress)
val address = EnvelopeSerializer.fromProtocol(msg.getAddress)
val frame = envelopes.nextFrame(returnAddress, address)
log.debug("Created new Frame for %s@%s:%d to %s@%s:%d, id %d, size %d.".format(frame.returnAddress.actor, frame.returnAddress.host,
frame.returnAddress.port, frame.address.actor, frame.address.host, frame.address.port, frame.id, frame.size))
self.reply(FrameResponseProtocol.newBuilder.setFrame(frame.toProtocol).build)
}
}
}