2 * Copyright 2011-2012 GRNET S.A. All rights reserved.
4 * Redistribution and use in source and binary forms, with or
5 * without modification, are permitted provided that the following
8 * 1. Redistributions of source code must retain the above
9 * copyright notice, this list of conditions and the following
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials
15 * provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and
31 * documentation are those of the authors and should not be
32 * interpreted as representing official policies, either expressed
33 * or implied, of GRNET S.A.
36 package gr.grnet.aquarium.service
38 import gr.grnet.aquarium.util.{Lifecycle, Loggable}
41 import akka.actor.Actor._
42 import akka.routing.CyclicIterator
43 import akka.routing.Routing._
44 import akka.dispatch.Dispatchers
45 import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy
46 import akka.config.Supervision.SupervisorConfig
47 import akka.config.Supervision.OneForOneStrategy
48 import gr.grnet.aquarium.messaging.AkkaAMQP
50 import java.util.concurrent.{ConcurrentHashMap, ConcurrentSkipListSet}
51 import com.ckkloverdos.maybe._
52 import gr.grnet.aquarium.util.date.TimeHelpers
53 import gr.grnet.aquarium.{AquariumException, Configurator}
54 import gr.grnet.aquarium.event.AquariumEventModel
57 * An abstract service that retrieves Aquarium events from a queue,
58 * stores them persistently and forwards them for further processing.
59 * The processing happens among two load-balanced actor clusters
60 * asynchronously. The number of employed actors is always equal to
61 * the number of processors. The number of threads per load-balanced
62 * cluster is configurable by subclasses.
64 * @author Georgios Gousios <gousiosg@gmail.com>
66 abstract class EventProcessorService[E <: AquariumEventModel] extends AkkaAMQP with Loggable with Lifecycle {
68 /* Messages exchanged between the persister and the queuereader */
69 case class AckData(msgId: String, deliveryTag: Long, queue: ActorRef)
71 case class Persist(event: E, initialPayload: Array[Byte], sender: ActorRef, ackData: AckData)
73 case class PersistOK(ackData: AckData)
75 case class PersistFailed(ackData: AckData)
77 case class Duplicate(ackData: AckData)
80 * Short term storage for delivery tags to work around AMQP
81 * limitation with redelivering rejected messages to same host.
83 * FIXME: Grow unbounded???
85 private val redeliveries = new ConcurrentSkipListSet[String]()
88 * Temporarily keeps track of messages while being processed
90 * FIXME: Grow unbounded???
92 private val inFlightEvents = new ConcurrentHashMap[Long, E](200, 0.9F, 4)
94 /* Supervisor actor for each event processing operation */
95 private lazy val supervisor = Supervisor(SupervisorConfig(
97 List(classOf[Exception]), //What exceptions will be handled
98 5, // maximum number of restart retries
99 5000 // within time in millis
103 protected def _configurator: Configurator = Configurator.MasterConfigurator
105 protected def parseJsonBytes(data: Array[Byte]): E
107 protected def forward(event: E): Unit
109 protected def existsInStore(event: E): Boolean
111 protected def storeParsedEvent(event: E, initialPayload: Array[Byte]): Unit
113 protected def storeUnparsedEvent(initialPayload: Array[Byte], exception: Throwable): Unit
115 protected def queueReaderThreads: Int
117 protected def persisterThreads: Int
119 protected def numQueueActors: Int
121 protected def numPersisterActors: Int
123 protected def name: String
125 protected def persisterManager: PersisterManager
127 protected def queueReaderManager: QueueReaderManager
129 protected val numCPUs = Runtime.getRuntime.availableProcessors
135 protected def declareQueues(conf: String) = {
136 val decl = _configurator.get(conf)
137 decl.split(";").foreach {
142 throw new AquariumException("Queue declaration \"%s\" not correct".format(q))
147 logger.info("Declaring queue '%s' for exchange '%s' and key '%s'".format(qname, exchange, route))
148 consumer(route, qname, exchange, queueReaderManager.lb, false)
152 class QueueReader extends Actor {
155 case Delivery(payload, _, deliveryTag, isRedeliver, _, queue) =>
157 val event = parseJsonBytes(payload)
158 inFlightEvents.put(deliveryTag, event)
161 //Message could not be processed 3 times, just ignore it
162 if(redeliveries.contains(event.id)) {
163 logger.warn("Actor[%s] - Event[%s] msg[%d] redelivered >2 times. Rejecting".format(self.getUuid(), event, deliveryTag))
164 queue ! Reject(deliveryTag, false)
165 redeliveries.remove(event.id)
166 inFlightEvents.remove(deliveryTag)
168 //Redeliver, but keep track of the message
169 redeliveries.add(event.id)
170 persisterManager.lb ! Persist(event, payload, queueReaderManager.lb, AckData(event.id, deliveryTag, queue.get))
173 val eventWithReceivedMillis = event.withReceivedMillis(TimeHelpers.nowMillis()).asInstanceOf[E]
174 persisterManager.lb ! Persist(eventWithReceivedMillis, payload, queueReaderManager.lb, AckData(event.id, deliveryTag, queue.get))
177 } catch { case e: Exception ⇒
178 logger.error("While parsing incoming json bytes payload", e)
180 // If we could not create an object from the incoming json, then we just store the message
181 // and then ignore it.
182 // TODO: Possibly the sending site should setup a queue to accept such erroneous messages?
184 storeUnparsedEvent(payload, e)
185 queue ! Acknowledge(deliveryTag)
186 } catch { case e: Exception ⇒
187 // Aquarium internal error here...
188 logger.error("Could not store unparsed json bytes payload", e)
189 queue ! Reject(deliveryTag, true)
193 case PersistOK(ackData) =>
194 logger.debug("Actor[%s] - Stored event[%s] msg[%d] - %d left".format(self.getUuid(), ackData.msgId, ackData.deliveryTag, inFlightEvents.size))
195 ackData.queue ! Acknowledge(ackData.deliveryTag)
197 case PersistFailed(ackData) =>
198 //Give the message a chance to be processed by other processors
199 logger.error("Actor[%s] - Storing event[%s] msg[%d] failed".format(self.getUuid(), ackData.msgId, ackData.deliveryTag))
200 inFlightEvents.remove(ackData.deliveryTag)
201 ackData.queue ! Reject(ackData.deliveryTag, true)
203 case Duplicate(ackData) =>
204 logger.debug("Actor[%s] - Event[%s] msg[%d] is duplicate".format(self.getUuid(), ackData.msgId, ackData.deliveryTag))
205 inFlightEvents.remove(ackData.deliveryTag)
206 ackData.queue ! Reject(ackData.deliveryTag, false)
208 case Acknowledged(deliveryTag) =>
209 logger.debug("Actor[%s] - Msg with tag [%d] acked. Forwarding...".format(self.getUuid(), deliveryTag))
210 forward(inFlightEvents.remove(deliveryTag))
212 case Rejected(deliveryTag) =>
213 logger.debug("Actor[%s] - Msg with tag [%d] rejected".format(self.getUuid(), deliveryTag))
215 case _ => logger.warn("Unknown message")
218 override def preStart = {
219 logger.debug("Starting actor QueueReader-%s".format(self.getUuid()))
223 self.dispatcher = queueReaderManager.dispatcher
226 class Persister extends Actor with Loggable {
229 case Persist(event, initialPayload, sender, ackData) ⇒
230 if(existsInStore(event))
231 sender ! Duplicate(ackData)
233 storeParsedEvent(event, initialPayload)
235 sender ! PersistOK(ackData)
236 } forFailed { case Failed(e) ⇒
237 sender ! PersistFailed(ackData)
238 logger.error("While persisting event", e)
242 self.dispatcher = persisterManager.dispatcher
245 class QueueReaderManager {
246 lazy val lb = loadBalancerActor(new CyclicIterator(actors))
248 lazy val dispatcher =
249 Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher(name + "-queuereader")
250 .withNewThreadPoolWithLinkedBlockingQueueWithCapacity(1000)
251 .setMaxPoolSize(2 * numCPUs)
252 .setCorePoolSize(queueReaderThreads)
253 .setKeepAliveTimeInMillis(60000)
254 .setRejectionPolicy(new CallerRunsPolicy).build
257 for(i <- 0 until numQueueActors) yield {
258 val actor = actorOf(new QueueReader)
259 supervisor.link(actor)
264 def stop() = dispatcher.stopAllAttachedActors
267 class PersisterManager {
268 lazy val lb = loadBalancerActor(new CyclicIterator(actors))
271 Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher(name + "-persister")
272 .withNewThreadPoolWithLinkedBlockingQueueWithCapacity(1000)
273 .setMaxPoolSize(2 * numCPUs)
274 .setCorePoolSize(persisterThreads)
275 .setKeepAliveTimeInMillis(60000)
276 .setRejectionPolicy(new CallerRunsPolicy).build
279 for(i <- 0 until numPersisterActors) yield {
280 val actor = actorOf(new Persister)
281 supervisor.link(actor)
286 def stop() = dispatcher.stopAllAttachedActors