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.model.im.IMEventModel
43 import gr.grnet.aquarium.event.model.im.IMEventModel.{Names ⇒ IMEventNames}
44 import gr.grnet.aquarium.event.model.resource.ResourceEventModel
45 import gr.grnet.aquarium.event.model.resource.ResourceEventModel.{Names ⇒ ResourceEventNames}
46 import gr.grnet.aquarium.store._
47 import gr.grnet.aquarium.event.model.PolicyEntry.{JsonNames ⇒ PolicyJsonNames}
48 import gr.grnet.aquarium.logic.accounting.Policy
50 import org.bson.types.ObjectId
51 import com.ckkloverdos.maybe.Maybe
52 import gr.grnet.aquarium.util._
53 import gr.grnet.aquarium.converter.Conversions
54 import gr.grnet.aquarium.computation.UserState
55 import gr.grnet.aquarium.event.model.{ExternalEventModel, PolicyEntry}
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
74 override type IMEvent = MongoDBIMEvent
75 override type ResourceEvent = MongoDBResourceEvent
77 private[store] lazy val resourceEvents = getCollection(MongoDBStore.RESOURCE_EVENTS_COLLECTION)
78 private[store] lazy val userStates = getCollection(MongoDBStore.USER_STATES_COLLECTION)
79 private[store] lazy val imEvents = getCollection(MongoDBStore.IM_EVENTS_COLLECTION)
80 private[store] lazy val unparsedIMEvents = getCollection(MongoDBStore.UNPARSED_IM_EVENTS_COLLECTION)
81 private[store] lazy val policyEntries = getCollection(MongoDBStore.POLICY_ENTRIES_COLLECTION)
83 private[this] def getCollection(name: String): DBCollection = {
84 val db = mongo.getDB(database)
85 //logger.debug("Authenticating to mongo")
86 if(!db.isAuthenticated && !db.authenticate(username, password.toCharArray)) {
87 throw new StoreException("Could not authenticate user %s".format(username))
89 db.getCollection(name)
92 private[this] def _sortByTimestampAsc[A <: ExternalEventModel](one: A, two: A): Boolean = {
93 if (one.occurredMillis > two.occurredMillis) false
94 else if (one.occurredMillis < two.occurredMillis) true
99 def createResourceEventFromOther(event: ResourceEventModel): ResourceEvent = {
100 MongoDBResourceEvent.fromOther(event, null)
103 def pingResourceEventStore(): Unit = synchronized {
104 MongoDBStore.ping(mongo)
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 countOutOfSyncResourceEventsForBillingPeriod(userID: String, startMillis: Long, stopMillis: Long): Long = {
188 val query = new BasicDBObjectBuilder().
189 add(ResourceEventModel.Names.userID, userID).
190 // received within the period
191 add(ResourceEventModel.Names.receivedMillis, new BasicDBObject("$gte", startMillis)).
192 add(ResourceEventModel.Names.receivedMillis, new BasicDBObject("$lte", stopMillis)).
193 // occurred outside the period
195 val dbList = new BasicDBList()
196 dbList.add(0, new BasicDBObject(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$lt", startMillis)))
197 dbList.add(1, new BasicDBObject(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$gt", stopMillis)))
202 resourceEvents.count(query)
205 def findAllRelevantResourceEventsForBillingPeriod(userId: String,
207 stopMillis: Long): List[ResourceEvent] = {
211 //-ResourceEventStore
214 def insertUserState(userState: UserState) = {
215 MongoDBStore.insertUserState(
216 userState.copy(_id = new ObjectId().toString),
218 MongoDBStore.jsonSupportToDBObject
222 def findUserStateByUserID(userID: String): Option[UserState] = {
223 val query = new BasicDBObject(UserStateJsonNames.userID, userID)
224 val cursor = userStates find query
226 MongoDBStore.firstResultIfExists(cursor, MongoDBStore.dbObjectToUserState)
229 def findLatestUserStateForEndOfBillingMonth(userID: String,
230 yearOfBillingMonth: Int,
231 billingMonth: Int): Option[UserState] = {
232 val query = new BasicDBObjectBuilder().
233 add(UserState.JsonNames.userID, userID).
234 add(UserState.JsonNames.isFullBillingMonthState, true).
235 add(UserState.JsonNames.theFullBillingMonth.year, yearOfBillingMonth).
236 add(UserState.JsonNames.theFullBillingMonth.month, billingMonth).
239 // Descending order, so that the latest comes first
240 val sorter = new BasicDBObject(UserState.JsonNames.occurredMillis, -1)
242 val cursor = userStates.find(query).sort(sorter)
244 MongoDBStore.firstResultIfExists(cursor, MongoDBStore.dbObjectToUserState)
247 def deleteUserState(userId: String) = {
248 val query = new BasicDBObject(UserStateJsonNames.userID, userId)
249 userStates.findAndRemove(query)
254 def createIMEventFromJson(json: String) = {
255 MongoDBStore.createIMEventFromJson(json)
258 def createIMEventFromOther(event: IMEventModel) = {
259 MongoDBStore.createIMEventFromOther(event)
262 def pingIMEventStore(): Unit = {
263 MongoDBStore.ping(mongo)
266 def insertIMEvent(event: IMEventModel): IMEvent = {
267 val localEvent = MongoDBIMEvent.fromOther(event, new ObjectId().toStringMongod)
268 MongoDBStore.insertObject(localEvent, imEvents, MongoDBStore.jsonSupportToDBObject)
272 def findIMEventById(id: String): Option[IMEvent] = {
273 MongoDBStore.findBy(IMEventNames.id, id, imEvents, MongoDBIMEvent.fromDBObject)
278 * Find the `CREATE` even for the given user. Note that there must be only one such event.
280 def findCreateIMEventByUserID(userID: String): Option[IMEvent] = {
281 val query = new BasicDBObjectBuilder().
282 add(IMEventNames.userID, userID).
283 add(IMEventNames.eventType, IMEventModel.EventTypeNames.create).get()
285 // Normally one such event is allowed ...
286 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
288 MongoDBStore.firstResultIfExists(cursor, MongoDBIMEvent.fromDBObject)
291 def findLatestIMEventByUserID(userID: String): Option[IMEvent] = {
292 val query = new BasicDBObject(IMEventNames.userID, userID)
293 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, -1))
295 MongoDBStore.firstResultIfExists(cursor, MongoDBIMEvent.fromDBObject)
299 * Find the very first activation event for a particular user.
302 def findFirstIsActiveIMEventByUserID(userID: String): Option[IMEvent] = {
303 val query = new BasicDBObjectBuilder().
304 add(IMEventNames.userID, userID).
305 add(IMEventNames.isActive, true).get()
307 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
309 withCloseable(cursor) { cursor ⇒
311 Some(MongoDBIMEvent.fromDBObject(cursor.next()))
319 * Scans events for the given user, sorted by `occurredMillis` in ascending order and runs them through
320 * the given function `f`.
322 * Any exception is propagated to the caller. The underlying DB resources are properly disposed in any case.
324 def replayIMEventsInOccurrenceOrder(userID: String)(f: (IMEvent) => Unit) = {
325 val query = new BasicDBObject(IMEventNames.userID, userID)
326 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
328 withCloseable(cursor) { cursor ⇒
329 while(cursor.hasNext) {
330 val model = MongoDBIMEvent.fromDBObject(cursor.next())
340 def loadPolicyEntriesAfter(after: Long): List[PolicyEntry] = {
341 val query = new BasicDBObject(PolicyEntry.JsonNames.validFrom,
342 new BasicDBObject("$gt", after))
343 MongoDBStore.runQuery(query, policyEntries)(MongoDBStore.dbObjectToPolicyEntry)(Some(_sortByTimestampAsc))
346 def storePolicyEntry(policy: PolicyEntry): Maybe[RecordID] = MongoDBStore.storePolicyEntry(policy, policyEntries)
349 def updatePolicyEntry(policy: PolicyEntry) = {
351 val query = new BasicDBObject(PolicyEntry.JsonNames.id, policy.id)
352 val policyObject = MongoDBStore.jsonSupportToDBObject(policy)
353 policyEntries.update(query, policyObject, true, false)
356 def findPolicyEntry(id: String) = {
357 MongoDBStore.findBy(PolicyJsonNames.id, id, policyEntries, MongoDBStore.dbObjectToPolicyEntry)
363 object MongoDBStore {
365 final val _id = "_id"
369 * Collection holding the [[gr.grnet.aquarium.event.model.resource.ResourceEventModel]]s.
371 * Resource events are coming from all systems handling billable resources.
373 final val RESOURCE_EVENTS_COLLECTION = "resevents"
376 * Collection holding the snapshots of [[gr.grnet.aquarium.computation.UserState]].
378 * [[gr.grnet.aquarium.computation.UserState]] is held internally within [[gr.grnet.aquarium.actor.service.user.UserActor]]s.
380 final val USER_STATES_COLLECTION = "userstates"
383 * Collection holding [[gr.grnet.aquarium.event.model.im.IMEventModel]]s.
385 * User events are coming from the IM module (external).
387 final val IM_EVENTS_COLLECTION = "imevents"
390 * Collection holding [[gr.grnet.aquarium.event.model.im.IMEventModel]]s that could not be parsed to normal objects.
392 * We of course assume at least a valid JSON representation.
394 * User events are coming from the IM module (external).
396 final val UNPARSED_IM_EVENTS_COLLECTION = "unparsed_imevents"
399 * Collection holding [[gr.grnet.aquarium.logic.accounting.dsl.DSLPolicy]].
401 // final val POLICIES_COLLECTION = "policies"
404 * Collection holding [[gr.grnet.aquarium.event.model.PolicyEntry]].
406 final val POLICY_ENTRIES_COLLECTION = "policyEntries"
408 def dbObjectToUserState(dbObj: DBObject): UserState = {
409 UserState.fromJson(JSON.serialize(dbObj))
412 def firstResultIfExists[A](cursor: DBCursor, f: DBObject ⇒ A): Option[A] = {
413 withCloseable(cursor) { cursor ⇒
415 Some(f(cursor.next()))
422 def dbObjectToPolicyEntry(dbObj: DBObject): PolicyEntry = {
423 PolicyEntry.fromJson(JSON.serialize(dbObj))
426 def ping(mongo: Mongo): Unit = synchronized {
427 // This requires a network roundtrip
431 def findBy[A >: Null <: AnyRef](name: String,
433 collection: DBCollection,
434 deserializer: (DBObject) => A) : Option[A] = {
435 val query = new BasicDBObject(name, value)
436 val cursor = collection find query
438 withCloseable(cursor) { cursor ⇒
440 Some(deserializer apply cursor.next)
446 def runQuery[A <: ExternalEventModel](query: DBObject, collection: DBCollection, orderBy: DBObject = null)
447 (deserializer: (DBObject) => A)
448 (sortWith: Option[(A, A) => Boolean]): List[A] = {
449 val cursor0 = collection find query
450 val cursor = if(orderBy ne null) {
454 } // I really know that docs say that it is the same cursor.
456 if(!cursor.hasNext) {
460 val buff = new ListBuffer[A]()
462 while(cursor.hasNext) {
463 buff += deserializer apply cursor.next
469 case Some(sorter) => buff.toList.sortWith(sorter)
470 case None => buff.toList
475 def storeUserState(userState: UserState, collection: DBCollection) = {
476 storeAny[UserState](userState, collection, ResourceEventNames.userID, _.userID, MongoDBStore.jsonSupportToDBObject)
479 def storePolicyEntry(policyEntry: PolicyEntry, collection: DBCollection): Maybe[RecordID] = {
480 Maybe(storeAny[PolicyEntry](policyEntry, collection, PolicyJsonNames.id, _.id, MongoDBStore.jsonSupportToDBObject))
483 def storeAny[A](any: A,
484 collection: DBCollection,
486 idValueProvider: (A) => String,
487 serializer: (A) => DBObject) : RecordID = {
489 val dbObject = serializer apply any
490 val _id = new ObjectId()
491 dbObject.put("_id", _id)
492 val writeResult = collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
493 writeResult.getLastError().throwOnError()
495 RecordID(dbObject.get("_id").toString)
498 // FIXME: consolidate
499 def insertUserState[A <: UserState](obj: A, collection: DBCollection, serializer: A ⇒ DBObject) = {
500 val dbObject = serializer apply obj
501 val objectId = obj._id match {
503 val _id = new ObjectId()
504 dbObject.put("_id", _id)
511 dbObject.put(JsonNames._id, objectId)
513 collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
518 def insertObject[A <: MongoDBEventModel](obj: A, collection: DBCollection, serializer: (A) => DBObject) : Unit = {
519 val dbObject = serializer apply obj
520 val objectId = obj._id match {
522 val _id = new ObjectId()
523 dbObject.put("_id", _id)
530 dbObject.put(JsonNames._id, objectId)
532 collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
535 def jsonSupportToDBObject(jsonSupport: JsonSupport) = {
536 Conversions.jsonSupportToDBObject(jsonSupport)
539 final def isLocalIMEvent(event: IMEventModel) = event match {
540 case _: MongoDBIMEvent ⇒ true
544 final def createIMEventFromJson(json: String) = {
545 MongoDBIMEvent.fromJsonString(json)
548 final def createIMEventFromOther(event: IMEventModel) = {
549 MongoDBIMEvent.fromOther(event, null)
552 final def createIMEventFromJsonBytes(jsonBytes: Array[Byte]) = {
553 MongoDBIMEvent.fromJsonBytes(jsonBytes)