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.computation
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
51 * Methods for converting accounting events to wallet entries.
53 * @author Georgios Gousios <gousiosg@gmail.com>
54 * @author Christos KK Loverdos <loverdos@gmail.com>
56 object TimeslotComputations extends Loggable {
59 * Breaks a reference timeslot (e.g. billing period) according to policies and agreements.
61 * @param referenceTimeslot
62 * @param policyTimeslots
63 * @param agreementTimeslots
67 def splitTimeslotByPoliciesAndAgreements(
68 referenceTimeslot: Timeslot,
69 policyTimeslots: List[Timeslot],
70 agreementTimeslots: List[Timeslot],
71 clogM: Maybe[ContextualLogger] = NoVal
74 // Align policy and agreement validity timeslots to the referenceTimeslot
75 val alignedPolicyTimeslots = referenceTimeslot.align(policyTimeslots)
76 val alignedAgreementTimeslots = referenceTimeslot.align(agreementTimeslots)
78 val result = alignTimeslots(alignedPolicyTimeslots, alignedAgreementTimeslots)
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.
89 def resolveEffectiveUnitPrices(
90 alignedTimeslot: Timeslot,
92 agreement: UserAgreementModel,
93 resourceType: ResourceType,
94 clogOpt: Option[ContextualLogger] = None
95 ): SortedMap[Timeslot, Double] = {
97 val clog = ContextualLogger.fromOther(clogOpt, logger, "resolveEffectiveUnitPrices()")
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)}
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] = {
112 val clog = ContextualLogger.fromOther(clogOpt, logger, "computeInitialChargeslots()")
114 val policyTimeslots = policyByTimeslot.keySet
115 val agreementTimeslots = agreementByTimeslot.keySet
117 def getPolicyWithin(ts: Timeslot): PolicyModel = {
118 policyByTimeslot.find(_._1.contains(ts)).get._2
120 def getAgreementWithin(ts: Timeslot): UserAgreementModel = {
121 agreementByTimeslot.find(_._1.contains(ts)).get._2
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))
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
134 val policy = policyByTimeslot.valuesIterator.next()//getPolicyWithin(alignedTimeslot)
135 // clog.debug("dslPolicy = %s", dslPolicy)
136 val userAgreement = agreementByTimeslot.valuesIterator.next()//getAgreementWithin(alignedTimeslot)
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))
143 // Now, the timeslots must be the same
144 val finegrainedTimeslots = unitPriceByTimeslot.keySet
146 val chargeslots = for (finegrainedTimeslot ← finegrainedTimeslots) yield {
148 finegrainedTimeslot.from.getTime,
149 finegrainedTimeslot.to.getTime,
150 unitPriceByTimeslot(finegrainedTimeslot)
157 val result = allChargeslots.flatten
163 * Given two lists of timeslots, produce a list which contains the
164 * set of timeslot slices, as those are defined by
167 * For example, given the timeslots a and b below, split them as shown.
169 * a = |****************|
176 * result: List(Timeslot(a.from, b.to), Timeslot(b.to, a.to))
178 private[computation] def alignTimeslots(a: List[Timeslot],
179 b: List[Timeslot]): List[Timeslot] = {
181 def safeTail(foo: List[Timeslot]) = foo match {
183 case x :: Nil => List()
184 case x :: rest => rest
187 if(a.isEmpty) return b
188 if(b.isEmpty) return a
190 assert(a.head.from == b.head.from)
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)
199 a.head :: alignTimeslots(safeTail(a), safeTail(b))
203 type PriceMap = immutable.SortedMap[Timeslot, EffectiveUnitPrice]
204 private type PriceList = List[EffectiveUnitPrice]
205 private def emptyMap = immutable.SortedMap[Timeslot,EffectiveUnitPrice]()
208 * Resolves the effective price list for each chunk of the
209 * provided timeslot and returns it as a Map
211 private def resolveEffectiveUnitPricesForTimeslot(
212 alignedTimeslot: Timeslot,
214 agreement: UserAgreementModel,
215 resourceType: ResourceType
218 val role = agreement.role
219 val fullPriceTable = agreement.fullPriceTableRef match {
220 case PolicyDefinedFullPriceTableRef ⇒
221 policy.roleMapping.get(role) match {
222 case Some(fullPriceTable) ⇒
226 throw new AquariumInternalError("Unknown role %s".format(role))
229 case AdHocFullPriceTableRef(fullPriceTable) ⇒
233 val effectivePriceTable = fullPriceTable.perResource.get(resourceType.name) match {
235 throw new AquariumInternalError("Unknown resource type %s".format(role))
237 case Some(effectivePriceTable) ⇒
241 //resolveEffective(alignedTimeslot, effectivePriceTable.priceOverrides)
242 immutable.SortedMap(alignedTimeslot -> effectivePriceTable.priceOverrides.head)
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")
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")
257 private def resolveEffective(alignedTimeslot: Timeslot,p:PriceList): PriceMap = {
258 Console.err.println("\n\nInput timeslot: " + alignedTimeslot + "\n\n")
260 val ret = resolveEffective3(alignedTimeslot,p) //HERE
266 private def resolveEffective3(alignedTimeslot: Timeslot, effectiveUnitPrices: PriceList): PriceMap =
267 effectiveUnitPrices match {
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)
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
283 val ret = satisfiedMap ++ notSatisfiedMap