Timeslot alignment test
authorChristos KK Loverdos <loverdos@gmail.com>
Fri, 9 Mar 2012 15:12:41 +0000 (17:12 +0200)
committerChristos KK Loverdos <loverdos@gmail.com>
Fri, 9 Mar 2012 15:12:41 +0000 (17:12 +0200)
src/main/scala/gr/grnet/aquarium/logic/accounting/Accounting.scala
src/main/scala/gr/grnet/aquarium/user/UserDataSnapshot.scala
src/main/scala/gr/grnet/aquarium/user/UserStateComputations.scala
src/main/scala/gr/grnet/aquarium/user/actor/UserActor.scala
src/test/resources/log4j.properties
src/test/scala/gr/grnet/aquarium/logic/test/TimeslotTest.scala
src/test/scala/gr/grnet/aquarium/user/UserStateComputationsTest.scala

index 7d1a077..b860bdb 100644 (file)
@@ -88,6 +88,7 @@ trait Accounting extends DSLUtils with Loggable {
     val alignedPolicyTimeslots    = referenceTimeslot.align(policyTimeslots)
     val alignedAgreementTimeslots = referenceTimeslot.align(agreementTimeslots)
 
+    clog.debug("referenceTimeslot = %s", referenceTimeslot)
     clog.debugSeq("alignedPolicyTimeslots", alignedPolicyTimeslots, 0)
     clog.debugSeq("alignedAgreementTimeslots", alignedAgreementTimeslots, 0)
 
@@ -186,35 +187,37 @@ trait Accounting extends DSLUtils with Loggable {
           val chargeslots = for {
             finegrainedTimeslot <- finegrainedTimeslots
           } yield {
+            val finegrainedTimeslotMsg = "finegrainedTimeslot = %s".format(finegrainedTimeslot)
+            clog.begin(finegrainedTimeslotMsg)
+
             val dslAlgorithm = algorithmByTimeslot(finegrainedTimeslot) // TODO: is this correct?
+            clog.debug("dslAlgorithm = %s", dslAlgorithm)
             val dslPricelist = pricelistByTimeslot(finegrainedTimeslot) // TODO: is this correct?
+            clog.debug("dslPricelist = %s", dslPricelist)
             val algorithmDefOpt = dslAlgorithm.algorithms.get(dslResource)
+            clog.debug("algorithmDefOpt = %s", algorithmDefOpt)
             val priceUnitOpt = dslPricelist.prices.get(dslResource)
+            clog.debug("priceUnitOpt = %s", priceUnitOpt)
 
-            clog.debug("%s:", finegrainedTimeslot)
-            clog.withIndent {
-              clog.debug("dslAlgorithm = %s", dslAlgorithm)
-              clog.debug("dslPricelist = %s", dslPricelist)
-              clog.debug("algorithmDefOpt = %s", algorithmDefOpt)
-              clog.debug("priceUnitOpt = %s", priceUnitOpt)
-            }
-
-            (algorithmDefOpt, priceUnitOpt) match {
+            val chargeslot = (algorithmDefOpt, priceUnitOpt) match {
               case (None, None) ⇒
                 throw new Exception(
                   "Unknown algorithm and price unit for resource %s during %s".
-                    format(dslResource.name, finegrainedTimeslot))
+                    format(dslResource, finegrainedTimeslot))
               case (None, _) ⇒
                 throw new Exception(
                   "Unknown algorithm for resource %s during %s".
-                    format(dslResource.name, finegrainedTimeslot))
+                    format(dslResource, finegrainedTimeslot))
               case (_, None) ⇒
                 throw new Exception(
                   "Unknown price unit for resource %s during %s".
-                    format(dslResource.name, finegrainedTimeslot))
+                    format(dslResource, finegrainedTimeslot))
               case (Some(algorithmDefinition), Some(priceUnit)) ⇒
                 Chargeslot(finegrainedTimeslot.from.getTime, finegrainedTimeslot.to.getTime, algorithmDefinition, priceUnit)
             }
+
+            clog.end(finegrainedTimeslotMsg)
+            chargeslot
           }
 
           clog.end(alignedTimeslotMsg)
