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.computation.UserState.{JsonNames ⇒ UserStateJsonNames}
40 import gr.grnet.aquarium.util.json.JsonSupport
41 import collection.mutable.ListBuffer
42 import gr.grnet.aquarium.event._
43 import gr.grnet.aquarium.event.im.IMEventModel
44 import gr.grnet.aquarium.event.im.IMEventModel.{Names ⇒ IMEventNames}
45 import gr.grnet.aquarium.event.resource.ResourceEventModel
46 import gr.grnet.aquarium.event.resource.ResourceEventModel.{Names ⇒ ResourceEventNames}
47 import gr.grnet.aquarium.store._
48 import gr.grnet.aquarium.event.WalletEntry.{JsonNames ⇒ WalletJsonNames}
49 import gr.grnet.aquarium.event.PolicyEntry.{JsonNames ⇒ PolicyJsonNames}
51 import gr.grnet.aquarium.logic.accounting.Policy
53 import org.bson.types.ObjectId
54 import com.ckkloverdos.maybe.Maybe
55 import gr.grnet.aquarium.util._
56 import gr.grnet.aquarium.converter.Conversions
57 import gr.grnet.aquarium.computation.UserState
60 * Mongodb implementation of the various aquarium stores.
62 * @author Christos KK Loverdos <loverdos@gmail.com>
63 * @author Georgios Gousios <gousiosg@gmail.com>
70 extends ResourceEventStore
77 override type IMEvent = MongoDBIMEvent
78 override type ResourceEvent = MongoDBResourceEvent
80 private[store] lazy val resourceEvents = getCollection(MongoDBStore.RESOURCE_EVENTS_COLLECTION)
81 private[store] lazy val userStates = getCollection(MongoDBStore.USER_STATES_COLLECTION)
82 private[store] lazy val imEvents = getCollection(MongoDBStore.IM_EVENTS_COLLECTION)
83 private[store] lazy val unparsedIMEvents = getCollection(MongoDBStore.UNPARSED_IM_EVENTS_COLLECTION)
84 private[store] lazy val walletEntries = getCollection(MongoDBStore.WALLET_ENTRIES_COLLECTION)
85 private[store] lazy val policyEntries = getCollection(MongoDBStore.POLICY_ENTRIES_COLLECTION)
87 private[this] def getCollection(name: String): DBCollection = {
88 val db = mongo.getDB(database)
89 //logger.debug("Authenticating to mongo")
90 if(!db.isAuthenticated && !db.authenticate(username, password.toCharArray)) {
91 throw new StoreException("Could not authenticate user %s".format(username))
93 db.getCollection(name)
96 private[this] def _sortByTimestampAsc[A <: ExternalEventModel](one: A, two: A): Boolean = {
97 if (one.occurredMillis > two.occurredMillis) false
98 else if (one.occurredMillis < two.occurredMillis) true
102 //+ResourceEventStore
103 def createResourceEventFromOther(event: ResourceEventModel): ResourceEvent = {
104 MongoDBResourceEvent.fromOther(event, null)
107 def insertResourceEvent(event: ResourceEventModel) = {
108 val localEvent = MongoDBResourceEvent.fromOther(event, new ObjectId().toStringMongod)
109 MongoDBStore.insertObject(localEvent, resourceEvents, MongoDBStore.jsonSupportToDBObject)
113 def findResourceEventById(id: String): Option[ResourceEvent] = {
114 MongoDBStore.findBy(ResourceEventNames.id, id, resourceEvents, MongoDBResourceEvent.fromDBObject)
117 def findResourceEventsByUserId(userId: String)
118 (sortWith: Option[(ResourceEvent, ResourceEvent) => Boolean]): List[ResourceEvent] = {
119 val query = new BasicDBObject(ResourceEventNames.userID, userId)
121 MongoDBStore.runQuery(query, resourceEvents)(MongoDBResourceEvent.fromDBObject)(sortWith)
124 def findResourceEventsByUserIdAfterTimestamp(userId: String, timestamp: Long): List[ResourceEvent] = {
125 val query = new BasicDBObject()
126 query.put(ResourceEventNames.userID, userId)
127 query.put(ResourceEventNames.occurredMillis, new BasicDBObject("$gt", timestamp))
129 val sort = new BasicDBObject(ResourceEventNames.occurredMillis, 1)
131 val cursor = resourceEvents.find(query).sort(sort)
134 val buffer = new scala.collection.mutable.ListBuffer[ResourceEvent]
135 while(cursor.hasNext) {
136 buffer += MongoDBResourceEvent.fromDBObject(cursor.next())
138 buffer.toList.sortWith(_sortByTimestampAsc)
144 def findResourceEventHistory(userId: String, resName: String,
145 instid: Option[String], upTo: Long) : List[ResourceEvent] = {
146 val query = new BasicDBObject()
147 query.put(ResourceEventNames.userID, userId)
148 query.put(ResourceEventNames.occurredMillis, new BasicDBObject("$lt", upTo))
149 query.put(ResourceEventNames.resource, resName)
153 Policy.policy.findResource(resName) match {
154 case Some(y) => query.put(ResourceEventNames.details,
155 new BasicDBObject(y.descriminatorField, instid.get))
161 val sort = new BasicDBObject(ResourceEventNames.occurredMillis, 1)
162 val cursor = resourceEvents.find(query).sort(sort)
165 val buffer = new scala.collection.mutable.ListBuffer[ResourceEvent]
166 while(cursor.hasNext) {
167 buffer += MongoDBResourceEvent.fromDBObject(cursor.next())
169 buffer.toList.sortWith(_sortByTimestampAsc)
175 def findResourceEventsForReceivedPeriod(userId: String, startTimeMillis: Long, stopTimeMillis: Long): List[ResourceEvent] = {
176 val query = new BasicDBObject()
177 query.put(ResourceEventNames.userID, userId)
178 query.put(ResourceEventNames.receivedMillis, new BasicDBObject("$gte", startTimeMillis))
179 query.put(ResourceEventNames.receivedMillis, new BasicDBObject("$lte", stopTimeMillis))
181 // Sort them by increasing order for occurred time
182 val orderBy = new BasicDBObject(ResourceEventNames.occurredMillis, 1)
184 MongoDBStore.runQuery[ResourceEvent](query, resourceEvents, orderBy)(MongoDBResourceEvent.fromDBObject)(None)
187 def countOutOfSyncEventsForBillingPeriod(userId: String, startMillis: Long, stopMillis: Long): Long = {
192 def findAllRelevantResourceEventsForBillingPeriod(userId: String,
194 stopMillis: Long): List[ResourceEvent] = {
198 //-ResourceEventStore
201 def insertUserState(userState: UserState) = {
202 MongoDBStore.insertUserState(userState, userStates, MongoDBStore.jsonSupportToDBObject)
205 def findUserStateByUserID(userID: String): Option[UserState] = {
206 val query = new BasicDBObject(UserStateJsonNames.userID, userID)
207 val cursor = userStates find query
209 withCloseable(cursor) { cursor ⇒
211 Some(MongoDBStore.dbObjectToUserState(cursor.next()))
218 def findLatestUserStateByUserID(userID: String) = {
223 def findLatestUserStateForEndOfBillingMonth(userId: String,
224 yearOfBillingMonth: Int,
225 billingMonth: Int): Option[UserState] = {
226 None // FIXME: implement
229 def deleteUserState(userId: String) = {
230 val query = new BasicDBObject(UserStateJsonNames.userID, userId)
231 userStates.findAndRemove(query)
236 def storeWalletEntry(entry: WalletEntry): Maybe[RecordID] = {
238 MongoDBStore.storeAny[WalletEntry](
243 MongoDBStore.jsonSupportToDBObject)
247 def findWalletEntryById(id: String): Maybe[WalletEntry] = {
248 MongoDBStore.findBy(WalletJsonNames.id, id, walletEntries, MongoDBStore.dbObjectToWalletEntry): Maybe[WalletEntry]
251 def findUserWalletEntries(userId: String) = {
253 findUserWalletEntriesFromTo(userId, new Date(0), new Date(Int.MaxValue))
256 def findUserWalletEntriesFromTo(userId: String, from: Date, to: Date) : List[WalletEntry] = {
257 val q = new BasicDBObject()
258 // TODO: Is this the correct way for an AND query?
259 q.put(WalletJsonNames.occurredMillis, new BasicDBObject("$gt", from.getTime))
260 q.put(WalletJsonNames.occurredMillis, new BasicDBObject("$lt", to.getTime))
261 q.put(WalletJsonNames.userId, userId)
263 MongoDBStore.runQuery[WalletEntry](q, walletEntries)(MongoDBStore.dbObjectToWalletEntry)(Some(_sortByTimestampAsc))
266 def findWalletEntriesAfter(userId: String, from: Date) : List[WalletEntry] = {
267 val q = new BasicDBObject()
268 q.put(WalletJsonNames.occurredMillis, new BasicDBObject("$gt", from.getTime))
269 q.put(WalletJsonNames.userId, userId)
271 MongoDBStore.runQuery[WalletEntry](q, walletEntries)(MongoDBStore.dbObjectToWalletEntry)(Some(_sortByTimestampAsc))
274 def findLatestUserWalletEntries(userId: String) = {
276 val orderBy = new BasicDBObject(WalletJsonNames.occurredMillis, -1) // -1 is descending order
277 val cursor = walletEntries.find().sort(orderBy)
280 val buffer = new scala.collection.mutable.ListBuffer[WalletEntry]
282 val walletEntry = MongoDBStore.dbObjectToWalletEntry(cursor.next())
283 buffer += walletEntry
285 var _previousOccurredMillis = walletEntry.occurredMillis
288 while(cursor.hasNext && _ok) {
289 val walletEntry = MongoDBStore.dbObjectToWalletEntry(cursor.next())
290 var currentOccurredMillis = walletEntry.occurredMillis
291 _ok = currentOccurredMillis == _previousOccurredMillis
294 buffer += walletEntry
308 def findPreviousEntry(userId: String, resource: String,
310 finalized: Option[Boolean]): List[WalletEntry] = {
311 val q = new BasicDBObject()
312 q.put(WalletJsonNames.userId, userId)
313 q.put(WalletJsonNames.resource, resource)
314 q.put(WalletJsonNames.instanceId, instanceId)
316 case Some(x) => q.put(WalletJsonNames.finalized, x)
320 MongoDBStore.runQuery[WalletEntry](q, walletEntries)(MongoDBStore.dbObjectToWalletEntry)(Some(_sortByTimestampAsc))
325 def createIMEventFromJson(json: String) = {
326 MongoDBStore.createIMEventFromJson(json)
329 def createIMEventFromOther(event: IMEventModel) = {
330 MongoDBStore.createIMEventFromOther(event)
333 def insertIMEvent(event: IMEventModel): IMEvent = {
334 val localEvent = MongoDBIMEvent.fromOther(event, new ObjectId().toStringMongod)
335 MongoDBStore.insertObject(localEvent, imEvents, MongoDBStore.jsonSupportToDBObject)
339 def findIMEventById(id: String): Option[IMEvent] = {
340 MongoDBStore.findBy(IMEventNames.id, id, imEvents, MongoDBIMEvent.fromDBObject)
345 def loadPolicyEntriesAfter(after: Long): List[PolicyEntry] = {
346 val query = new BasicDBObject(PolicyEntry.JsonNames.validFrom,
347 new BasicDBObject("$gt", after))
348 MongoDBStore.runQuery(query, policyEntries)(MongoDBStore.dbObjectToPolicyEntry)(Some(_sortByTimestampAsc))
351 def storePolicyEntry(policy: PolicyEntry): Maybe[RecordID] = MongoDBStore.storePolicyEntry(policy, policyEntries)
354 def updatePolicyEntry(policy: PolicyEntry) = {
356 val query = new BasicDBObject(PolicyEntry.JsonNames.id, policy.id)
357 val policyObject = MongoDBStore.jsonSupportToDBObject(policy)
358 policyEntries.update(query, policyObject, true, false)
361 def findPolicyEntry(id: String) = {
362 MongoDBStore.findBy(PolicyJsonNames.id, id, policyEntries, MongoDBStore.dbObjectToPolicyEntry)
368 object MongoDBStore {
370 final val _id = "_id"
374 * Collection holding the [[gr.grnet.aquarium.event.resource.ResourceEventModel]]s.
376 * Resource events are coming from all systems handling billable resources.
378 final val RESOURCE_EVENTS_COLLECTION = "resevents"
381 * Collection holding the snapshots of [[gr.grnet.aquarium.computation.UserState]].
383 * [[gr.grnet.aquarium.computation.UserState]] is held internally within [[gr.grnet.aquarium.actor.service.user.UserActor]]s.
385 final val USER_STATES_COLLECTION = "userstates"
388 * Collection holding [[gr.grnet.aquarium.event.im.IMEventModel]]s.
390 * User events are coming from the IM module (external).
392 final val IM_EVENTS_COLLECTION = "imevents"
395 * Collection holding [[gr.grnet.aquarium.event.im.IMEventModel]]s that could not be parsed to normal objects.
397 * We of course assume at least a valid JSON representation.
399 * User events are coming from the IM module (external).
401 final val UNPARSED_IM_EVENTS_COLLECTION = "unparsed_imevents"
404 * Collection holding [[gr.grnet.aquarium.event.WalletEntry]].
406 * Wallet entries are generated internally in Aquarium.
408 final val WALLET_ENTRIES_COLLECTION = "wallets"
411 * Collection holding [[gr.grnet.aquarium.logic.accounting.dsl.DSLPolicy]].
413 // final val POLICIES_COLLECTION = "policies"
416 * Collection holding [[gr.grnet.aquarium.event.PolicyEntry]].
418 final val POLICY_ENTRIES_COLLECTION = "policyEntries"
420 def dbObjectToUserState(dbObj: DBObject): UserState = {
421 UserState.fromJson(JSON.serialize(dbObj))
424 def dbObjectToWalletEntry(dbObj: DBObject): WalletEntry = {
425 WalletEntry.fromJson(JSON.serialize(dbObj))
428 def dbObjectToPolicyEntry(dbObj: DBObject): PolicyEntry = {
429 PolicyEntry.fromJson(JSON.serialize(dbObj))
432 def findBy[A >: Null <: AnyRef](name: String,
434 collection: DBCollection,
435 deserializer: (DBObject) => A) : Option[A] = {
436 val query = new BasicDBObject(name, value)
437 val cursor = collection find query
439 withCloseable(cursor) { cursor ⇒
441 Some(deserializer apply cursor.next)
447 def runQuery[A <: ExternalEventModel](query: DBObject, collection: DBCollection, orderBy: DBObject = null)
448 (deserializer: (DBObject) => A)
449 (sortWith: Option[(A, A) => Boolean]): List[A] = {
450 val cursor0 = collection find query
451 val cursor = if(orderBy ne null) {
455 } // I really know that docs say that it is the same cursor.
457 if(!cursor.hasNext) {
461 val buff = new ListBuffer[A]()
463 while(cursor.hasNext) {
464 buff += deserializer apply cursor.next
470 case Some(sorter) => buff.toList.sortWith(sorter)
471 case None => buff.toList
476 def storeUserState(userState: UserState, collection: DBCollection) = {
477 storeAny[UserState](userState, collection, ResourceEventNames.userID, _.userID, MongoDBStore.jsonSupportToDBObject)
480 def storePolicyEntry(policyEntry: PolicyEntry, collection: DBCollection): Maybe[RecordID] = {
481 Maybe(storeAny[PolicyEntry](policyEntry, collection, PolicyJsonNames.id, _.id, MongoDBStore.jsonSupportToDBObject))
484 def storeAny[A](any: A,
485 collection: DBCollection,
487 idValueProvider: (A) => String,
488 serializer: (A) => DBObject) : RecordID = {
490 val dbObject = serializer apply any
491 val _id = new ObjectId()
492 dbObject.put("_id", _id)
493 val writeResult = collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
494 writeResult.getLastError().throwOnError()
496 RecordID(dbObject.get("_id").toString)
499 // FIXME: consolidate
500 def insertUserState[A <: UserState](obj: A, collection: DBCollection, serializer: A ⇒ DBObject) = {
501 val dbObject = serializer apply obj
502 val objectId = obj._id match {
504 val _id = new ObjectId()
505 dbObject.put("_id", _id)
512 dbObject.put(JsonNames._id, objectId)
514 collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
519 def insertObject[A <: MongoDBEventModel](obj: A, collection: DBCollection, serializer: (A) => DBObject) : Unit = {
520 val dbObject = serializer apply obj
521 val objectId = obj._id match {
523 val _id = new ObjectId()
524 dbObject.put("_id", _id)
531 dbObject.put(JsonNames._id, objectId)
533 collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
536 def jsonSupportToDBObject(jsonSupport: JsonSupport) = {
537 Conversions.jsonSupportToDBObject(jsonSupport)
540 final def isLocalIMEvent(event: IMEventModel) = event match {
541 case _: MongoDBIMEvent ⇒ true
545 final def createIMEventFromJson(json: String) = {
546 MongoDBIMEvent.fromJsonString(json)
549 final def createIMEventFromOther(event: IMEventModel) = {
550 MongoDBIMEvent.fromOther(event, null)
553 final def createIMEventFromJsonBytes(jsonBytes: Array[Byte]) = {
554 MongoDBIMEvent.fromJsonBytes(jsonBytes)