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 collection.immutable
40 import gr.grnet.aquarium.computation.BillingMonthInfo
41 import gr.grnet.aquarium.converter.StdConverters
42 import gr.grnet.aquarium.logic.accounting.dsl.Timeslot
43 import gr.grnet.aquarium.message.MessageConstants
44 import gr.grnet.aquarium.message.avro.gen.{UserStateMsg, IMEventMsg, ResourceEventMsg, PolicyMsg}
45 import gr.grnet.aquarium.message.avro.{MessageFactory, OrderingHelpers, AvroHelpers}
46 import gr.grnet.aquarium.store._
47 import gr.grnet.aquarium.util._
48 import gr.grnet.aquarium.util.json.JsonSupport
49 import gr.grnet.aquarium.{Aquarium, AquariumException}
50 import org.apache.avro.specific.SpecificRecord
51 import org.bson.types.ObjectId
54 * Mongodb implementation of the various aquarium stores.
56 * @author Christos KK Loverdos <loverdos@gmail.com>
57 * @author Georgios Gousios <gousiosg@gmail.com>
58 * @author Prodromos Gerakios <pgerakio@grnet.gr>
61 val aquarium: Aquarium,
66 extends ResourceEventStore
72 private[store] lazy val resourceEvents = getCollection(MongoDBStore.ResourceEventCollection)
73 private[store] lazy val userStates = getCollection(MongoDBStore.UserStateCollection)
74 private[store] lazy val imEvents = getCollection(MongoDBStore.IMEventCollection)
75 private[store] lazy val policies = getCollection(MongoDBStore.PolicyCollection)
77 private[this] def getCollection(name: String): DBCollection = {
78 val db = mongo.getDB(database)
79 //logger.debug("Authenticating to mongo")
80 if(!db.isAuthenticated && !db.authenticate(username, password.toCharArray)) {
81 throw new AquariumException("Could not authenticate user %s".format(username))
83 db.getCollection(name)
87 def pingResourceEventStore(): Unit = synchronized {
88 MongoDBStore.ping(mongo)
91 def insertResourceEvent(event: ResourceEventMsg) = {
92 val mongoID = new ObjectId()
93 event.setInStoreID(mongoID.toStringMongod)
95 val dbObject = new BasicDBObjectBuilder().
96 add(MongoDBStore.JsonNames._id, mongoID).
97 add(MongoDBStore.JsonNames.payload, AvroHelpers.bytesOfSpecificRecord(event)).
98 add(MongoDBStore.JsonNames.userID, event.getUserID).
99 add(MongoDBStore.JsonNames.occurredMillis, event.getOccurredMillis).
100 add(MongoDBStore.JsonNames.receivedMillis, event.getReceivedMillis).
103 MongoDBStore.insertDBObject(dbObject, resourceEvents)
107 def findResourceEventByID(id: String): Option[ResourceEventMsg] = {
108 val dbObjectOpt = MongoDBStore.findOneByAttribute(resourceEvents, MongoDBStore.JsonNames.id, id)
110 dbObject ← dbObjectOpt
111 payload = dbObject.get(MongoDBStore.JsonNames.payload)
112 msg = AvroHelpers.specificRecordOfBytes(payload.asInstanceOf[Array[Byte]], new ResourceEventMsg)
116 def countOutOfSyncResourceEventsForBillingPeriod(userID: String, startMillis: Long, stopMillis: Long): Long = {
117 val query = new BasicDBObjectBuilder().
118 add(MongoDBStore.JsonNames.userID, userID).
119 // received within the period
120 add(MongoDBStore.JsonNames.receivedMillis, new BasicDBObject("$gte", startMillis)).
121 add(MongoDBStore.JsonNames.receivedMillis, new BasicDBObject("$lte", stopMillis)).
122 // occurred outside the period
124 val dbList = new BasicDBList()
125 dbList.add(0, new BasicDBObject(MongoDBStore.JsonNames.occurredMillis, new BasicDBObject("$lt", startMillis)))
126 dbList.add(1, new BasicDBObject(MongoDBStore.JsonNames.occurredMillis, new BasicDBObject("$gt", stopMillis)))
131 resourceEvents.count(query)
134 def foreachResourceEventOccurredInPeriod(
138 )(f: ResourceEventMsg ⇒ Unit): Unit = {
140 val query = new BasicDBObjectBuilder().
141 add(MongoDBStore.JsonNames.userID, userID).
142 add(MongoDBStore.JsonNames.occurredMillis, new BasicDBObject("$gte", startMillis)).
143 add(MongoDBStore.JsonNames.occurredMillis, new BasicDBObject("$lte", stopMillis)).
146 val sorter = new BasicDBObject(MongoDBStore.JsonNames.occurredMillis, 1)
147 val cursor = resourceEvents.find(query).sort(sorter)
149 withCloseable(cursor) { cursor ⇒
150 while(cursor.hasNext) {
151 val nextDBObject = cursor.next()
152 val payload = nextDBObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
153 val nextEvent = AvroHelpers.specificRecordOfBytes(payload, new ResourceEventMsg)
159 //-ResourceEventStore
162 def findUserStateByUserID(userID: String) = {
163 val dbObjectOpt = MongoDBStore.findOneByAttribute(userStates, MongoDBStore.JsonNames.userID, userID)
165 dbObject <- dbObjectOpt
166 payload = dbObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
167 msg = AvroHelpers.specificRecordOfBytes(payload, new UserStateMsg)
173 def findLatestUserStateForFullMonthBilling(userID: String, bmi: BillingMonthInfo) = {
174 val query = new BasicDBObjectBuilder().
175 add(MongoDBStore.JsonNames.userID, userID).
176 add(MongoDBStore.JsonNames.isFullBillingMonth, true).
177 add(MongoDBStore.JsonNames.billingYear, bmi.year).
178 add(MongoDBStore.JsonNames.billingMonth, bmi.month).
181 // Descending order, so that the latest comes first
182 val sorter = new BasicDBObject(MongoDBStore.JsonNames.occurredMillis, -1)
184 val cursor = userStates.find(query).sort(sorter)
186 withCloseable(cursor) { cursor ⇒
187 MongoDBStore.findNextPayloadRecord(cursor, new UserStateMsg)
192 * Stores a user state.
194 def insertUserState(event: UserStateMsg)= {
195 val mongoID = new ObjectId()
196 event.setInStoreID(mongoID.toStringMongod)
198 val dbObject = new BasicDBObjectBuilder().
199 add(MongoDBStore.JsonNames._id, mongoID).
200 add(MongoDBStore.JsonNames.payload, AvroHelpers.bytesOfSpecificRecord(event)).
201 add(MongoDBStore.JsonNames.userID, event.getUserID).
202 add(MongoDBStore.JsonNames.occurredMillis, event.getOccurredMillis).
203 add(MongoDBStore.JsonNames.isFullBillingMonth, event.getIsFullBillingMonth).
204 add(MongoDBStore.JsonNames.billingYear, event.getBillingYear).
205 add(MongoDBStore.JsonNames.billingMonth, event.getBillingMonth).
206 add(MongoDBStore.JsonNames.billingMonthDay, event.getBillingMonthDay).
209 MongoDBStore.insertDBObject(dbObject, userStates)
215 def pingIMEventStore(): Unit = {
216 MongoDBStore.ping(mongo)
219 def insertIMEvent(event: IMEventMsg) = {
220 val mongoID = new ObjectId()
221 event.setInStoreID(mongoID.toStringMongod)
223 val dbObject = new BasicDBObjectBuilder().
224 add(MongoDBStore.JsonNames._id, mongoID).
225 add(MongoDBStore.JsonNames.payload, AvroHelpers.bytesOfSpecificRecord(event)).
226 add(MongoDBStore.JsonNames.userID, event.getUserID).
227 add(MongoDBStore.JsonNames.eventType, event.getEventType().toLowerCase).
228 add(MongoDBStore.JsonNames.occurredMillis, event.getOccurredMillis).
229 add(MongoDBStore.JsonNames.receivedMillis, event.getReceivedMillis).
232 MongoDBStore.insertDBObject(dbObject, imEvents)
236 def findIMEventByID(id: String) = {
237 val dbObjectOpt = MongoDBStore.findOneByAttribute(imEvents, MongoDBStore.JsonNames.id, id)
239 dbObject ← dbObjectOpt
240 payload = dbObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
241 msg = AvroHelpers.specificRecordOfBytes(payload, new IMEventMsg)
249 * Find the `CREATE` even for the given user. Note that there must be only one such event.
251 def findCreateIMEventByUserID(userID: String) = {
252 val query = new BasicDBObjectBuilder().
253 add(MongoDBStore.JsonNames.userID, userID).
254 add(MongoDBStore.JsonNames.eventType, MessageConstants.IMEventMsg.EventTypes.create).get()
256 // Normally one such event is allowed ...
257 val cursor = imEvents.find(query).sort(new BasicDBObject(MongoDBStore.JsonNames.occurredMillis, 1))
259 val dbObjectOpt = withCloseable(cursor) { cursor ⇒
268 dbObject <- dbObjectOpt
269 payload = dbObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
270 msg = AvroHelpers.specificRecordOfBytes(payload, new IMEventMsg)
277 * Scans events for the given user, sorted by `occurredMillis` in ascending order and runs them through
278 * the given function `f`.
280 * Any exception is propagated to the caller. The underlying DB resources are properly disposed in any case.
282 def foreachIMEventInOccurrenceOrder(userID: String)(f: (IMEventMsg) ⇒ Unit) = {
283 val query = new BasicDBObject(MongoDBStore.JsonNames.userID, userID)
284 val cursor = imEvents.find(query).sort(new BasicDBObject(MongoDBStore.JsonNames.occurredMillis, 1))
286 withCloseable(cursor) { cursor ⇒
287 while(cursor.hasNext) {
288 val dbObject = cursor.next()
289 val payload = dbObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
290 val msg = AvroHelpers.specificRecordOfBytes(payload, new IMEventMsg)
301 def foreachPolicy[U](f: PolicyMsg ⇒ U) {
302 val cursor = policies.find()
303 withCloseable(cursor) { cursor ⇒
304 while(cursor.hasNext) {
305 val dbObject = cursor.next()
306 val payload = dbObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
307 val policy = AvroHelpers.specificRecordOfBytes(payload, new PolicyMsg)
313 def insertPolicy(policy: PolicyMsg): PolicyMsg = {
314 val mongoID = new ObjectId()
315 policy.setInStoreID(mongoID.toStringMongod)
316 val dbObject = new BasicDBObjectBuilder().
317 add(MongoDBStore.JsonNames._id, mongoID).
318 add(MongoDBStore.JsonNames.validFromMillis, policy.getValidFromMillis).
319 add(MongoDBStore.JsonNames.validToMillis, policy.getValidToMillis).
320 add(MongoDBStore.JsonNames.payload, AvroHelpers.bytesOfSpecificRecord(policy)).
323 MongoDBStore.insertDBObject(dbObject, policies)
327 def loadPolicyAt(atMillis: Long): Option[PolicyMsg] = {
329 var _policies = immutable.TreeSet[PolicyMsg]()(OrderingHelpers.DefaultPolicyMsgOrdering)
330 foreachPolicy(_policies += _)
331 _policies.to(MessageFactory.newDummyPolicyMsgAt(atMillis)).lastOption
334 def loadSortedPoliciesWithin(fromMillis: Long, toMillis: Long): immutable.SortedMap[Timeslot, PolicyMsg] = {
336 var _policies = immutable.TreeSet[PolicyMsg]()(OrderingHelpers.DefaultPolicyMsgOrdering)
337 foreachPolicy(_policies += _)
339 immutable.SortedMap(_policies.
340 from(MessageFactory.newDummyPolicyMsgAt(fromMillis)).
341 to(MessageFactory.newDummyPolicyMsgAt(toMillis)).toSeq.
342 map(p ⇒ (Timeslot(p.getValidFromMillis, p.getValidToMillis), p)): _*
348 object MongoDBStore {
349 final val JsonNames = gr.grnet.aquarium.util.json.JsonNames
351 final val ResourceEventCollection = "resevents"
353 final val UserStateCollection = "userstates"
355 final val IMEventCollection = "imevents"
357 final val PolicyCollection = "policies"
359 def firstResultIfExists[A](cursor: DBCursor, f: DBObject ⇒ A): Option[A] = {
360 withCloseable(cursor) { cursor ⇒
362 Some(f(cursor.next()))
369 def ping(mongo: Mongo): Unit = synchronized {
370 // This requires a network roundtrip
374 def findOneByAttribute(
375 collection: DBCollection,
376 attributeName: String,
377 attributeValue: String,
378 sortByOpt: Option[DBObject] = None
379 ): Option[DBObject] = {
380 val query = new BasicDBObject(attributeName, attributeValue)
381 val cursor = sortByOpt match {
382 case None ⇒ collection find query
383 case Some(sortBy) ⇒ collection find query sort sortBy
385 withCloseable(cursor) { cursor ⇒
386 if(cursor.hasNext) Some(cursor.next()) else None
390 def insertDBObject(dbObj: DBObject, collection: DBCollection) {
391 collection.insert(dbObj, WriteConcern.JOURNAL_SAFE)
394 def findNextPayloadRecord[R <: SpecificRecord](cursor: DBCursor, fresh: R): Option[R] = {
396 dbObject <- if(cursor.hasNext) Some(cursor.next()) else None
397 payload = dbObject.get(MongoDBStore.JsonNames.payload).asInstanceOf[Array[Byte]]
398 msg = AvroHelpers.specificRecordOfBytes(payload, fresh)
404 def jsonSupportToDBObject(jsonSupport: JsonSupport) = {
405 StdConverters.AllConverters.convertEx[DBObject](jsonSupport)