@@ -268,7 +271,7 @@ trait Accounting extends DSLUtils with Loggable {
             // all policies within the interval from previous to current resource event
             clog.debug("Calling policyStore.loadAndSortPoliciesWithin(%s)", referenceTimeslot)
             val relevantPolicies = policyStore.loadAndSortPoliciesWithin(referenceTimeslot.from.getTime, referenceTimeslot.to.getTime, dsl)
-            clog.debugMap("relevantPolicies", relevantPolicies)
+            clog.debugMap("==> relevantPolicies", relevantPolicies, 1)
 
             (referenceTimeslot, relevantPolicies, previousResourceEvent.value)
 
@@ -298,7 +301,7 @@ trait Accounting extends DSLUtils with Loggable {
 
         clog.debug("Calling policyStore.loadValidPolicyEntryAt(%s)", new MutableDateCalc(occurredMillis))
         val relevantPolicyM = policyStore.loadValidPolicyAt(occurredMillis, dsl)
-        clog.debug("relevantPolicyM = %s", relevantPolicyM)
+        clog.debug("  ==> relevantPolicyM = %s", relevantPolicyM)
 
         val relevantPolicies = relevantPolicyM match {
           case Just(relevantPolicy) ⇒
index 00b8259..cbb5ef7 100644 (file)
@@ -36,7 +36,7 @@
 package gr.grnet.aquarium
 package user
 
-import gr.grnet.aquarium.util.{findFromMapAsMaybe, findAndRemoveFromMap}
+import gr.grnet.aquarium.util.{findFromMapAsMaybe, findAndRemoveFromMap, shortClassNameOf}
 import gr.grnet.aquarium.logic.accounting.Policy
 import java.util.Date
 import com.ckkloverdos.maybe.{Failed, NoVal, Maybe, Just}
@@ -111,6 +111,10 @@ case class AgreementSnapshot(agreements: List[Agreement], snapshotTime: Long) ex
         }
       case None => NoVal
     }
+
+  override def toString = {
+    "%s(%s, %s)".format(shortClassNameOf(this), agreements, new MutableDateCalc(snapshotTime).toString)
+  }
 }
 
 /**
index 9953169..8d1f6fd 100644 (file)
@@ -54,10 +54,9 @@ class UserStateComputations extends Loggable {
                            userCreationMillis: Long,
                            isActive: Boolean,
                            credits: Double,
-                           defaultPolicy: DSLPolicy,
+                           roleNames: List[String] = List(),
                            agreementName: String = DSLAgreement.DefaultAgreementName) = {
     val now = userCreationMillis
-    defaultPolicy.findAgreement(agreementName).get // needed only for the side-effect
 
     UserState(
       userId,
@@ -74,7 +73,7 @@ class UserStateComputations extends Loggable {
       ActiveStateSnapshot(isActive, now),
       CreditSnapshot(credits, now),
       AgreementSnapshot(List(Agreement(agreementName, userCreationMillis)), now),
-      RolesSnapshot(Nil, now),
+      RolesSnapshot(roleNames, now),
       OwnedResourcesSnapshot(Nil, now)
     )
   }
@@ -304,12 +303,9 @@ class UserStateComputations extends Loggable {
           val theInstanceId = currentResourceEvent.safeInstanceId
           val theValue = currentResourceEvent.value
 
-          clog.indent()
           clog.debug("")
           clog.debug("Processing %s", currentResourceEvent)
-          clog.debug("+========= %s", rcDebugInfo(currentResourceEvent))
-
-          clog.indent()
+          clog.begin(rcDebugInfo(currentResourceEvent))
 
           if(previousResourceEvents.size > 0) {
             clog.debug("%s previousResourceEvents", previousResourceEvents.size)
@@ -447,9 +443,7 @@ class UserStateComputations extends Loggable {
               clog.error(e, m)
           }
 
-          clog.unindent()
-          clog.debug("-========= %s", rcDebugInfo(currentResourceEvent))
-          clog.unindent()
+          clog.end(rcDebugInfo(currentResourceEvent))
         }
         
 
index be102e3..d27567b 100644 (file)
@@ -104,7 +104,7 @@ class UserActor extends AquariumActor
    * Create an empty state for a user
    */
   def createBlankState = {
-    this._userState = DefaultUserStateComputations.createFirstUserState(this._userId, 0L, true, 0.0, null)
+    this._userState = DefaultUserStateComputations.createFirstUserState(this._userId, 0L, true, 0.0)
   }
 
   /**
@@ -178,8 +178,7 @@ class UserActor extends AquariumActor
           this._userState = DefaultUserStateComputations.createFirstUserState(
             userId,
             event.occurredMillis,
-            true, 0.0, null,
-            DSLAgreement.DefaultAgreementName)
+            true, 0.0)
           saveUserState
           DEBUG("Created and stored %s", this._userState)
         }
index b3bb9fa..aafb266 100644 (file)
@@ -2,7 +2,7 @@ log4j.rootLogger=DEBUG,console
 
 log4j.appender.console=org.apache.log4j.ConsoleAppender
 log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=[%-5p] %d %t - %m%n
+log4j.appender.console.layout.ConversionPattern=%-5p %d %m%n
 log4j.appender.console.threshold=DEBUG
 
 log4j.logger.com.ckkloverdos=INFO
\ No newline at end of file
index 1e70639..2671974 100644 (file)
@@ -40,6 +40,7 @@ import org.junit.Assert._
 import org.junit.{Test}
 import gr.grnet.aquarium.logic.accounting.dsl.Timeslot
 import java.util.Date
+import gr.grnet.aquarium.util.date.MutableDateCalc
 
 /**
  * Tests for the Timeslot class
@@ -127,4 +128,26 @@ class TimeslotTest extends TestMethods {
     assertEquals(Timeslot(new Date(19), new Date(20)), aligned.last)
 
   }
+
+  @Test
+  def testAlign2 = {
+    val t = Timeslot(
+      new MutableDateCalc(2012, 1, 1).goPlusHours(3).toDate,
+      new MutableDateCalc(2012, 1, 2).goPlusHours(4).toDate)
+
+    val dc20110101 = new MutableDateCalc(2011, 1, 1)
+    val dc20111101 = new MutableDateCalc(2011, 11, 1)
+    val polTs = List(Timeslot(dc20110101.toDate, dc20110101.copy.goPlusYears(2).toDate))
+    val agrTs = List(Timeslot(dc20111101.toDate, new Date(Long.MaxValue)))
+
+    val alignedPolTs = t.align(polTs)
+    assertEquals(1, alignedPolTs.size)
+    assertEquals(t.to, alignedPolTs.last.to)
+
+    val alignedAgrTs = t.align(agrTs)
+    assertEquals(1, alignedAgrTs.size)
+    assertEquals(t.to, alignedAgrTs.last.to)
+
+
+  }
 }
\ No newline at end of file
index 99b60a8..87b7563 100644 (file)
@@ -91,8 +91,8 @@ aquariumpolicy:
   @Test
   def testOne: Unit = {
     val clog = ContextualLogger.fromOther(NoVal, logger, "testOne()")
-    val StartOfBillingYearDateCalc = new MutableDateCalc(2012, 1, 1)
-    val UserCreationDateCalc       = new MutableDateCalc(2012, 1, 1).goMinusMonths(2)
+    val StartOfBillingYearDateCalc = new MutableDateCalc(2012,  1, 1)
+    val UserCreationDate           = new MutableDateCalc(2011, 11, 1).toDate
 
     val computations = new UserStateComputations
 
@@ -104,6 +104,7 @@ aquariumpolicy:
     val resourceEventStore = storeProvider.resourceEventStore
     val policyStore = storeProvider.policyStore
 
+    // Store the default policy
     val policyDateCalc        = StartOfBillingYearDateCalc.copy
     val policyOccurredMillis  = policyDateCalc.toMillis
     val policyValidFromMillis = policyDateCalc.copy.goPreviousYear.toMillis
@@ -114,7 +115,7 @@ aquariumpolicy:
     val DefaultResourcesMap = Aquarium.resourcesMap
 
     // A new user is created on 2012-01-15 00:00:00.000
-    val UserCKKL  = Aquarium.newUser("CKKL", UserCreationDateCalc.toDate)
+    val UserCKKL  = Aquarium.newUser("CKKL", UserCreationDate)
 
     // By convention
     // - synnefo is for VMTime and Bandwidth
@@ -154,28 +155,30 @@ aquariumpolicy:
       777)
 
     clog.debug("")
-    clog.debug("=== Events by OccurredMillis ===")
+    clog.begin("Events by OccurredMillis")
     clog.withIndent {
       for(event <- UserCKKL.myResourceEventsByOccurredDate) {
         clog.debug(event.toDebugString(DefaultResourcesMap))
       }
     }
-    clog.debug("=== Events by OccurredMillis ===")
+    clog.end("Events by OccurredMillis")
     clog.debug("")
 
     val billingMonthInfo = BillingMonthInfo.fromDateCalc(StartOfBillingYearDateCalc)
 
     val initialUserState = computations.createFirstUserState(
       userId = UserCKKL.userId,
-      userCreationMillis = UserCreationDateCalc.toMillis,
+      userCreationMillis = UserCreationDate.getTime,
       isActive = true,
       credits = 0.0,
-      defaultPolicy = DefaultPolicy,
+      roleNames = List("user"),
       agreementName = DSLAgreement.DefaultAgreementName
     )
 
     val currentUserState = initialUserState
 
+    // Policy: from 2012-01-01 to Infinity
+
     val userStateM = computations.doFullMonthlyBilling(
       UserCKKL.userId,
       billingMonthInfo,