Wallets go REST
[aquarium] / src / main / scala / gr / grnet / aquarium / computation / TimeslotComputations.scala
1 /*
2  * Copyright 2011-2012 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
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.
16  *
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.
29  *
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.
34  */
35
36 package gr.grnet.aquarium.computation
37
38 import collection.immutable.SortedMap
39 import com.ckkloverdos.maybe.{NoVal, Maybe}
40 import gr.grnet.aquarium.util.{ContextualLogger, Loggable}
41 import gr.grnet.aquarium.AquariumInternalError
42 import gr.grnet.aquarium.logic.accounting.dsl.Timeslot
43 import gr.grnet.aquarium.policy._
44 import collection.immutable
45 import com.ckkloverdos.maybe.Just
46 import gr.grnet.aquarium.policy.ResourceType
47 import gr.grnet.aquarium.policy.EffectiveUnitPrice
48 import gr.grnet.aquarium.charging.Chargeslot
49
50 /**
51  * Methods for converting accounting events to wallet entries.
52  *
53  * @author Georgios Gousios <gousiosg@gmail.com>
54  * @author Christos KK Loverdos <loverdos@gmail.com>
55  */
56 object TimeslotComputations extends Loggable {
57
58   /**
59    * Breaks a reference timeslot (e.g. billing period) according to policies and agreements.
60    *
61    * @param referenceTimeslot
62    * @param policyTimeslots
63    * @param agreementTimeslots
64    * @return
65    */
66   protected
67   def splitTimeslotByPoliciesAndAgreements(
68       referenceTimeslot: Timeslot,
69       policyTimeslots: List[Timeslot],
70       agreementTimeslots: List[Timeslot],
71       clogM: Maybe[ContextualLogger] = NoVal
72   ): List[Timeslot] = {
73
74     // Align policy and agreement validity timeslots to the referenceTimeslot
75     val alignedPolicyTimeslots = referenceTimeslot.align(policyTimeslots)
76     val alignedAgreementTimeslots = referenceTimeslot.align(agreementTimeslots)
77
78     val result = alignTimeslots(alignedPolicyTimeslots, alignedAgreementTimeslots)
79
80     result
81   }
82
83   /**
84    * Given a reference timeslot, we have to break it up to a series of timeslots where a particular
85    * algorithm and price unit is in effect.
86    *
87    */
88   protected
89   def resolveEffectiveUnitPrices(
90       alignedTimeslot: Timeslot,
91       policy: PolicyModel,
92       agreement: UserAgreementModel,
93       resourceType: ResourceType,
94       clogOpt: Option[ContextualLogger] = None
95   ): SortedMap[Timeslot, Double] = {
96
97     val clog = ContextualLogger.fromOther(clogOpt, logger, "resolveEffectiveUnitPrices()")
98
99     // Note that most of the code is taken from calcChangeChunks()
100     val ret = resolveEffectiveUnitPricesForTimeslot(alignedTimeslot, policy, agreement, resourceType)
101     ret map {case (t,p) => (t,p.unitPrice)}
102   }
103
104   def computeInitialChargeslots(
105       referenceTimeslot: Timeslot,
106       resourceType: ResourceType,
107       policyByTimeslot: SortedMap[Timeslot, PolicyModel],
108       agreementByTimeslot: SortedMap[Timeslot, UserAgreementModel],
109       clogOpt: Option[ContextualLogger] = None
110   ): List[Chargeslot] = {
111
112     val clog = ContextualLogger.fromOther(clogOpt, logger, "computeInitialChargeslots()")
113
114     val policyTimeslots = policyByTimeslot.keySet
115     val agreementTimeslots = agreementByTimeslot.keySet
116
117     def getPolicyWithin(ts: Timeslot): PolicyModel = {
118       policyByTimeslot.find(_._1.contains(ts)).get._2
119     }
120     def getAgreementWithin(ts: Timeslot): UserAgreementModel = {
121       agreementByTimeslot.find(_._1.contains(ts)).get._2
122     }
123
124     // 1. Round ONE: split time according to overlapping policies and agreements.
125     val alignedTimeslots = List(referenceTimeslot) //splitTimeslotByPoliciesAndAgreements(referenceTimeslot, policyTimeslots.toList, agreementTimeslots.toList, Just(clog))
126
127     // 2. Round TWO: Use the aligned timeslots of Round ONE to produce even more
128     //    fine-grained timeslots according to applicable algorithms.
129     //    Then pack the info into charge slots.
130     //    clog.begin("ROUND 2")
131     val allChargeslots = for {
132       alignedTimeslot <- alignedTimeslots
133     } yield {
134       val policy = policyByTimeslot.valuesIterator.next()//getPolicyWithin(alignedTimeslot)
135       //      clog.debug("dslPolicy = %s", dslPolicy)
136       val userAgreement = agreementByTimeslot.valuesIterator.next()//getAgreementWithin(alignedTimeslot)
137
138       // TODO: Factor this out, just like we did with:
139       // TODO:  val alignedTimeslots = splitTimeslotByPoliciesAndAgreements
140       // Note that most of the code is already taken from calcChangeChunks()
141       val unitPriceByTimeslot = resolveEffectiveUnitPrices(alignedTimeslot, policy, userAgreement, resourceType, Some(clog))
142
143       // Now, the timeslots must be the same
144       val finegrainedTimeslots = unitPriceByTimeslot.keySet
145
146       val chargeslots = for (finegrainedTimeslot ← finegrainedTimeslots) yield {
147         Chargeslot(
148           finegrainedTimeslot.from.getTime,
149           finegrainedTimeslot.to.getTime,
150           unitPriceByTimeslot(finegrainedTimeslot)
151         )
152       }
153
154       chargeslots.toList
155     }
156
157     val result = allChargeslots.flatten
158
159     result
160   }
161
162   /**
163    * Given two lists of timeslots, produce a list which contains the
164    * set of timeslot slices, as those are defined by
165    * timeslot overlaps.
166    *
167    * For example, given the timeslots a and b below, split them as shown.
168    *
169    * a = |****************|
170    * ^                ^
171    * a.from            a.to
172    * b = |*********|
173    * ^         ^
174    * b.from     b.to
175    *
176    * result: List(Timeslot(a.from, b.to), Timeslot(b.to, a.to))
177    */
178   private[computation] def alignTimeslots(a: List[Timeslot],
179                                     b: List[Timeslot]): List[Timeslot] = {
180
181     def safeTail(foo: List[Timeslot]) = foo match {
182       case Nil => List()
183       case x :: Nil => List()
184       case x :: rest => rest
185     }
186
187     if(a.isEmpty) return b
188     if(b.isEmpty) return a
189
190     assert(a.head.from == b.head.from)
191
192     if(a.head.endsAfter(b.head)) {
193       val slice = a.head.slice(b.head.to)
194       slice.head :: alignTimeslots(slice.last :: a.tail, safeTail(b))
195     } else if(b.head.endsAfter(a.head)) {
196       val slice = b.head.slice(a.head.to)
197       slice.head :: alignTimeslots(safeTail(a), slice.last :: b.tail)
198     } else {
199       a.head :: alignTimeslots(safeTail(a), safeTail(b))
200     }
201   }
202
203     type PriceMap =  immutable.SortedMap[Timeslot, EffectiveUnitPrice]
204     private type PriceList = List[EffectiveUnitPrice]
205     private def emptyMap = immutable.SortedMap[Timeslot,EffectiveUnitPrice]()
206
207     /**
208      * Resolves the effective price list for each chunk of the
209      * provided timeslot and returns it as a Map
210      */
211     private def resolveEffectiveUnitPricesForTimeslot(
212                                                alignedTimeslot: Timeslot,
213                                                policy: PolicyModel,
214                                                agreement: UserAgreementModel,
215                                                resourceType: ResourceType
216                                                ): PriceMap = {
217
218       val role = agreement.role
219       val fullPriceTable = agreement.fullPriceTableRef match {
220         case PolicyDefinedFullPriceTableRef ⇒
221           policy.roleMapping.get(role) match {
222             case Some(fullPriceTable) ⇒
223               fullPriceTable
224
225             case None ⇒
226               throw new AquariumInternalError("Unknown role %s".format(role))
227           }
228
229         case AdHocFullPriceTableRef(fullPriceTable) ⇒
230           fullPriceTable
231       }
232
233       val effectivePriceTable = fullPriceTable.perResource.get(resourceType.name) match {
234         case None ⇒
235           throw new AquariumInternalError("Unknown resource type %s".format(role))
236
237         case Some(effectivePriceTable) ⇒
238           effectivePriceTable
239       }
240
241       //resolveEffective(alignedTimeslot, effectivePriceTable.priceOverrides)
242       immutable.SortedMap(alignedTimeslot -> effectivePriceTable.priceOverrides.head)
243     }
244
245     private def printPriceList(p: PriceList) : Unit = {
246       Console.err.println("BEGIN PRICE LIST")
247       for { p1 <- p } Console.err.println(p1)
248       Console.err.println("END PRICE LIST")
249     }
250
251     private def printPriceMap(m: PriceMap) = {
252       Console.err.println("BEGIN PRICE MAP")
253       for { (t,p) <- m.toList } Console.err.println("Timeslot " + t + "\t\t" + p)
254       Console.err.println("END PRICE MAP")
255     }
256
257     private def resolveEffective(alignedTimeslot: Timeslot,p:PriceList): PriceMap = {
258       Console.err.println("\n\nInput timeslot: " + alignedTimeslot + "\n\n")
259       printPriceList(p)
260       val ret =  resolveEffective3(alignedTimeslot,p) //HERE
261       printPriceMap(ret)
262       ret
263     }
264
265
266     private def resolveEffective3(alignedTimeslot: Timeslot, effectiveUnitPrices: PriceList): PriceMap =
267       effectiveUnitPrices match {
268         case Nil =>
269           emptyMap
270         case hd::tl =>
271           val (satisfied,notSatisfied) = hd splitTimeslot alignedTimeslot
272           val satisfiedMap = satisfied.foldLeft (emptyMap)  {(map,t) =>
273           //Console.err.println("Adding timeslot" + t +
274           // " for policy " + policy.name)
275             map + ((t,hd))
276           }
277           val notSatisfiedMap = notSatisfied.foldLeft (emptyMap) {(map,t) =>
278             val otherMap = resolveEffective3(t,tl)
279             //Console.err.println("Residual timeslot: " + t)
280             val ret = map ++ otherMap
281             ret
282           }
283           val ret = satisfiedMap ++ notSatisfiedMap
284           ret
285       }
286 }