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
38 import com.ckkloverdos.convert.Converters
39 import com.ckkloverdos.env.Env
40 import com.ckkloverdos.key.{IntKey, StringKey, LongKey, TypedKeySkeleton, TypedKey, BooleanKey}
41 import com.ckkloverdos.maybe._
42 import com.ckkloverdos.props.Props
43 import com.ckkloverdos.sys.SysProp
44 import connector.rabbitmq.RabbitMQProducer
45 import gr.grnet.aquarium.charging.{ChargingService, ChargingBehavior}
46 import gr.grnet.aquarium.message.avro.gen.{UserAgreementMsg, FullPriceTableMsg, IMEventMsg, ResourceTypeMsg, PolicyMsg}
47 import gr.grnet.aquarium.message.avro.{MessageHelpers, MessageFactory, ModelFactory, AvroHelpers}
48 import gr.grnet.aquarium.policy.{AdHocFullPriceTableRef, FullPriceTableModel, PolicyModel, CachingPolicyStore, PolicyDefinedFullPriceTableRef, UserAgreementModel, ResourceType}
49 import gr.grnet.aquarium.service.event.AquariumCreatedEvent
50 import gr.grnet.aquarium.service.{StoreWatcherService, RabbitMQService, TimerService, EventBusService, AkkaService}
51 import gr.grnet.aquarium.store.StoreProvider
52 import gr.grnet.aquarium.util.date.TimeHelpers
53 import gr.grnet.aquarium.util.{Loggable, Lifecycle}
55 import java.util.concurrent.atomic.AtomicBoolean
56 import org.slf4j.{LoggerFactory, Logger}
57 import gr.grnet.aquarium.event.CreditsModel
58 import gr.grnet.aquarium.charging.state.UserStateBootstrap
59 import java.util.{Map ⇒ JMap}
63 * @author Christos KK Loverdos <loverdos@gmail.com>
66 final class Aquarium(env: Env) extends Lifecycle with Loggable {
68 import Aquarium.EnvKeys
70 @volatile private[this] var _chargingBehaviorMap = Map[String, ChargingBehavior]()
72 private[this] lazy val cachingPolicyStore = new CachingPolicyStore(
73 apply(EnvKeys.defaultPolicyMsg),
74 apply(EnvKeys.storeProvider).policyStore
77 private[this] val _isStopping = new AtomicBoolean(false)
79 override def toString = "%s/v%s".format(getClass.getName, version)
81 def isStopping() = _isStopping.get()
84 def getClientLogger(client: AnyRef): Logger = {
90 LoggerFactory.getLogger(client.getClass)
94 def debug(client: AnyRef, fmt: String, args: Any*) = {
95 getClientLogger(client).debug(fmt.format(args: _*))
98 def info(client: AnyRef, fmt: String, args: Any*) = {
99 getClientLogger(client).info(fmt.format(args: _*))
102 def warn(client: AnyRef, fmt: String, args: Any*) = {
103 getClientLogger(client).warn(fmt.format(args: _*))
106 @throws(classOf[AquariumInternalError])
107 def apply[T: Manifest](key: TypedKey[T]): T = {
112 throw new AquariumInternalError("Could not locate %s in Aquarium environment".format(key))
116 private[this] lazy val _allServices: Seq[_ <: Lifecycle] = Aquarium.ServiceKeys.map(this.apply(_))
118 private[this] def startServices(): Unit = {
119 for(service ← _allServices) {
120 logStartingF(service.toString) {
126 private[this] def stopServices(): Unit = {
127 val services = _allServices.reverse
129 for(service ← services) {
130 logStoppingF(service.toString) {
131 safeUnit(service.stop())
136 private[this] def showBasicConfiguration(): Unit = {
137 for(folder ← this.eventsStoreFolder) {
138 logger.info("{} = {}", EnvKeys.eventsStoreFolder.name, folder)
140 this.eventsStoreFolder.throwMe // on error
142 logger.info("default policy = {}", AvroHelpers.jsonStringOfSpecificRecord(defaultPolicyMsg))
145 private[this] def addShutdownHooks(): Unit = {
146 Runtime.getRuntime.addShutdownHook(new Thread(new Runnable {
148 if(!_isStopping.get()) {
149 logStoppingF("Aquarium") {
157 def start(): Unit = {
158 this._isStopping.set(false)
159 showBasicConfiguration()
165 this._isStopping.set(true)
170 * Stops Aquarium after the given millis. Used during testing.
172 def stopAfterMillis(millis: Long) {
178 * Reflectively provide a new instance of a class and configure it appropriately.
180 def newInstance[C <: AnyRef](_class: Class[C]): C = {
181 newInstance(_class.getName)
185 * Reflectively provide a new instance of a class and configure it appropriately.
187 def newInstance[C <: AnyRef](className: String): C = {
188 val originalProps = apply(EnvKeys.originalProps)
190 val instanceM = MaybeEither(defaultClassLoader.loadClass(className).newInstance().asInstanceOf[C])
192 case Just(instance) ⇒
193 // eventBus.addSubscriber[C](instance)
195 case aquariumAware: AquariumAware ⇒
196 aquariumAware.awareOfAquarium(AquariumCreatedEvent(this))
202 case configurable: Configurable if (originalProps ne null) ⇒
203 val localProps = configurable.propertyPrefix match {
204 case somePrefix @ Some(prefix) ⇒
205 if(prefix.length == 0) {
207 "Property prefix for %s is %s. Consider using None".format(instance, somePrefix))
210 originalProps.subsetForKeyPrefix(prefix)
216 logger.debug("Configuring {} with props (prefix={})", configurable.getClass.getName, configurable.propertyPrefix)
217 MaybeEither(configurable configure localProps) match {
219 logger.info("Configured {} with props (prefix={})", configurable.getClass.getName, configurable.propertyPrefix)
222 throw new AquariumInternalError("Could not configure instance of %s".format(className), e)
231 throw new AquariumInternalError("Could not instantiate %s".format(className), e)
236 def resourceMappingAtMillis(millis: Long): JMap[String, ResourceTypeMsg] = {
237 val policyMspOpt = policyStore.loadPolicyAt(millis)
238 if(policyMspOpt.isEmpty) {
239 throw new AquariumInternalError(
240 "Cannot get resource mapping. Not even the default policy found for time %s",
241 TimeHelpers.toYYYYMMDDHHMMSSSSS(millis)
245 val policyMsg = policyMspOpt.get
246 policyMsg.getResourceMapping
249 // def resourceTypesMapAtMillis(millis: Long): Map[String, ResourceType] = {
250 // val policyMspOpt = policyStore.loadPolicyAt(millis)
251 // if(policyMspOpt.isEmpty) {
252 // throw new AquariumInternalError(
253 // "Cannot get resource types map. Not even the default policy found for time %s",
254 // TimeHelpers.toYYYYMMDDHHMMSSSSS(millis)
258 // val policyMsg = policyMspOpt.get
260 // ModelFactory.newPolicyModel(policyMsg).resourceTypesMap
263 // def currentResourceTypesMap: Map[String, ResourceType] = {
264 // resourceTypesMapAtMillis(TimeHelpers.nowMillis())
267 def unsafeValidPolicyModelAt(referenceTimeMillis: Long): PolicyModel = {
268 policyStore.loadPolicyAt(referenceTimeMillis) match {
270 throw new AquariumInternalError(
271 "No policy found at %s".format(TimeHelpers.toYYYYMMDDHHMMSSSSS(referenceTimeMillis))
274 case Some(policyMsg) ⇒
275 ModelFactory.newPolicyModel(policyMsg)
279 def unsafeValidPolicyAt(referenceTimeMillis: Long): PolicyMsg = {
280 unsafeValidPolicyModelAt(referenceTimeMillis).msg
283 def unsafeFullPriceTableModelForRoleAt(role: String, referenceTimeMillis: Long): FullPriceTableModel = {
284 val policyModelAtReferenceTime = unsafeValidPolicyModelAt(referenceTimeMillis)
286 policyModelAtReferenceTime.roleMapping.get(role) match {
288 throw new AquariumInternalError("Unknown price table for role %s at %s".format(
290 TimeHelpers.toYYYYMMDDHHMMSSSSS(referenceTimeMillis)
293 case Some(fullPriceTable) ⇒
298 def unsafeFullPriceTableForRoleAt(role: String, referenceTimeMillis: Long): FullPriceTableMsg = {
299 val policyAtReferenceTime = unsafeValidPolicyAt(referenceTimeMillis)
300 policyAtReferenceTime.getRoleMapping.get(role) match {
302 throw new AquariumInternalError("Unknown price table for role %s at %s".format(
304 TimeHelpers.toYYYYMMDDHHMMSSSSS(referenceTimeMillis)
307 case fullPriceTable ⇒
312 def unsafeFullPriceTableModelForAgreement(
313 userAgreementModel: UserAgreementModel,
314 knownPolicyModel: PolicyModel
315 ): FullPriceTableModel = {
316 val policyModel = knownPolicyModel match {
318 unsafeValidPolicyModelAt(userAgreementModel.validFromMillis)
324 userAgreementModel.fullPriceTableRef match {
325 case PolicyDefinedFullPriceTableRef ⇒
326 val role = userAgreementModel.role
327 policyModel.roleMapping.get(role) match {
329 throw new AquariumInternalError("Unknown role %s while computing full price table for user %s at %s",
331 userAgreementModel.userID,
332 TimeHelpers.toYYYYMMDDHHMMSSSSS(userAgreementModel.validFromMillis)
335 case Some(fullPriceTable) ⇒
339 case AdHocFullPriceTableRef(fullPriceTable) ⇒
344 def unsafeFullPriceTableForAgreement(
345 userAgreement: UserAgreementMsg,
346 knownPolicyModel: PolicyModel
347 ): FullPriceTableMsg = {
349 val policyModel = knownPolicyModel match {
351 unsafeValidPolicyModelAt(userAgreement.getValidFromMillis)
357 unsafeFullPriceTableForAgreement(userAgreement, policyModel.msg)
360 def unsafeFullPriceTableForAgreement(
361 userAgreement: UserAgreementMsg,
362 knownPolicy: PolicyMsg
363 ): FullPriceTableMsg = {
364 val policy = knownPolicy match {
366 unsafeValidPolicyAt(userAgreement.getValidFromMillis)
372 val role = userAgreement.getRole
373 userAgreement.getFullPriceTableRef match {
375 policy.getRoleMapping.get(role) match {
377 throw new AquariumInternalError("Unknown role %s while computing full price table for user %s at %s",
379 userAgreement.getUserID,
380 TimeHelpers.toYYYYMMDDHHMMSSSSS(userAgreement.getValidFromMillis)
383 case fullPriceTable ⇒
387 case fullPriceTable ⇒
393 * Computes the initial user agreement for the given role and reference time. Also,
394 * records the ID from a potential related IMEvent.
396 * @param imEvent The IMEvent that creates the user
398 def initialUserAgreement(imEvent: IMEventMsg): UserAgreementModel = {
399 require(MessageHelpers.isIMEventCreate(imEvent))
401 val role = imEvent.getRole
402 val referenceTimeMillis = imEvent.getOccurredMillis
405 assert(null ne unsafeFullPriceTableModelForRoleAt(role, referenceTimeMillis))
407 ModelFactory.newUserAgreementModelFromIMEvent(imEvent)
410 def initialUserBalance(role: String, referenceTimeMillis: Long): CreditsModel.Type = {
411 // FIXME: Where is the mapping?
412 CreditsModel.from(0.0)
415 def getUserStateBootstrap(imEvent: IMEventMsg): UserStateBootstrap = {
417 this.initialUserAgreement(imEvent),
418 this.initialUserBalance(imEvent.getRole, imEvent.getOccurredMillis)
422 def chargingBehaviorOf(resourceType: ResourceTypeMsg): ChargingBehavior = {
423 // A resource type never changes charging behavior. By definition.
424 val className = resourceType.getChargingBehaviorClass
425 _chargingBehaviorMap.get(className) match {
426 case Some(chargingBehavior) ⇒
431 _chargingBehaviorMap synchronized {
432 val chargingBehavior = newInstance[ChargingBehavior](className)
433 _chargingBehaviorMap = _chargingBehaviorMap.updated(className, chargingBehavior)
439 throw new AquariumInternalError("Could not load charging behavior %s".format(className), e)
444 def defaultPolicyMsg = apply(EnvKeys.defaultPolicyMsg)
446 def defaultClassLoader = apply(EnvKeys.defaultClassLoader)
448 def resourceEventStore = apply(EnvKeys.storeProvider).resourceEventStore
450 def imEventStore = apply(EnvKeys.storeProvider).imEventStore
452 def userStateStore = apply(EnvKeys.storeProvider).userStateStore
454 def policyStore = this.cachingPolicyStore
456 def eventsStoreFolder = apply(EnvKeys.eventsStoreFolder)
458 def eventBus = apply(EnvKeys.eventBus)
460 def chargingService = apply(EnvKeys.chargingService)
462 def userStateTimestampThreshold = apply(EnvKeys.userStateTimestampThreshold)
464 def adminCookie = apply(EnvKeys.adminCookie)
466 def converters = apply(EnvKeys.converters)
468 def saveResourceEventsToEventsStoreFolder = apply(EnvKeys.eventsStoreSaveRCEvents)
470 def saveIMEventsToEventsStoreFolder = apply(EnvKeys.eventsStoreSaveIMEvents)
472 def timerService = apply(EnvKeys.timerService)
474 def restPort = apply(EnvKeys.restPort)
476 def akkaService = apply(EnvKeys.akkaService)
478 def version = apply(EnvKeys.version)
482 final val PropsToShow = List(
486 SysProp.JavaClassVersion,
487 SysProp.JavaLibraryPath,
488 SysProp.JavaClassPath,
489 SysProp.JavaIOTmpDir,
497 final val RESTAdminHeaderName = "X-Aquarium-Admin-Cookie"
498 final val RESTAdminHeaderNameLowerCase = RESTAdminHeaderName.toLowerCase
501 final class AquariumEnvKey[T: Manifest](override val name: String) extends TypedKeySkeleton[T](name) {
502 override def toString = "%s(%s)".format(manifest[T], name)
505 final val ServiceKeys: List[TypedKey[_ <: Lifecycle]] = List(
506 EnvKeys.timerService,
510 EnvKeys.rabbitMQService,
511 EnvKeys.storeWatcherService,
512 EnvKeys.rabbitMQProducer
517 * The Aquarium version. Will be reported in any due occasion.
519 final val version = StringKey("version")
521 final val originalProps: TypedKey[Props] =
522 new AquariumEnvKey[Props]("originalProps")
525 * The fully qualified name of the class that implements the `StoreProvider`.
526 * Will be instantiated reflectively and should have a public default constructor.
528 final val storeProvider: TypedKey[StoreProvider] =
529 new AquariumEnvKey[StoreProvider]("store.provider.class")
532 * If a value is given to this property, then it represents a folder where all events coming to aquarium are
535 * This is for debugging purposes.
537 final val eventsStoreFolder: TypedKey[Option[File]] =
538 new AquariumEnvKey[Option[File]]("events.store.folder")
541 * If this is `true` and `events.store.folder` is defined, then all resource events are
542 * also stored in `events.store.folder`.
544 * This is for debugging purposes.
547 final val eventsStoreSaveRCEvents = BooleanKey("events.store.save.rc.events")
550 * If this is `true` and `events.store.folder` is defined, then all IM events are
551 * also stored in `events.store.folder`.
553 * This is for debugging purposes.
555 final val eventsStoreSaveIMEvents = BooleanKey("events.store.save.im.events")
558 * A time period in milliseconds for which we can tolerate stale parts regarding user state.
560 * The smaller the value, the more accurate the user credits and other state parts are.
562 * If a request for user state (e.g. balance) is received and the request timestamp exceeds
563 * the timestamp of the last known balance amount by this value, then a re-computation for
564 * the balance is triggered.
566 final val userStateTimestampThreshold = LongKey("user.state.timestamp.threshold")
569 * REST service listening port.
571 final val restPort = IntKey("rest.port")
573 final val restShutdownTimeoutMillis = LongKey("rest.shutdown.timeout.millis")
576 * A cookie used in every administrative REST API call, so that Aquarium knows it comes from
577 * an authorised client.
579 final val adminCookie: TypedKey[Option[String]] =
580 new AquariumEnvKey[Option[String]]("admin.cookie")
583 * The class that initializes the REST service
585 final val restService: TypedKey[Lifecycle] =
586 new AquariumEnvKey[Lifecycle]("rest.service.class")
588 final val akkaService: TypedKey[AkkaService] =
589 new AquariumEnvKey[AkkaService]("akka.service")
591 final val eventBus: TypedKey[EventBusService] =
592 new AquariumEnvKey[EventBusService]("event.bus.service")
594 final val timerService: TypedKey[TimerService] =
595 new AquariumEnvKey[TimerService]("timer.service")
597 final val rabbitMQService: TypedKey[RabbitMQService] =
598 new AquariumEnvKey[RabbitMQService]("rabbitmq.service")
600 final val rabbitMQProducer: TypedKey[RabbitMQProducer] =
601 new AquariumEnvKey[RabbitMQProducer]("rabbitmq.client")
603 final val storeWatcherService: TypedKey[StoreWatcherService] =
604 new AquariumEnvKey[StoreWatcherService]("store.watcher.service")
606 final val converters: TypedKey[Converters] =
607 new AquariumEnvKey[Converters]("converters")
609 final val chargingService: TypedKey[ChargingService] =
610 new AquariumEnvKey[ChargingService]("charging.service")
612 final val defaultClassLoader: TypedKey[ClassLoader] =
613 new AquariumEnvKey[ClassLoader]("default.class.loader")
615 final val defaultPolicyMsg: TypedKey[PolicyMsg] =
616 new AquariumEnvKey[PolicyMsg]("default.policy.msg")