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 actor.ActorProvider
39 import com.ckkloverdos.props.Props
40 import com.ckkloverdos.maybe.{Maybe, Failed, Just, NoVal}
41 import com.ckkloverdos.convert.Converters.{DefaultConverters => TheDefaultConverters}
42 import processor.actor.{UserEventProcessorService, ResourceEventProcessorService}
44 import util.{Lifecycle, Loggable}
48 * The master configurator. Responsible to load all of application configuration and provide the relevant services.
50 * @author Christos KK Loverdos <loverdos@gmail.com>.
52 class Configurator(val props: Props) extends Loggable {
53 import Configurator.Keys
56 * Reflectively provide a new instance of a class and configure it appropriately.
58 private[this] def newInstance[C : Manifest](className: String): C = {
59 val instanceM = Maybe(defaultClassLoader.loadClass(className).newInstance().asInstanceOf[C])
61 case Just(instance) ⇒ instance match {
62 case configurable: Configurable ⇒
63 Maybe(configurable configure props) match {
67 throw new AquariumException("Could not configure instance of %s".format(className), e)
69 throw new AquariumException("Could not configure instance of %s".format(className))
75 throw new AquariumException("Could not instantiate %s".format(className), e)
77 throw new AquariumException("Could not instantiate %s".format(className))
82 private[this] lazy val _actorProvider: ActorProvider = {
83 val instance = newInstance[ActorProvider](props.getEx(Keys.actor_provider_class))
84 logger.info("Loaded ActorProvider: %s".format(instance.getClass))
89 * Initializes a store provider, according to the value configured
90 * in the configuration file. The
92 private[this] lazy val _storeProvider: StoreProvider = {
93 val instance = newInstance[StoreProvider](props.getEx(Keys.store_provider_class))
94 logger.info("Loaded StoreProvider: %s".format(instance.getClass))
98 private[this] lazy val _restService: Lifecycle = {
99 val instance = newInstance[Lifecycle](props.getEx(Keys.rest_service_class))
100 logger.info("Loaded RESTService: %s".format(instance.getClass))
104 private[this] lazy val _userStateStoreM: Maybe[UserStateStore] = {
105 // If there is a specific `UserStateStore` implementation specified in the
106 // properties, then this implementation overrides the user store given by
108 props.get(Keys.user_state_store_class) map { className ⇒
109 val instance = newInstance[UserStateStore](className)
110 logger.info("Overriding UserStateStore provisioning. Implementation given by: %s".format(instance.getClass))
115 private[this] lazy val _resourceEventStoreM: Maybe[ResourceEventStore] = {
116 // If there is a specific `EventStore` implementation specified in the
117 // properties, then this implementation overrides the event store given by
119 props.get(Keys.resource_event_store_class) map { className ⇒
120 val instance = newInstance[ResourceEventStore](className)
121 logger.info("Overriding EventStore provisioning. Implementation given by: %s".format(instance.getClass))
126 private[this] lazy val _userEventStoreM: Maybe[UserEventStore] = {
127 props.get(Keys.user_event_store_class) map { className ⇒
128 val instance = newInstance[UserEventStore](className)
129 logger.info("Overriding UserEventStore provisioning. Implementation given by: %s".format(instance.getClass))
134 private[this] lazy val _WalletEventStoreM: Maybe[WalletEntryStore] = {
135 // If there is a specific `IMStore` implementation specified in the
136 // properties, then this implementation overrides the event store given by
138 props.get(Keys.wallet_entry_store_class) map {
140 val instance = newInstance[WalletEntryStore](className)
141 logger.info("Overriding WalletEntryStore provisioning. Implementation given by: %s".format(instance.getClass))
146 private[this] lazy val _policyStoreM: Maybe[PolicyStore] = {
147 props.get(Keys.policy_store_class) map {
149 val instance = newInstance[PolicyStore](className)
150 logger.info("Overriding PolicyStore provisioning. Implementation given by: %s".format(instance.getClass))
155 private[this] lazy val _eventsStoreFolder: Maybe[File] = {
156 props.get(Keys.events_store_folder) map {
158 val canonicalFolder = {
159 val folder = new File(folderName)
160 if(folder.isAbsolute) {
161 folder.getCanonicalFile
163 logger.info("{} is not absolute, making it relative to AQUARIUM_HOME", Keys.events_store_folder)
164 new File(ResourceLocator.AQUARIUM_HOME_FOLDER, folderName).getCanonicalFile
168 val canonicalPath = canonicalFolder.getCanonicalPath
170 logger.info("{} = {}", Keys.events_store_folder, canonicalPath)
172 if(canonicalFolder.exists() && !canonicalFolder.isDirectory) {
173 throw new AquariumException("%s = %s is not a folder".format(Keys.events_store_folder, canonicalFolder))
176 // Now, events folder must be outside AQUARIUM_HOME, since AQUARIUM_HOME can be wiped out for an upgrade but
177 // we still want to keep the events.
178 val ahCanonicalPath = ResourceLocator.AQUARIUM_HOME_FOLDER.getCanonicalPath
179 if(canonicalPath.startsWith(ahCanonicalPath)) {
180 throw new AquariumException(
181 "%s = %s is under %s = %s".format(
182 Keys.events_store_folder, canonicalFolder,
183 ResourceLocator.AQUARIUM_HOME.name, ahCanonicalPath
187 canonicalFolder.mkdirs()
193 private[this] lazy val _resEventProc: ResourceEventProcessorService = new ResourceEventProcessorService
195 private[this] lazy val _imEventProc: UserEventProcessorService = new UserEventProcessorService
197 def get(key: String, default: String = ""): String = props.getOr(key, default)
199 def defaultClassLoader = Thread.currentThread().getContextClassLoader
202 * FIXME: This must be ditched.
204 * Find a file whose location can be overiden in
205 * the configuration file (e.g. policy.yaml)
207 * @param name Name of the file to search for
208 * @param prop Name of the property that defines the file path
209 * @param default Name to return if no file is found
211 def findConfigFile(name: String, prop: String, default: String): File = {
212 // Check for the configured value first
213 val configured = new File(get(prop))
214 if (configured.exists)
217 // Look into the configuration context
218 ResourceLocator.getResource(name) match {
219 case Just(policyResource) ⇒
220 val path = policyResource.url.getPath
227 def startServices(): Unit = {
229 _actorProvider.start()
230 _resEventProc.start()
234 def stopServices(): Unit = {
238 _actorProvider.stop()
240 // akka.actor.Actor.registry.shutdownAll()
243 def stopServicesWithDelay(millis: Long) {
248 def actorProvider = _actorProvider
250 def userStateStore = {
251 _userStateStoreM match {
253 case _ ⇒ storeProvider.userStateStore
257 def resourceEventStore = {
258 _resourceEventStoreM match {
260 case _ ⇒ storeProvider.resourceEventStore
265 _WalletEventStoreM match {
267 case _ ⇒ storeProvider.walletEntryStore
271 def userEventStore = {
272 _userEventStoreM match {
274 case _ ⇒ storeProvider.userEventStore
279 _policyStoreM match {
281 case _ ⇒ storeProvider.policyStore
285 def storeProvider = _storeProvider
287 def withStoreProviderClass[C <: StoreProvider](spc: Class[C]): Configurator = {
288 val map = this.props.map
289 val newMap = map.updated(Keys.store_provider_class, spc.getName)
290 val newProps = new Props(newMap)
291 new Configurator(newProps)
294 // FIXME: This is instead of props.getInt which currently contains a bug.
295 // FIXME: Fix the original bug and delete this method
296 def getInt(name: String): Maybe[Int] = {
297 props.get(name).map(_.toInt)
300 def eventsStoreFolder = _eventsStoreFolder
303 object Configurator {
304 implicit val DefaultConverters = TheDefaultConverters
306 val MasterConfName = "aquarium.properties"
308 val PolicyConfName = "policy.yaml"
310 val RolesAgreementsName = "roles-agreements.map"
312 lazy val MasterConfResource = {
313 val maybeMCResource = ResourceLocator getResource MasterConfName
314 maybeMCResource match {
315 case Just(masterConfResource) ⇒
318 throw new AquariumException("Could not find master configuration file: %s".format(MasterConfName))
320 throw new AquariumException(e, "Could not find master configuration file: %s".format(MasterConfName))
324 lazy val MasterConfProps = {
325 val maybeProps = Props apply MasterConfResource
330 throw new AquariumException("Could not load master configuration file: %s".format(MasterConfName))
332 throw new AquariumException(e, "Could not load master configuration file: %s".format(MasterConfName))
336 lazy val MasterConfigurator = {
337 Maybe(new Configurator(MasterConfProps)) match {
338 case Just(masterConf) ⇒
341 throw new AquariumException("Could not initialize master configuration file: %s".format(MasterConfName))
343 throw new AquariumException(e, "Could not initialize master configuration file: %s".format(MasterConfName))
348 * Defines the names of all the known keys inside the master properties file.
353 * The Aquarium version. Will be reported in any due occasion.
355 final val version = "version"
358 * The fully qualified name of the class that implements the `ActorProvider`.
359 * Will be instantiated reflectively and should have a public default constructor.
361 final val actor_provider_class = "actor.provider.class"
364 * The class that initializes the REST service
366 final val rest_service_class = "rest.service.class"
369 * The fully qualified name of the class that implements the `StoreProvider`.
370 * Will be instantiated reflectively and should have a public default constructor.
372 final val store_provider_class = "store.provider.class"
375 * The class that implements the User store
377 final val user_state_store_class = "user.state.store.class"
380 * The class that implements the resource event store
382 final val resource_event_store_class = "resource.event.store.class"
385 * The class that implements the IM event store
387 final val user_event_store_class = "user.event.store.class"
390 * The class that implements the wallet entries store
392 final val wallet_entry_store_class = "wallet.entry.store.class"
395 * The class that implements the wallet entries store
397 final val policy_store_class = "policy.store.class"
400 /** The lower mark for the UserActors' LRU, managed by UserActorManager.
402 * The terminology is borrowed from the (also borrowed) Apache-lucene-solr-based implementation.
405 final val user_actors_lru_lower_mark = "user.actors.LRU.lower.mark"
408 * The upper mark for the UserActors' LRU, managed by UserActorManager.
410 * The terminology is borrowed from the (also borrowed) Apache-lucene-solr-based implementation.
412 final val user_actors_lru_upper_mark = "user.actors.LRU.upper.mark"
415 * Comma separated list of amqp servers running in active-active
418 final val amqp_servers = "amqp.servers"
421 * Comma separated list of amqp servers running in active-active
424 final val amqp_port = "amqp.port"
427 * User name for connecting with the AMQP server
429 final val amqp_username = "amqp.username"
432 * Passwd for connecting with the AMQP server
434 final val amqp_password = "amqp.passwd"
437 * Virtual host on the AMQP server
439 final val amqp_vhost = "amqp.vhost"
442 * Comma separated list of exchanges known to aquarium
444 final val amqp_exchange = "amqp.exchange"
447 * Queues for retrieving resource events from. Multiple queues can be
448 * declared, seperated by semicolon
450 * Format is `exchange:routing.key:queue-name;<exchnage2:routing.key2:queue-name>;...`
452 final val amqp_resevents_queues = "amqp.resevents.queues"
455 * Queues for retrieving user events from. Multiple queues can be
456 * declared, seperated by semicolon
458 * Format is `exchange:routing.key:queue-name;<exchnage2:routing.key2:queue-name>;...`
460 final val amqp_userevents_queues="amqp.userevents.queues"
463 * REST service listening port.
467 final val rest_port = "rest.port"
470 * Provider for persistence services
472 final val persistence_provider = "persistence.provider"
475 * Hostname for the persistence service
477 final val persistence_host = "persistence.host"
480 * Username for connecting to the persistence service
482 final val persistence_username = "persistence.username"
485 * Password for connecting to the persistence service
487 final val persistence_password = "persistence.password"
490 * Password for connecting to the persistence service
492 final val persistence_port = "persistence.port"
495 * The DB schema to use
497 final val persistence_db = "persistence.db"
500 * Maximum number of open connections to MongoDB
502 final val mongo_connection_pool_size = "mongo.connection.pool.size"
505 * Location of the Aquarium accounting policy config file
507 final val aquarium_policy = "aquarium.policy"
510 * Location of the role-agreement mapping file
512 final val aquarium_role_agreement_map = "aquarium.role-agreement.map"
515 * A time period in milliseconds for which we can tolerate stale data regarding user state.
517 * The smaller the value, the more accurate the user credits and other state data are.
519 * If a request for user state (e.g. balance) is received and the request timestamp exceeds
520 * the timestamp of the last known balance amount by this value, then a re-computation for
521 * the balance is triggered.
523 final val user_state_timestamp_threshold = "user.state.timestamp.threshold"
526 * The time unit is the lowest billable time period.
527 * For example, with a time unit of ten seconds, if a VM is started up and shut down in nine
528 * seconds, then the user will be billed for ten seconds.
530 * This is an overall constant. We use it as a property in order to prepare ourselves for
531 * multi-cloud setup, where the same Aquarium instance is used to bill several distinct cloud
534 final val time_unit_in_millis = "time.unit.in.seconds"
537 * If a value is given to this property, then it represents a folder where all events coming to aquarium are
540 final val events_store_folder = "events.store.folder"
543 * If set to `true`, then an IM event that cannot be parsed to [[gr.grnet.aquarium.logic.events.UserEvent]] is
544 * saved to the [[gr.grnet.aquarium.store.UserEventStore]].
546 final val save_unparsed_event_im = "save.unparsed.event.im"