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.computation.state.UserState
51 import gr.grnet.aquarium.event.model.ExternalEventModel
52 import gr.grnet.aquarium.computation.BillingMonthInfo
53 import gr.grnet.aquarium.policy.PolicyModel
54 import gr.grnet.aquarium.{Aquarium, AquariumException}
55 import collection.immutable.SortedMap
56 import gr.grnet.aquarium.logic.accounting.dsl.Timeslot
57 import collection.immutable
59 import gr.grnet.aquarium.charging.state.UserStateModel
62 * Mongodb implementation of the various aquarium stores.
64 * @author Christos KK Loverdos <loverdos@gmail.com>
65 * @author Georgios Gousios <gousiosg@gmail.com>
66 * @author Prodromos Gerakios <pgerakio@grnet.gr>
69 val aquarium: Aquarium,
74 extends ResourceEventStore
80 override type IMEvent = MongoDBIMEvent
81 override type ResourceEvent = MongoDBResourceEvent
82 override type Policy = MongoDBPolicy
83 override type UserState = MongoDBUserState
85 private[store] lazy val resourceEvents = getCollection(MongoDBStore.RESOURCE_EVENTS_COLLECTION)
86 private[store] lazy val userStates = getCollection(MongoDBStore.USER_STATES_COLLECTION)
87 private[store] lazy val imEvents = getCollection(MongoDBStore.IM_EVENTS_COLLECTION)
88 private[store] lazy val policies = getCollection(MongoDBStore.POLICY_COLLECTION)
90 private[this] def getCollection(name: String): DBCollection = {
91 val db = mongo.getDB(database)
92 //logger.debug("Authenticating to mongo")
93 if(!db.isAuthenticated && !db.authenticate(username, password.toCharArray)) {
94 throw new AquariumException("Could not authenticate user %s".format(username))
96 db.getCollection(name)
100 def createResourceEventFromOther(event: ResourceEventModel): ResourceEvent = {
101 MongoDBResourceEvent.fromOther(event, null)
104 def pingResourceEventStore(): Unit = synchronized {
105 MongoDBStore.ping(mongo)
108 def insertResourceEvent(event: ResourceEventModel) = {
109 val localEvent = MongoDBResourceEvent.fromOther(event, new ObjectId().toStringMongod)
110 MongoDBStore.insertObject(localEvent, resourceEvents, MongoDBStore.jsonSupportToDBObject)
114 def findResourceEventByID(id: String): Option[ResourceEvent] = {
115 MongoDBStore.findBy(ResourceEventNames.id, id, resourceEvents, MongoDBResourceEvent.fromDBObject)
118 def findResourceEventsByUserID(userId: String)
119 (sortWith: Option[(ResourceEvent, ResourceEvent) => Boolean]): List[ResourceEvent] = {
120 val query = new BasicDBObject(ResourceEventNames.userID, userId)
122 MongoDBStore.runQuery(query, resourceEvents)(MongoDBResourceEvent.fromDBObject)(sortWith)
125 def countOutOfSyncResourceEventsForBillingPeriod(userID: String, startMillis: Long, stopMillis: Long): Long = {
126 val query = new BasicDBObjectBuilder().
127 add(ResourceEventModel.Names.userID, userID).
128 // received within the period
129 add(ResourceEventModel.Names.receivedMillis, new BasicDBObject("$gte", startMillis)).
130 add(ResourceEventModel.Names.receivedMillis, new BasicDBObject("$lte", stopMillis)).
131 // occurred outside the period
133 val dbList = new BasicDBList()
134 dbList.add(0, new BasicDBObject(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$lt", startMillis)))
135 dbList.add(1, new BasicDBObject(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$gt", stopMillis)))
140 resourceEvents.count(query)
143 def foreachResourceEventOccurredInPeriod(
147 )(f: ResourceEvent ⇒ Unit): Unit = {
149 val query = new BasicDBObjectBuilder().
150 add(ResourceEventModel.Names.userID, userID).
151 add(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$gte", startMillis)).
152 add(ResourceEventModel.Names.occurredMillis, new BasicDBObject("$lte", stopMillis)).
155 val sorter = new BasicDBObject(ResourceEventModel.Names.occurredMillis, 1)
156 val cursor = resourceEvents.find(query).sort(sorter)
158 withCloseable(cursor) { cursor ⇒
159 while(cursor.hasNext) {
160 val nextDBObject = cursor.next()
161 val nextEvent = MongoDBResourceEvent.fromDBObject(nextDBObject)
167 //-ResourceEventStore
170 def insertUserState(userState: UserState) = {
171 MongoDBStore.insertObject(
172 userState.copy(_id = new ObjectId().toString),
174 MongoDBStore.jsonSupportToDBObject
178 def findUserStateByUserID(userID: String): Option[UserState] = {
179 val query = new BasicDBObject(UserStateModel.Names.userID, userID)
180 val cursor = userStates find query
182 MongoDBStore.firstResultIfExists(cursor, MongoDBStore.dbObjectToUserState)
185 def findLatestUserStateForFullMonthBilling(userID: String, bmi: BillingMonthInfo): Option[UserState] = {
186 val query = new BasicDBObjectBuilder().
187 add(UserState.JsonNames.userID, userID).
188 add(UserState.JsonNames.isFullBillingMonthState, true).
189 add(UserState.JsonNames.theFullBillingMonth_year, bmi.year).
190 add(UserState.JsonNames.theFullBillingMonth_month, bmi.month).
193 // Descending order, so that the latest comes first
194 val sorter = new BasicDBObject(UserState.JsonNames.occurredMillis, -1)
196 val cursor = userStates.find(query).sort(sorter)
198 MongoDBStore.firstResultIfExists(cursor, MongoDBStore.dbObjectToUserState)
201 def createUserStateFromOther(userState: UserStateModel) = {
202 MongoDBUserState.fromOther(userState, new ObjectId().toStringMongod)
206 * Stores a user state.
208 def insertUserState(userState: UserStateModel): UserState = {
209 val localUserState = createUserStateFromOther(userState)
210 MongoDBStore.insertObject(localUserState, userStates, MongoDBStore.jsonSupportToDBObject)
215 def createIMEventFromJson(json: String) = {
216 MongoDBStore.createIMEventFromJson(json)
219 def createIMEventFromOther(event: IMEventModel) = {
220 MongoDBStore.createIMEventFromOther(event)
223 def pingIMEventStore(): Unit = {
224 MongoDBStore.ping(mongo)
227 def insertIMEvent(event: IMEventModel): IMEvent = {
228 val localEvent = MongoDBIMEvent.fromOther(event, new ObjectId().toStringMongod)
229 MongoDBStore.insertObject(localEvent, imEvents, MongoDBStore.jsonSupportToDBObject)
233 def findIMEventByID(id: String): Option[IMEvent] = {
234 MongoDBStore.findBy(IMEventNames.id, id, imEvents, MongoDBIMEvent.fromDBObject)
239 * Find the `CREATE` even for the given user. Note that there must be only one such event.
241 def findCreateIMEventByUserID(userID: String): Option[IMEvent] = {
242 val query = new BasicDBObjectBuilder().
243 add(IMEventNames.userID, userID).
244 add(IMEventNames.eventType, IMEventModel.EventTypeNames.create).get()
246 // Normally one such event is allowed ...
247 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
249 MongoDBStore.firstResultIfExists(cursor, MongoDBIMEvent.fromDBObject)
252 def findLatestIMEventByUserID(userID: String): Option[IMEvent] = {
253 val query = new BasicDBObject(IMEventNames.userID, userID)
254 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, -1))
256 MongoDBStore.firstResultIfExists(cursor, MongoDBIMEvent.fromDBObject)
260 * Scans events for the given user, sorted by `occurredMillis` in ascending order and runs them through
261 * the given function `f`.
263 * Any exception is propagated to the caller. The underlying DB resources are properly disposed in any case.
265 def foreachIMEventInOccurrenceOrder(userID: String)(f: (IMEvent) => Unit) = {
266 val query = new BasicDBObject(IMEventNames.userID, userID)
267 val cursor = imEvents.find(query).sort(new BasicDBObject(IMEventNames.occurredMillis, 1))
269 withCloseable(cursor) { cursor ⇒
270 while(cursor.hasNext) {
271 val model = MongoDBIMEvent.fromDBObject(cursor.next())
282 * Store an accounting policy.
284 def insertPolicy(policy: PolicyModel): Policy = {
285 val dbPolicy = MongoDBPolicy.fromOther(policy, new ObjectId().toStringMongod)
286 MongoDBStore.insertObject(dbPolicy, policies, MongoDBStore.jsonSupportToDBObject)
289 private def emptyMap = immutable.SortedMap[Timeslot,Policy]()
291 def loadValidPolicyAt(atMillis: Long): Option[Policy] = {
292 /*var d = new Date(atMillis)
293 /* sort in reverse order and return the first that includes this date*/
294 policies.sortWith({(x,y)=> y.validFrom < x.validFrom}).collectFirst({
295 case t if(t.validityTimespan.toTimeslot.includes(d)) => t
297 throw new UnsupportedOperationException
300 def loadAndSortPoliciesWithin(fromMillis: Long, toMillis: Long): SortedMap[Timeslot, Policy] = {
302 throw new UnsupportedOperationException
307 object MongoDBStore {
309 final val _id = "_id"
313 * Collection holding the [[gr.grnet.aquarium.event.model.resource.ResourceEventModel]]s.
315 * Resource events are coming from all systems handling billable resources.
317 final val RESOURCE_EVENTS_COLLECTION = "resevents"
320 * Collection holding the snapshots of [[gr.grnet.aquarium.computation.state.UserState]].
322 * [[gr.grnet.aquarium.computation.state.UserState]] is held internally within
323 * [[gr.grnet.aquarium.actor.service.user .UserActor]]s.
325 final val USER_STATES_COLLECTION = "userstates"
328 * Collection holding [[gr.grnet.aquarium.event.model.im.IMEventModel]]s.
330 * User events are coming from the IM module (external).
332 final val IM_EVENTS_COLLECTION = "imevents"
335 * Collection holding [[gr.grnet.aquarium.policy.PolicyModel]]s.
337 final val POLICY_COLLECTION = "policies"
339 def dbObjectToUserState(dbObj: DBObject): MongoDBUserState = {
340 MongoDBUserState.fromJSONString(JSON.serialize(dbObj))
343 def firstResultIfExists[A](cursor: DBCursor, f: DBObject ⇒ A): Option[A] = {
344 withCloseable(cursor) { cursor ⇒
346 Some(f(cursor.next()))
353 def ping(mongo: Mongo): Unit = synchronized {
354 // This requires a network roundtrip
358 def findBy[A >: Null <: AnyRef](name: String,
360 collection: DBCollection,
361 deserializer: (DBObject) => A) : Option[A] = {
362 val query = new BasicDBObject(name, value)
363 val cursor = collection find query
365 withCloseable(cursor) { cursor ⇒
367 Some(deserializer apply cursor.next)
373 def runQuery[A <: ExternalEventModel](query: DBObject, collection: DBCollection, orderBy: DBObject = null)
374 (deserializer: (DBObject) => A)
375 (sortWith: Option[(A, A) => Boolean]): List[A] = {
376 val cursor0 = collection find query
377 val cursor = if(orderBy ne null) {
381 } // I really know that docs say that it is the same cursor.
383 if(!cursor.hasNext) {
387 val buff = new ListBuffer[A]()
389 while(cursor.hasNext) {
390 buff += deserializer apply cursor.next
396 case Some(sorter) => buff.toList.sortWith(sorter)
397 case None => buff.toList
402 def storeUserState(userState: UserState, collection: DBCollection) = {
403 storeAny[UserState](userState, collection, ResourceEventNames.userID, _.userID, MongoDBStore.jsonSupportToDBObject)
406 def storeAny[A](any: A,
407 collection: DBCollection,
409 idValueProvider: (A) => String,
410 serializer: (A) => DBObject) : RecordID = {
412 val dbObject = serializer apply any
413 val _id = new ObjectId()
414 dbObject.put("_id", _id)
415 val writeResult = collection.insert(dbObject, WriteConcern.JOURNAL_SAFE)
416 writeResult.getLastError().throwOnError()
418 RecordID(dbObject.get("_id").toString)
421 def insertObject[A <: AnyRef](obj: A, collection: DBCollection, serializer: A ⇒ DBObject) : A = {
422 collection.insert(serializer apply obj, WriteConcern.JOURNAL_SAFE)
426 def jsonSupportToDBObject(jsonSupport: JsonSupport) = {
427 StdConverters.AllConverters.convertEx[DBObject](jsonSupport)
430 final def isLocalIMEvent(event: IMEventModel) = event match {
431 case _: MongoDBIMEvent ⇒ true
435 final def createIMEventFromJson(json: String) = {
436 MongoDBIMEvent.fromJsonString(json)
439 final def createIMEventFromOther(event: IMEventModel) = {
440 MongoDBIMEvent.fromOther(event, new ObjectId().toStringMongod)
443 final def createIMEventFromJsonBytes(jsonBytes: Array[Byte]) = {
444 MongoDBIMEvent.fromJsonBytes(jsonBytes)