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.store.mongodb
38 import com.mongodb.util.JSON
39 import gr.grnet.aquarium.util.json.JsonSupport
40 import collection.mutable.ListBuffer
41 import gr.grnet.aquarium.event.model.im.IMEventModel
42 import gr.grnet.aquarium.event.model.im.IMEventModel.{Names ⇒ IMEventNames}
43 import gr.grnet.aquarium.event.model.resource.ResourceEventModel
44 import gr.grnet.aquarium.event.model.resource.ResourceEventModel.{Names ⇒ ResourceEventNames}
45 import gr.grnet.aquarium.store._
47 import org.bson.types.ObjectId
48 import gr.grnet.aquarium.util._
49 import gr.grnet.aquarium.converter.StdConverters
50 import gr.grnet.aquarium.event.model.ExternalEventModel
51 import gr.grnet.aquarium.computation.BillingMonthInfo
52 import gr.grnet.aquarium.policy.PolicyModel
53 import gr.grnet.aquarium.{Aquarium, AquariumException}
54 import collection.immutable.SortedMap
55 import gr.grnet.aquarium.logic.accounting.dsl.Timeslot
56 import collection.immutable
57 import gr.grnet.aquarium.charging.state.UserStateModel
60 * Mongodb implementation of the various aquarium stores.
62 * @author Christos KK Loverdos <loverdos@gmail.com>
63 * @author Georgios Gousios <gousiosg@gmail.com>
64 * @author Prodromos Gerakios <pgerakio@grnet.gr>
67 val aquarium: Aquarium,
72 extends ResourceEventStore
78 override type IMEvent = MongoDBIMEvent
79 override type ResourceEvent = MongoDBResourceEvent
80 override type Policy = MongoDBPolicy
81 override type UserState = MongoDBUserState
83 private[store] lazy val resourceEvents = getCollection(MongoDBStore.RESOURCE_EVENTS_COLLECTION)
84 private[store] lazy val userStates = getCollection(MongoDBStore.USER_STATES_COLLECTION)
85 private[store] lazy val imEvents = getCollection(MongoDBStore.IM_EVENTS_COLLECTION)
86 private[store] lazy val policies = getCollection(MongoDBStore.POLICY_COLLECTION)
88 private[this] def getCollection(name: String): DBCollection = {
89 val db = mongo.getDB(database)
90 //logger.debug("Authenticating to mongo")
91 if(!db.isAuthenticated && !db.authenticate(username, password.toCharArray)) {
92 throw new AquariumException("Could not authenticate user %s".format(username))
94 db.getCollection(name)
98 def createResourceEventFromOther(event: ResourceEventModel): ResourceEvent = {
99 MongoDBResourceEvent.fromOther(event, null)
102 def pingResourceEventStore(): Unit = synchronized {
103 MongoDBStore.ping(mongo)
106 def insertResourceEvent(event: ResourceEventModel) = {
107 val localEvent = MongoDBResourceEvent.fromOther(event, new ObjectId().toStringMongod)
108 MongoDBStore.insertObject(localEvent, resourceEvents, MongoDBStore.jsonSupportToDBObject)
112 def findResourceEventByID(id: String): Option[ResourceEvent] = {
113 MongoDBStore.findBy(ResourceEventNames.id, id, resourceEvents, MongoDBResourceEvent.fromDBObject)
116 def findResourceEventsByUserID(userId: String)
117 (sortWith: Option[(ResourceEvent, ResourceEvent) => Boolean]): List[ResourceEvent] = {
118 val query = new BasicDBObject(ResourceEventNames.userID, userId)
120 MongoDBStore.runQuery(query, resourceEvents)(MongoDBResourceEvent.fromDBObject)(sortWith)
123 def countOutOfSyncResourceEventsForBillingPeriod(userID: String, startMillis: Long, stopMillis: Long): Long = {
124 val query = new BasicDBObjectBuilder().
125 add(ResourceEventModel.Names.userID, userID).
126 // received within the period
127 add(ResourceEventModel.Names.receivedMillis, new BasicDBObject("$gte", startMillis)).
128 add(ResourceEventModel.Names.receivedMillis, new BasicDBObject("$lte", stopMillis)).
129 // occurred outside the period
131 val dbList = new BasicDBList()
132 dbList.add(0, new BasicDBObject(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$lt", startMillis)))
133 dbList.add(1, new BasicDBObject(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$gt", stopMillis)))
138 resourceEvents.count(query)
141 def foreachResourceEventOccurredInPeriod(
145 )(f: ResourceEvent ⇒ Unit): Unit = {
147 val query = new BasicDBObjectBuilder().
148 add(ResourceEventModel.Names.userID, userID).
149 add(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$gte", startMillis)).
150 add(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$lte", stopMillis)).
153 val sorter = new BasicDBObject(ResourceEventModel.Names.occurredMillis, 1)
154 val cursor = resourceEvents.find(query).sort(sorter)
156 withCloseable(cursor) { cursor ⇒
157 while(cursor.hasNext) {
158 val nextDBObject = cursor.next()
159 val nextEvent = MongoDBResourceEvent.fromDBObject(nextDBObject)
165 //-ResourceEventStore
168 def insertUserState(userState: UserState) = {
169 MongoDBStore.insertObject(
170 userState.copy(_id = new ObjectId().toString),
172 MongoDBStore.jsonSupportToDBObject
176 def findUserStateByUserID(userID: String): Option[UserState] = {
177 val query = new BasicDBObject(UserStateModel.Names.userID, userID)
178 val cursor = userStates find query
180 MongoDBStore.firstResultIfExists(cursor, MongoDBStore.dbObjectToUserState)
183 def findLatestUserStateForFullMonthBilling(userID: String, bmi: BillingMonthInfo): Option[UserState] = {
184 val query = new BasicDBObjectBuilder().
185 add(UserStateModel.Names.userID, userID).
186 add(UserStateModel.Names.isFullBillingMonth, true).
187 add(UserStateModel.Names.billingYear, bmi.year).
188 add(UserStateModel.Names.billingMonth, bmi.month).
191 // Descending order, so that the latest comes first
192 val sorter = new BasicDBObject(UserStateModel.Names.occurredMillis, -1)
194 val cursor = userStates.find(query).sort(sorter)
196 MongoDBStore.firstResultIfExists(cursor, MongoDBStore.dbObjectToUserState)
199 def createUserStateFromOther(userState: UserStateModel) = {
200 MongoDBUserState.fromOther(userState, new ObjectId().toStringMongod)
204 * Stores a user state.
206 def insertUserState(userState: UserStateModel): UserState = {
207 val localUserState = createUserStateFromOther(userState)
208 MongoDBStore.insertObject(localUserState, userStates, MongoDBStore.jsonSupportToDBObject)
213 def createIMEventFromJson(json: String) = {
214 MongoDBStore.createIMEventFromJson(json)
217 def createIMEventFromOther(event: IMEventModel) = {
218 MongoDBStore.createIMEventFromOther(event)
221 def pingIMEventStore(): Unit = {
222 MongoDBStore.ping(mongo)
225 def insertIMEvent(event: IMEventModel): IMEvent = {
226 val localEvent = MongoDBIMEvent.fromOther(event, new ObjectId().toStringMongod)
227 MongoDBStore.insertObject(localEvent, imEvents, MongoDBStore.jsonSupportToDBObject)
231 def findIMEventByID(id: String): Option[IMEvent] = {
232 MongoDBStore.findBy(IMEventNames.id, id, imEvents, MongoDBIMEvent.fromDBObject)
237 * Find the `CREATE` even for the given user. Note that there must be only one such event.
239 def findCreateIMEventByUserID(userID: String): Option[IMEvent] = {
240 val query = new BasicDBObjectBuilder().
241 add(IMEventNames.userID, userID).
242 add(IMEventNames.eventType, IMEventModel.EventTypeNames.create).get()
244 // Normally one such event is allowed ...
245 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
247 MongoDBStore.firstResultIfExists(cursor, MongoDBIMEvent.fromDBObject)
250 def findLatestIMEventByUserID(userID: String): Option[IMEvent] = {
251 val query = new BasicDBObject(IMEventNames.userID, userID)
252 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, -1))
254 MongoDBStore.firstResultIfExists(cursor, MongoDBIMEvent.fromDBObject)
258 * Scans events for the given user, sorted by `occurredMillis` in ascending order and runs them through
259 * the given function `f`.
261 * Any exception is propagated to the caller. The underlying DB resources are properly disposed in any case.
263 def foreachIMEventInOccurrenceOrder(userID: String)(f: (IMEvent) => Unit) = {
264 val query = new BasicDBObject(IMEventNames.userID, userID)
265 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
267 withCloseable(cursor) { cursor ⇒
268 while(cursor.hasNext) {
269 val model = MongoDBIMEvent.fromDBObject(cursor.next())
280 * Store an accounting policy.
282 def insertPolicy(policy: PolicyModel): Policy = {
283 val dbPolicy = MongoDBPolicy.fromOther(policy, new ObjectId().toStringMongod)
284 MongoDBStore.insertObject(dbPolicy, policies, MongoDBStore.jsonSupportToDBObject)
287 private def emptyMap = immutable.SortedMap[Timeslot,Policy]()
289 def loadValidPolicyAt(atMillis: Long): Option[Policy] = {
290 /*var d = new Date(atMillis)
291 /* sort in reverse order and return the first that includes this date*/
292 policies.sortWith({(x,y)=> y.validFrom < x.validFrom}).collectFirst({
293 case t if(t.validityTimespan.toTimeslot.includes(d)) => t
295 throw new UnsupportedOperationException
298 def loadAndSortPoliciesWithin(fromMillis: Long, toMillis: Long): SortedMap[Timeslot, Policy] = {
300 throw new UnsupportedOperationException
305 object MongoDBStore {
307 final val _id = "_id"
311 * Collection holding the [[gr.grnet.aquarium.event.model.resource.ResourceEventModel]]s.
313 * Resource events are coming from all systems handling billable resources.
315 final val RESOURCE_EVENTS_COLLECTION = "resevents"
318 * Collection holding the snapshots of [[gr.grnet.aquarium.charging.state.UserStateModel]].
320 * [[gr.grnet.aquarium.charging.state.UserStateModel]] is held internally within
321 * [[gr.grnet.aquarium.actor.service.user.UserActor]]s.
323 final val USER_STATES_COLLECTION = "userstates"
326 * Collection holding [[gr.grnet.aquarium.event.model.im.IMEventModel]]s.
328 * User events are coming from the IM module (external).
330 final val IM_EVENTS_COLLECTION = "imevents"
333 * Collection holding [[gr.grnet.aquarium.policy.PolicyModel]]s.
335 final val POLICY_COLLECTION = "policies"
337 def dbObjectToUserState(dbObj: DBObject): MongoDBUserState = {
338 MongoDBUserState.fromJSONString(JSON.serialize(dbObj))
341 def firstResultIfExists[A](cursor: DBCursor, f: DBObject ⇒ A): Option[A] = {
342 withCloseable(cursor) { cursor ⇒
344 Some(f(cursor.next()))
351 def ping(mongo: Mongo): Unit = synchronized {
352 // This requires a network roundtrip
356 def findBy[A >: Null <: AnyRef](name: String,
358 collection: DBCollection,
359 deserializer: (DBObject) => A) : Option[A] = {
360 val query = new BasicDBObject(name, value)
361 val cursor = collection find query
363 withCloseable(cursor) { cursor ⇒
365 Some(deserializer apply cursor.next)
371 def runQuery[A <: ExternalEventModel](query: DBObject, collection: DBCollection, orderBy: DBObject = null)
372 (deserializer: (DBObject) => A)
373 (sortWith: Option[(A, A) => Boolean]): List[A] = {
374 val cursor0 = collection find query
375 val cursor = if(orderBy ne null) {
379 } // I really know that docs say that it is the same cursor.
381 if(!cursor.hasNext) {
385 val buff = new ListBuffer[A]()
387 while(cursor.hasNext) {
388 buff += deserializer apply cursor.next
394 case Some(sorter) => buff.toList.sortWith(sorter)
395 case None => buff.toList
400 def insertObject[A <: AnyRef](obj: A, collection: DBCollection, serializer: A ⇒ DBObject) : A = {
401 collection.insert(serializer apply obj, WriteConcern.JOURNAL_SAFE)
405 def jsonSupportToDBObject(jsonSupport: JsonSupport) = {
406 StdConverters.AllConverters.convertEx[DBObject](jsonSupport)
409 final def isLocalIMEvent(event: IMEventModel) = event match {
410 case _: MongoDBIMEvent ⇒ true
414 final def createIMEventFromJson(json: String) = {
415 MongoDBIMEvent.fromJsonString(json)
418 final def createIMEventFromOther(event: IMEventModel) = {
419 MongoDBIMEvent.fromOther(event, new ObjectId().toStringMongod)
422 final def createIMEventFromJsonBytes(jsonBytes: Array[Byte]) = {
423 MongoDBIMEvent.fromJsonBytes(jsonBytes)