3184da0b569d54e549ec98cd72f1bc76cc76d8c5
[aquarium] / src / main / scala / gr / grnet / aquarium / Configurator.scala
1 /*
2  * Copyright 2011 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
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.
16  *
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.
29  *
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.
34  */
35
36 package gr.grnet.aquarium
37
38 import actor.{ActorProvider}
39 import com.ckkloverdos.resource._
40 import com.ckkloverdos.sys.SysProp
41 import com.ckkloverdos.props.Props
42 import com.ckkloverdos.maybe.{Maybe, Failed, Just, NoVal}
43 import com.ckkloverdos.convert.Converters.{DefaultConverters => TheDefaultConverters}
44 import processor.actor.{IMEventProcessorService, ResourceEventProcessorService, EventProcessorService}
45 import store._
46 import util.{Lifecycle, Loggable}
47
48 /**
49  * The master configurator. Responsible to load all of application configuration and provide the relevant services.
50  *
51  * @author Christos KK Loverdos <loverdos@gmail.com>.
52  */
53 class Configurator(val props: Props) extends Loggable {
54   import Configurator.Keys
55
56   /**
57    * Reflectively provide a new instance of a class and configure it appropriately.
58    */
59   private[this] def newInstance[C : Manifest](className: String): C = {
60     val instanceM = Maybe(defaultClassLoader.loadClass(className).newInstance().asInstanceOf[C])
61     instanceM match {
62       case Just(instance) ⇒ instance match {
63         case configurable: Configurable ⇒
64           Maybe(configurable configure props) match {
65             case Just(_) ⇒
66               instance
67             case Failed(e, _) ⇒
68               throw new Exception("Could not configure instance of %s".format(className), e)
69             case NoVal ⇒
70               throw new Exception("Could not configure instance of %s".format(className))
71           }
72         case _ ⇒
73           instance
74       }
75       case Failed(e, _) ⇒
76         throw new Exception("Could not instantiate %s".format(className), e)
77       case NoVal ⇒
78         throw new Exception("Could not instantiate %s".format(className))
79     }
80
81   }
82
83   private[this] lazy val _actorProvider: ActorProvider = {
84     val instance = newInstance[ActorProvider](props.getEx(Keys.actor_provider_class))
85     logger.info("Loaded ActorProvider: %s".format(instance.getClass))
86     instance
87   }
88
89   private[this] lazy val _storeProvider: StoreProvider = {
90     val instance = newInstance[StoreProvider](props.getEx(Keys.store_provider_class))
91     logger.info("Loaded StoreProvider: %s".format(instance.getClass))
92     instance
93   }
94   
95   private[this] lazy val _restService: Lifecycle = {
96     val instance = newInstance[Lifecycle](props.getEx(Keys.rest_service_class))
97     logger.info("Loaded RESTService: %s".format(instance.getClass))
98     instance
99   }
100
101   private[this] lazy val _userStateStoreM: Maybe[UserStateStore] = {
102     // If there is a specific `UserStateStore` implementation specified in the
103     // properties, then this implementation overrides the user store given by
104     // `StoreProvider`.
105     props.get(Keys.user_state_store_class) map { className ⇒
106       val instance = newInstance[UserStateStore](className)
107       logger.info("Overriding UserStateStore provisioning. Implementation given by: %s".format(instance.getClass))
108       instance
109     }
110   }
111
112   private[this] lazy val _resourceEventStoreM: Maybe[ResourceEventStore] = {
113     // If there is a specific `EventStore` implementation specified in the
114     // properties, then this implementation overrides the event store given by
115     // `StoreProvider`.
116     props.get(Keys.resource_event_store_class) map { className ⇒
117       val instance = newInstance[ResourceEventStore](className)
118       logger.info("Overriding EventStore provisioning. Implementation given by: %s".format(instance.getClass))
119       instance
120     }
121   }
122
123   private[this] lazy val _WalletEventStoreM: Maybe[WalletEntryStore] = {
124     // If there is a specific `IMStore` implementation specified in the
125     // properties, then this implementation overrides the event store given by
126     // `IMProvider`.
127     props.get(Keys.wallet_entry_store_class) map { className ⇒
128       val instance = newInstance[WalletEntryStore](className)
129       logger.info("Overriding WalletEntryStore provisioning. Implementation given by: %s".format(instance.getClass))
130       instance
131     }
132   }
133
134   private[this] lazy val _resEventProc: ResourceEventProcessorService = new ResourceEventProcessorService
135
136   private[this] lazy val _imEventProc: EventProcessorService = new IMEventProcessorService
137
138   def get(key: String, default: String = ""): String = props.getOr(key, default)
139
140   def defaultClassLoader = Thread.currentThread().getContextClassLoader
141
142   def startServices(): Unit = {
143     _restService.start()
144     _actorProvider.start()
145     _resEventProc.start()
146     _imEventProc.start()
147   }
148
149   def stopServices(): Unit = {
150     _imEventProc.stop()
151     _resEventProc.stop()
152     _restService.stop()
153     _actorProvider.stop()
154
155 //    akka.actor.Actor.registry.shutdownAll()
156   }
157
158   def stopServicesWithDelay(millis: Long) {
159     Thread sleep millis
160     stopServices()
161   }
162   
163   def actorProvider = _actorProvider
164
165   def userStateStore = {
166     _userStateStoreM match {
167       case Just(us) ⇒ us
168       case _        ⇒ storeProvider.userStateStore
169     }
170   }
171
172   def resourceEventStore = {
173     _resourceEventStoreM match {
174       case Just(es) ⇒ es
175       case _        ⇒ storeProvider.resourceEventStore
176     }
177   }
178
179   def walletStore = {
180     _WalletEventStoreM match {
181       case Just(es) ⇒ es
182       case _        ⇒ storeProvider.walletEntryStore
183     }
184   }
185
186   def storeProvider = _storeProvider
187 }
188
189 object Configurator {
190   implicit val DefaultConverters = TheDefaultConverters
191
192   val MasterConfName = "aquarium.properties"
193
194   /**
195    * Current directory resource context.
196    * Normally this should be the application installation directory.
197    *
198    * It takes priority over `ClasspathBaseResourceContext`.
199    */
200   val AppBaseResourceContext = new FileStreamResourceContext(".")
201
202   /**
203    * The venerable /etc resource context
204    */
205   val SlashEtcResourceContext = new FileStreamResourceContext("/etc")
206
207   /**
208    * Class loader resource context.
209    * This has the lowest priority.
210    */
211   val ClasspathBaseResourceContext = new ClassLoaderStreamResourceContext(Thread.currentThread().getContextClassLoader)
212
213   /**
214    * Use this property to override the place where aquarium configuration resides.
215    *
216    * The value of this property is a folder that defines the highest-priority resource context.
217    */
218   val ConfBaseFolderSysProp = SysProp("aquarium.conf.base.folder")
219
220   /**
221    * The resource context used in the application.
222    */
223   lazy val MasterResourceContext = {
224     val rc0 = ClasspathBaseResourceContext
225     val rc1 = AppBaseResourceContext
226     val rc2 = SlashEtcResourceContext
227     val basicContext = new CompositeStreamResourceContext(NoVal, rc2, rc1, rc0)
228     
229     ConfBaseFolderSysProp.value match {
230       case Just(value) ⇒
231         // We have a system override for the configuration location
232         new CompositeStreamResourceContext(Just(basicContext), new FileStreamResourceContext(value))
233       case NoVal ⇒
234         basicContext
235       case Failed(e, m) ⇒
236         throw new RuntimeException(m , e)
237     }
238   }
239
240   lazy val MasterConfResource = {
241     val maybeMCResource = MasterResourceContext getResource MasterConfName
242     maybeMCResource match {
243       case Just(masterConfResource) ⇒
244         masterConfResource
245       case NoVal ⇒
246         throw new RuntimeException("Could not find master configuration file: %s".format(MasterConfName))
247       case Failed(e, m) ⇒
248         throw new RuntimeException(m, e)
249     }
250   }
251
252   lazy val MasterConfProps = {
253     val maybeProps = Props apply MasterConfResource
254     maybeProps match {
255       case Just(props) ⇒
256         props
257       case NoVal ⇒
258         throw new RuntimeException("Could not load master configuration file: %s".format(MasterConfName))
259       case Failed(e, m) ⇒
260         throw new RuntimeException(m, e)
261     }
262   }
263
264   lazy val MasterConfigurator = {
265     Maybe(new Configurator(MasterConfProps)) match {
266       case Just(masterConf) ⇒
267         masterConf
268       case NoVal ⇒
269         throw new RuntimeException("Could not initialize master configuration file: %s".format(MasterConfName))
270       case Failed(e, m) ⇒
271         throw new RuntimeException(m, e)
272     }
273   }
274
275   /**
276    * Defines the names of all the known keys inside the master properties file.
277    */
278   final object Keys {
279     /**
280      * The Aquarium version. Will be reported in any due occasion.
281      */
282     final val version = "version"
283
284     /**
285      * The fully qualified name of the class that implements the `ActorProvider`.
286      * Will be instantiated reflectively and should have a public default constructor.
287      */
288     final val actor_provider_class = "actor.provider.class"
289
290     /**
291      * The class that initializes the REST service
292      */
293     final val rest_service_class = "rest.service.class"
294
295     /**
296      * The fully qualified name of the class that implements the `StoreProvider`.
297      * Will be instantiated reflectively and should have a public default constructor.
298      */
299     final val store_provider_class = "store.provider.class"
300
301     /**
302      * The class that implements the User store
303      */
304     final val user_state_store_class = "user.state.store.class"
305
306     /**
307      * The class that implements the resource event store
308      */
309     final val resource_event_store_class = "resource.event.store.class"
310
311     /**
312      * The class that implements the IM event store
313      */
314     final val im_eventstore_class = "imevent.store.class"
315
316     /**
317      * The class that implements the wallet entries store
318      */
319     final val wallet_entry_store_class = "wallet.entry.store.class"
320
321     /** The lower mark for the UserActors' LRU, managed by UserActorManager.
322      *
323      * The terminology is borrowed from the (also borrowed) Apache-lucene-solr-based implementation.
324      *
325      */
326     final val user_actors_lru_lower_mark = "user.actors.LRU.lower.mark"
327
328     /**
329      * The upper mark for the UserActors' LRU, managed by UserActorManager.
330      *
331      * The terminology is borrowed from the (also borrowed) Apache-lucene-solr-based implementation.
332      */
333     final val user_actors_lru_upper_mark = "user.actors.LRU.upper.mark"
334
335     /**
336      * Comma separated list of amqp servers running in active-active
337      * configuration.
338      */
339     final val amqp_servers = "amqp.servers"
340
341     /**
342      * Comma separated list of amqp servers running in active-active
343      * configuration.
344      */
345     final val amqp_port = "amqp.port"
346
347     /**
348      * User name for connecting with the AMQP server
349      */
350     final val amqp_username = "amqp.username"
351
352     /**
353      * Passwd for connecting with the AMQP server
354      */
355     final val amqp_password = "amqp.passwd"
356
357     /**
358      * Virtual host on the AMQP server
359      */
360     final val amqp_vhost = "amqp.vhost"
361
362     /**
363      * Comma separated list of exchanges known to aquarium
364      */
365     final val amqp_exchanges = "amqp.exchanges"
366
367     /**
368      * REST service listening port.
369      *
370      * Default is 8080.
371      */
372     final val rest_port = "rest.port"
373
374     /*
375      * Provider for persistence services
376      */
377     final val persistence_provider = "persistence.provider"
378
379     /**
380      * Hostname for the persistence service
381      */
382     final val persistence_host = "persistence.host"
383
384     /**
385      * Username for connecting to the persistence service
386      */
387     final val persistence_username = "persistence.username"
388
389     /**
390      *  Password for connecting to the persistence service
391      */
392     final val persistence_password = "persistence.password"
393
394     /**
395      *  Password for connecting to the persistence service
396      */
397     final val persistence_port = "persistence.port"
398
399     /**
400      *  The DB schema to use
401      */
402     final val persistence_db = "persistence.db"
403
404     /**
405      * A time period in milliseconds for which we can tolerate stale data regarding user state.
406      *
407      * The smaller the value, the more accurate the user credits and other state data are.
408      *
409      * If a request for user state (e.g. balance) is received and the request timestamp exceeds
410      * the timestamp of the last known balance amount by this value, then a re-computation for
411      * the balance is triggered.
412      */
413     final val user_state_timestamp_threshold = "user.state.timestamp.threshold"
414   }
415 }