2 * Copyright 2011 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 gr.grnet.aquarium.util.Loggable
39 import com.mongodb.util.JSON
40 import gr.grnet.aquarium.user.UserState
41 import gr.grnet.aquarium.user.UserState.{JsonNames => UserStateJsonNames}
42 import gr.grnet.aquarium.util.displayableObjectInfo
43 import gr.grnet.aquarium.util.json.JsonSupport
44 import collection.mutable.ListBuffer
45 import gr.grnet.aquarium.store._
46 import gr.grnet.aquarium.logic.events.ResourceEvent.{JsonNames => ResourceJsonNames}
47 import gr.grnet.aquarium.logic.events.UserEvent.{JsonNames => UserEventJsonNames}
48 import gr.grnet.aquarium.logic.events.WalletEntry.{JsonNames => WalletJsonNames}
49 import gr.grnet.aquarium.logic.events.PolicyEntry.{JsonNames => PolicyJsonNames}
51 import gr.grnet.aquarium.logic.accounting.Policy
52 import gr.grnet.aquarium.logic.events._
54 import com.ckkloverdos.maybe.{NoVal, Maybe}
55 import gr.grnet.aquarium.logic.accounting.dsl.{DSLResource, Timeslot, DSLPolicy, DSLComplexResource}
58 * Mongodb implementation of the various aquarium stores.
60 * @author Christos KK Loverdos <loverdos@gmail.com>
61 * @author Georgios Gousios <gousiosg@gmail.com>
68 extends ResourceEventStore
75 private[store] lazy val resourceEvents = getCollection(MongoDBStore.RESOURCE_EVENTS_COLLECTION)
76 private[store] lazy val userStates = getCollection(MongoDBStore.USER_STATES_COLLECTION)
77 private[store] lazy val userEvents = getCollection(MongoDBStore.USER_EVENTS_COLLECTION)
78 private[store] lazy val walletEntries = getCollection(MongoDBStore.WALLET_ENTRIES_COLLECTION)
79 // private[store] lazy val policies = getCollection(MongoDBStore.POLICIES_COLLECTION)
80 private[store] lazy val policyEntries = getCollection(MongoDBStore.POLICY_ENTRIES_COLLECTION)
82 private[this] def getCollection(name: String): DBCollection = {
83 val db = mongo.getDB(database)
84 //logger.debug("Authenticating to mongo")
85 if(!db.isAuthenticated && !db.authenticate(username, password.toCharArray)) {
86 throw new StoreException("Could not authenticate user %s".format(username))
88 db.getCollection(name)
91 private[this] def _sortByTimestampAsc[A <: AquariumEvent](one: A, two: A): Boolean = {
92 if (one.occurredMillis > two.occurredMillis) false
93 else if (one.occurredMillis < two.occurredMillis) true
97 private[this] def _sortByTimestampDesc[A <: AquariumEvent](one: A, two: A): Boolean = {
98 if (one.occurredMillis < two.occurredMillis) false
99 else if (one.occurredMillis > two.occurredMillis) true
103 //+ResourceEventStore
104 def storeResourceEvent(event: ResourceEvent): Maybe[RecordID] =
105 MongoDBStore.storeAquariumEvent(event, resourceEvents)
107 def findResourceEventById(id: String): Maybe[ResourceEvent] =
108 MongoDBStore.findById(id, resourceEvents, MongoDBStore.dbObjectToResourceEvent)
110 def findResourceEventsByUserId(userId: String)
111 (sortWith: Option[(ResourceEvent, ResourceEvent) => Boolean]): List[ResourceEvent] = {
112 val query = new BasicDBObject(ResourceJsonNames.userId, userId)
114 MongoDBStore.runQuery(query, resourceEvents)(MongoDBStore.dbObjectToResourceEvent)(sortWith)
117 def findResourceEventsByUserIdAfterTimestamp(userId: String, timestamp: Long): List[ResourceEvent] = {
118 val query = new BasicDBObject()
119 query.put(ResourceJsonNames.userId, userId)
120 query.put(ResourceJsonNames.occurredMillis, new BasicDBObject("$gt", timestamp))
122 val sort = new BasicDBObject(ResourceJsonNames.occurredMillis, 1)
124 val cursor = resourceEvents.find(query).sort(sort)
127 val buffer = new scala.collection.mutable.ListBuffer[ResourceEvent]
128 while(cursor.hasNext) {
129 buffer += MongoDBStore.dbObjectToResourceEvent(cursor.next())
131 buffer.toList.sortWith(_sortByTimestampAsc)
137 def findResourceEventHistory(userId: String, resName: String,
138 instid: Option[String], upTo: Long) : List[ResourceEvent] = {
139 val query = new BasicDBObject()
140 query.put(ResourceJsonNames.userId, userId)
141 query.put(ResourceJsonNames.occurredMillis, new BasicDBObject("$lt", upTo))
142 query.put(ResourceJsonNames.resource, resName)
146 Policy.policy.findResource(resName) match {
147 case Some(y) => query.put(ResourceJsonNames.details,
148 new BasicDBObject(y.descriminatorField, instid.get))
154 val sort = new BasicDBObject(ResourceJsonNames.occurredMillis, 1)
155 val cursor = resourceEvents.find(query).sort(sort)
158 val buffer = new scala.collection.mutable.ListBuffer[ResourceEvent]
159 while(cursor.hasNext) {
160 buffer += MongoDBStore.dbObjectToResourceEvent(cursor.next())
162 buffer.toList.sortWith(_sortByTimestampAsc)
168 def findResourceEventsForReceivedPeriod(userId: String, startTimeMillis: Long, stopTimeMillis: Long): List[ResourceEvent] = {
169 val query = new BasicDBObject()
170 query.put(ResourceJsonNames.userId, userId)
171 query.put(ResourceJsonNames.receivedMillis, new BasicDBObject("$gte", startTimeMillis))
172 query.put(ResourceJsonNames.receivedMillis, new BasicDBObject("$lte", stopTimeMillis))
174 // Sort them by increasing order for occurred time
175 val orderBy = new BasicDBObject(ResourceJsonNames.occurredMillis, 1)
177 MongoDBStore.runQuery[ResourceEvent](query, resourceEvents, orderBy)(MongoDBStore.dbObjectToResourceEvent)(None)
180 def countOutOfSyncEventsForBillingPeriod(userId: String, startMillis: Long, stopMillis: Long): Maybe[Long] = {
187 def findAllRelevantResourceEventsForBillingPeriod(userId: String,
189 stopMillis: Long): List[ResourceEvent] = {
193 //-ResourceEventStore
196 def storeUserState(userState: UserState): Maybe[RecordID] = {
197 MongoDBStore.storeUserState(userState, userStates)
200 def findUserStateByUserId(userId: String): Maybe[UserState] = {
202 val query = new BasicDBObject(UserStateJsonNames.userId, userId)
203 val cursor = userStates find query
207 MongoDBStore.dbObjectToUserState(cursor.next())
216 def findLatestUserStateForEndOfBillingMonth(userId: String,
217 yearOfBillingMonth: Int,
218 billingMonth: Int): Maybe[UserState] = {
219 NoVal // FIXME: implement
222 def deleteUserState(userId: String) = {
223 val query = new BasicDBObject(UserStateJsonNames.userId, userId)
224 userStates.findAndRemove(query)
229 def storeWalletEntry(entry: WalletEntry): Maybe[RecordID] =
230 MongoDBStore.storeAquariumEvent(entry, walletEntries)
232 def findWalletEntryById(id: String): Maybe[WalletEntry] =
233 MongoDBStore.findById[WalletEntry](id, walletEntries, MongoDBStore.dbObjectToWalletEntry)
235 def findUserWalletEntries(userId: String) = {
237 findUserWalletEntriesFromTo(userId, new Date(0), new Date(Int.MaxValue))
240 def findUserWalletEntriesFromTo(userId: String, from: Date, to: Date) : List[WalletEntry] = {
241 val q = new BasicDBObject()
242 // TODO: Is this the correct way for an AND query?
243 q.put(WalletJsonNames.occurredMillis, new BasicDBObject("$gt", from.getTime))
244 q.put(WalletJsonNames.occurredMillis, new BasicDBObject("$lt", to.getTime))
245 q.put(WalletJsonNames.userId, userId)
247 MongoDBStore.runQuery[WalletEntry](q, walletEntries)(MongoDBStore.dbObjectToWalletEntry)(Some(_sortByTimestampAsc))
250 def findWalletEntriesAfter(userId: String, from: Date) : List[WalletEntry] = {
251 val q = new BasicDBObject()
252 q.put(WalletJsonNames.occurredMillis, new BasicDBObject("$gt", from.getTime))
253 q.put(WalletJsonNames.userId, userId)
255 MongoDBStore.runQuery[WalletEntry](q, walletEntries)(MongoDBStore.dbObjectToWalletEntry)(Some(_sortByTimestampAsc))
258 def findLatestUserWalletEntries(userId: String) = {
260 val orderBy = new BasicDBObject(WalletJsonNames.occurredMillis, -1) // -1 is descending order
261 val cursor = walletEntries.find().sort(orderBy)
264 val buffer = new scala.collection.mutable.ListBuffer[WalletEntry]
266 val walletEntry = MongoDBStore.dbObjectToWalletEntry(cursor.next())
267 buffer += walletEntry
269 var _previousOccurredMillis = walletEntry.occurredMillis
272 while(cursor.hasNext && _ok) {
273 val walletEntry = MongoDBStore.dbObjectToWalletEntry(cursor.next())
274 var currentOccurredMillis = walletEntry.occurredMillis
275 _ok = currentOccurredMillis == _previousOccurredMillis
278 buffer += walletEntry
292 def findPreviousEntry(userId: String, resource: String,
294 finalized: Option[Boolean]): List[WalletEntry] = {
295 val q = new BasicDBObject()
296 q.put(WalletJsonNames.userId, userId)
297 q.put(WalletJsonNames.resource, resource)
298 q.put(WalletJsonNames.instanceId, instanceId)
300 case Some(x) => q.put(WalletJsonNames.finalized, x)
304 MongoDBStore.runQuery[WalletEntry](q, walletEntries)(MongoDBStore.dbObjectToWalletEntry)(Some(_sortByTimestampAsc))
309 def storeUserEvent(event: UserEvent): Maybe[RecordID] =
310 MongoDBStore.storeAny[UserEvent](event, userEvents, UserEventJsonNames.userId,
311 _.userID, MongoDBStore.jsonSupportToDBObject)
314 def findUserEventById(id: String): Maybe[UserEvent] =
315 MongoDBStore.findById[UserEvent](id, userEvents, MongoDBStore.dbObjectToUserEvent)
317 def findUserEventsByUserId(userId: String): List[UserEvent] = {
318 val query = new BasicDBObject(UserEventJsonNames.userId, userId)
319 MongoDBStore.runQuery(query, userEvents)(MongoDBStore.dbObjectToUserEvent)(Some(_sortByTimestampAsc))
324 def loadPolicyEntriesAfter(after: Long): List[PolicyEntry] = {
325 val query = new BasicDBObject(PolicyEntry.JsonNames.validFrom,
326 new BasicDBObject("$gt", after))
327 MongoDBStore.runQuery(query, policyEntries)(MongoDBStore.dbObjectToPolicyEntry)(Some(_sortByTimestampAsc))
330 def storePolicyEntry(policy: PolicyEntry): Maybe[RecordID] = MongoDBStore.storePolicyEntry(policy, policyEntries)
333 def updatePolicyEntry(policy: PolicyEntry) = {
335 val query = new BasicDBObject(PolicyEntry.JsonNames.id, policy.id)
336 val policyObject = MongoDBStore.jsonSupportToDBObject(policy)
337 policyEntries.update(query, policyObject, true, false)
340 def findPolicyEntry(id: String) =
341 MongoDBStore.findById[PolicyEntry](id, policyEntries, MongoDBStore.dbObjectToPolicyEntry)
346 object MongoDBStore {
348 final val _id = "_id"
352 * Collection holding the [[gr.grnet.aquarium.logic.events.ResourceEvent]]s.
354 * Resource events are coming from all systems handling billable resources.
356 final val RESOURCE_EVENTS_COLLECTION = "resevents"
359 * Collection holding the snapshots of [[gr.grnet.aquarium.user.UserState]].
361 * [[gr.grnet.aquarium.user.UserState]] is held internally within [[gr.grnet.aquarium.user.actor.UserActor]]s.
363 final val USER_STATES_COLLECTION = "userstates"
366 * Collection holding [[gr.grnet.aquarium.logic.events.UserEvent]]s.
368 * User events are coming from the IM module (external).
370 final val USER_EVENTS_COLLECTION = "userevents"
373 * Collection holding [[gr.grnet.aquarium.logic.events.WalletEntry]].
375 * Wallet entries are generated internally in Aquarium.
377 final val WALLET_ENTRIES_COLLECTION = "wallets"
380 * Collection holding [[gr.grnet.aquarium.logic.accounting.dsl.DSLPolicy]].
382 // final val POLICIES_COLLECTION = "policies"
385 * Collection holding [[gr.grnet.aquarium.logic.events.PolicyEntry]].
387 final val POLICY_ENTRIES_COLLECTION = "policyEntries"
389 /* TODO: Some of the following methods rely on JSON (de-)serialization).
390 * A method based on proper object serialization would be much faster.
392 def dbObjectToResourceEvent(dbObject: DBObject): ResourceEvent = {
393 ResourceEvent.fromJson(JSON.serialize(dbObject))
396 def dbObjectToUserState(dbObj: DBObject): UserState = {
397 UserState.fromJson(JSON.serialize(dbObj))
400 def dbObjectToWalletEntry(dbObj: DBObject): WalletEntry = {
401 WalletEntry.fromJson(JSON.serialize(dbObj))
404 def dbObjectToUserEvent(dbObj: DBObject): UserEvent = {
405 UserEvent.fromJson(JSON.serialize(dbObj))
408 def dbObjectToPolicyEntry(dbObj: DBObject): PolicyEntry = {
409 PolicyEntry.fromJson(JSON.serialize(dbObj))
412 def findById[A >: Null <: AquariumEvent](id: String, collection: DBCollection, deserializer: (DBObject) => A) : Maybe[A] = Maybe {
413 val query = new BasicDBObject(ResourceJsonNames.id, id)
414 val cursor = collection find query
418 deserializer apply cursor.next
420 null: A // will be transformed to NoVal by the Maybe polymorphic constructor
426 def runQuery[A <: AquariumEvent](query: DBObject, collection: DBCollection, orderBy: DBObject = null)
427 (deserializer: (DBObject) => A)
428 (sortWith: Option[(A, A) => Boolean]): List[A] = {
429 val cursor0 = collection find query
430 val cursor = if(orderBy ne null) {
434 } // I really know that docs say that it is the same cursor.
436 if(!cursor.hasNext) {
440 val buff = new ListBuffer[A]()
442 while(cursor.hasNext) {
443 buff += deserializer apply cursor.next
449 case Some(sorter) => buff.toList.sortWith(sorter)
450 case None => buff.toList
455 def storeAquariumEvent[A <: AquariumEvent](event: A, collection: DBCollection) : Maybe[RecordID] = {
456 storeAny[A](event, collection, ResourceJsonNames.id, (e) => e.id, MongoDBStore.jsonSupportToDBObject)
459 def storeUserState(userState: UserState, collection: DBCollection): Maybe[RecordID] = {
460 storeAny[UserState](userState, collection, ResourceJsonNames.userId, _.userId, MongoDBStore.jsonSupportToDBObject)
463 def storePolicyEntry(policyEntry: PolicyEntry, collection: DBCollection): Maybe[RecordID] = {
464 storeAny[PolicyEntry](policyEntry, collection, PolicyJsonNames.id, _.id, MongoDBStore.jsonSupportToDBObject)
467 def storeAny[A](any: A,
468 collection: DBCollection,
470 idValueProvider: (A) => String,
471 serializer: (A) => DBObject) : Maybe[RecordID] = {
472 import com.ckkloverdos.maybe.effect
475 val dbObj = serializer apply any
476 val writeResult = collection insert dbObj
477 writeResult.getLastError().throwOnError()
479 // Get back to retrieve unique id
480 val cursor = collection.find(new BasicDBObject(idName, idValueProvider(any)))
485 RecordID(cursor.next().get(JsonNames._id).toString)
487 throw new StoreException("Could not store %s to %s".format(any, collection))
488 } {} { cursor.close() }
492 def jsonSupportToDBObject(any: JsonSupport): DBObject = {
493 JSON.parse(any.toJson) match {
494 case dbObject: DBObject ⇒
497 throw new StoreException("Could not transform %s -> %s".format(displayableObjectInfo(any), classOf[DBObject].getName))