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.logic.accounting
38 import algorithm.CostPolicyAlgorithmCompiler
40 import collection.immutable.SortedMap
41 import com.ckkloverdos.maybe.{NoVal, Maybe, Just}
42 import gr.grnet.aquarium.util.{ContextualLogger, Loggable}
43 import gr.grnet.aquarium.store.PolicyStore
44 import gr.grnet.aquarium.util.date.MutableDateCalc
45 import gr.grnet.aquarium.{AquariumInternalError, AquariumException}
46 import gr.grnet.aquarium.event.model.resource.ResourceEventModel
49 * Methods for converting accounting events to wallet entries.
51 * @author Georgios Gousios <gousiosg@gmail.com>
52 * @author Christos KK Loverdos <loverdos@gmail.com>
54 trait Accounting extends Loggable {
55 // TODO: favour composition over inheritance until we decide what to do with DSLUtils (and Accounting).
56 protected val dslUtils = new DSLUtils {}
58 * Breaks a reference timeslot (e.g. billing period) according to policies and agreements.
60 * @param referenceTimeslot
61 * @param policyTimeslots
62 * @param agreementTimeslots
66 def splitTimeslotByPoliciesAndAgreements(referenceTimeslot: Timeslot,
67 policyTimeslots: List[Timeslot],
68 agreementTimeslots: List[Timeslot],
69 clogM: Maybe[ContextualLogger] = NoVal): List[Timeslot] = {
71 // val clog = ContextualLogger.fromOther(clogM, logger, "splitTimeslotByPoliciesAndAgreements()")
74 // Align policy and agreement validity timeslots to the referenceTimeslot
75 val alignedPolicyTimeslots = referenceTimeslot.align(policyTimeslots)
76 val alignedAgreementTimeslots = referenceTimeslot.align(agreementTimeslots)
78 // clog.debug("referenceTimeslot = %s", referenceTimeslot)
79 // clog.debugSeq("alignedPolicyTimeslots", alignedPolicyTimeslots, 0)
80 // clog.debugSeq("alignedAgreementTimeslots", alignedAgreementTimeslots, 0)
82 val result = alignTimeslots(alignedPolicyTimeslots, alignedAgreementTimeslots)
83 // clog.debugSeq("result", result, 1)
89 * Given a reference timeslot, we have to break it up to a series of timeslots where a particular
90 * algorithm and price unit is in effect.
94 def resolveEffectiveAlgorithmsAndPriceLists(alignedTimeslot: Timeslot,
95 agreement: DSLAgreement,
96 clogOpt: Option[ContextualLogger] = None):
97 (Map[Timeslot, DSLAlgorithm], Map[Timeslot, DSLPriceList]) = {
99 val clog = ContextualLogger.fromOther(clogOpt, logger, "resolveEffectiveAlgorithmsAndPriceLists()")
101 // Note that most of the code is taken from calcChangeChunks()
102 val alg = dslUtils.resolveEffectiveAlgorithmsForTimeslot(alignedTimeslot, agreement)
103 val pri = dslUtils.resolveEffectivePricelistsForTimeslot(alignedTimeslot, agreement)
104 val chargeChunks = splitChargeChunks(alg, pri)
105 val algorithmByTimeslot = chargeChunks._1
106 val pricelistByTimeslot = chargeChunks._2
108 assert(algorithmByTimeslot.size == pricelistByTimeslot.size)
110 (algorithmByTimeslot, pricelistByTimeslot)
114 def computeInitialChargeslots(referenceTimeslot: Timeslot,
115 dslResource: DSLResource,
116 policiesByTimeslot: Map[Timeslot, DSLPolicy],
117 agreementNamesByTimeslot: Map[Timeslot, String],
118 clogOpt: Option[ContextualLogger] = None): List[Chargeslot] = {
120 val clog = ContextualLogger.fromOther(clogOpt, logger, "computeInitialChargeslots()")
123 val policyTimeslots = policiesByTimeslot.keySet
124 val agreementTimeslots = agreementNamesByTimeslot.keySet
126 // clog.debugMap("policiesByTimeslot", policiesByTimeslot, 1)
127 // clog.debugMap("agreementNamesByTimeslot", agreementNamesByTimeslot, 1)
129 def getPolicy(ts: Timeslot): DSLPolicy = {
130 policiesByTimeslot.find(_._1.contains(ts)).get._2
132 def getAgreementName(ts: Timeslot): String = {
133 agreementNamesByTimeslot.find(_._1.contains(ts)).get._2
136 // 1. Round ONE: split time according to overlapping policies and agreements.
137 // clog.begin("ROUND 1")
138 val alignedTimeslots = splitTimeslotByPoliciesAndAgreements(referenceTimeslot, policyTimeslots.toList, agreementTimeslots.toList, Just(clog))
139 // clog.debugSeq("alignedTimeslots", alignedTimeslots, 1)
140 // clog.end("ROUND 1")
142 // 2. Round TWO: Use the aligned timeslots of Round ONE to produce even more
143 // fine-grained timeslots according to applicable algorithms.
144 // Then pack the info into charge slots.
145 // clog.begin("ROUND 2")
146 val allChargeslots = for {
147 alignedTimeslot <- alignedTimeslots
149 // val alignedTimeslotMsg = "alignedTimeslot = %s".format(alignedTimeslot)
150 // clog.begin(alignedTimeslotMsg)
152 val dslPolicy = getPolicy(alignedTimeslot)
153 // clog.debug("dslPolicy = %s", dslPolicy)
154 val agreementName = getAgreementName(alignedTimeslot)
155 // clog.debug("agreementName = %s", agreementName)
156 val agreementOpt = dslPolicy.findAgreement(agreementName)
157 // clog.debug("agreementOpt = %s", agreementOpt)
161 val errMsg = "Unknown agreement %s during %s".format(agreementName, alignedTimeslot)
162 clog.error("%s", errMsg)
163 throw new AquariumException(errMsg)
165 case Some(agreement) ⇒
166 // TODO: Factor this out, just like we did with:
167 // TODO: val alignedTimeslots = splitTimeslotByPoliciesAndAgreements
168 // Note that most of the code is already taken from calcChangeChunks()
169 val r = resolveEffectiveAlgorithmsAndPriceLists(alignedTimeslot, agreement, Some(clog))
170 val algorithmByTimeslot: Map[Timeslot, DSLAlgorithm] = r._1
171 val pricelistByTimeslot: Map[Timeslot, DSLPriceList] = r._2
173 // Now, the timeslots must be the same
174 val finegrainedTimeslots = algorithmByTimeslot.keySet
176 val chargeslots = for {
177 finegrainedTimeslot <- finegrainedTimeslots
179 // val finegrainedTimeslotMsg = "finegrainedTimeslot = %s".format(finegrainedTimeslot)
180 // clog.begin(finegrainedTimeslotMsg)
182 val dslAlgorithm = algorithmByTimeslot(finegrainedTimeslot) // TODO: is this correct?
183 // clog.debug("dslAlgorithm = %s", dslAlgorithm)
184 // clog.debugMap("dslAlgorithm.algorithms", dslAlgorithm.algorithms, 1)
185 val dslPricelist = pricelistByTimeslot(finegrainedTimeslot) // TODO: is this correct?
186 // clog.debug("dslPricelist = %s", dslPricelist)
187 // clog.debug("dslResource = %s", dslResource)
188 val algorithmDefOpt = dslAlgorithm.algorithms.get(dslResource)
189 // clog.debug("algorithmDefOpt = %s", algorithmDefOpt)
190 val priceUnitOpt = dslPricelist.prices.get(dslResource)
191 // clog.debug("priceUnitOpt = %s", priceUnitOpt)
193 val chargeslot = (algorithmDefOpt, priceUnitOpt) match {
195 throw new AquariumException(
196 "Unknown algorithm and price unit for resource %s during %s".
197 format(dslResource, finegrainedTimeslot))
199 throw new AquariumException(
200 "Unknown algorithm for resource %s during %s".
201 format(dslResource, finegrainedTimeslot))
203 throw new AquariumException(
204 "Unknown price unit for resource %s during %s".
205 format(dslResource, finegrainedTimeslot))
206 case (Some(algorithmDefinition), Some(priceUnit)) ⇒
207 Chargeslot(finegrainedTimeslot.from.getTime, finegrainedTimeslot.to.getTime, algorithmDefinition, priceUnit)
210 // clog.end(finegrainedTimeslotMsg)
214 // clog.end(alignedTimeslotMsg)
218 // clog.end("ROUND 2")
221 val result = allChargeslots.flatten
222 // clog.debugSeq("result", allChargeslots, 1)
228 * Compute the charge slots generated by a particular resource event.
231 def computeFullChargeslots(previousResourceEventOpt: Option[ResourceEventModel],
232 currentResourceEvent: ResourceEventModel,
234 oldTotalAmount: Double,
235 newTotalAmount: Double,
236 dslResource: DSLResource,
237 defaultResourceMap: DSLResourcesMap,
238 agreementNamesByTimeslot: SortedMap[Timeslot, String],
239 algorithmCompiler: CostPolicyAlgorithmCompiler,
240 policyStore: PolicyStore,
241 clogOpt: Option[ContextualLogger] = None): (Timeslot, List[Chargeslot]) = {
243 val clog = ContextualLogger.fromOther(clogOpt, logger, "computeFullChargeslots()")
246 val occurredDate = currentResourceEvent.occurredDate
247 val occurredMillis = currentResourceEvent.occurredMillis
248 val costPolicy = dslResource.costPolicy
251 val (referenceTimeslot, relevantPolicies, previousValue) = costPolicy.needsPreviousEventForCreditAndAmountCalculation match {
252 // We need a previous event
254 previousResourceEventOpt match {
255 // We have a previous event
256 case Some(previousResourceEvent) ⇒
257 // clog.debug("Have previous event")
258 // clog.debug("previousValue = %s", previousResourceEvent.value)
260 val referenceTimeslot = Timeslot(previousResourceEvent.occurredDate, occurredDate)
261 // clog.debug("referenceTimeslot = %s".format(referenceTimeslot))
263 // all policies within the interval from previous to current resource event
264 // clog.debug("Calling policyStore.loadAndSortPoliciesWithin(%s)", referenceTimeslot)
265 val relevantPolicies = policyStore.loadAndSortPoliciesWithin(referenceTimeslot.from.getTime, referenceTimeslot.to.getTime, dsl)
266 // clog.debugMap("==> relevantPolicies", relevantPolicies, 0)
268 (referenceTimeslot, relevantPolicies, previousResourceEvent.value)
270 // We do not have a previous event
272 throw new AquariumException(
273 "Unable to charge. No previous event given for %s".
274 format(currentResourceEvent.toDebugString()))
277 // We do not need a previous event
279 // ... so we cannot compute timedelta from a previous event, there is just one chargeslot
280 // referring to (almost) an instant in time
281 // clog.debug("DO NOT have previous event")
282 val previousValue = costPolicy.getResourceInstanceUndefinedAmount
283 // clog.debug("previousValue = costPolicy.getResourceInstanceUndefinedAmount = %s", previousValue)
285 val referenceTimeslot = Timeslot(new MutableDateCalc(occurredDate).goPreviousMilli.toDate, occurredDate)
286 // clog.debug("referenceTimeslot = %s".format(referenceTimeslot))
288 // clog.debug("Calling policyStore.loadValidPolicyEntryAt(%s)", new MutableDateCalc(occurredMillis))
289 val relevantPolicyOpt = policyStore.loadValidPolicyAt(occurredMillis, dsl)
290 // clog.debug(" ==> relevantPolicyM = %s", relevantPolicyM)
292 val relevantPolicies = relevantPolicyOpt match {
293 case Some(relevantPolicy) ⇒
294 Map(referenceTimeslot -> relevantPolicy)
297 throw new AquariumInternalError("No relevant policy found for %s".format(referenceTimeslot))
300 (referenceTimeslot, relevantPolicies, previousValue)
303 val initialChargeslots = computeInitialChargeslots(
307 agreementNamesByTimeslot,
311 val fullChargeslots = initialChargeslots.map {
312 case chargeslot @ Chargeslot(startMillis, stopMillis, algorithmDefinition, unitPrice, _) ⇒
313 val execAlgorithm = algorithmCompiler.compile(algorithmDefinition)
314 val valueMap = costPolicy.makeValueMap(
318 stopMillis - startMillis,
320 currentResourceEvent.value,
324 // clog.debug("execAlgorithm = %s", execAlgorithm)
325 clog.debugMap("valueMap", valueMap, 1)
328 val credits = execAlgorithm.apply(valueMap)
329 chargeslot.copyWithCredits(credits)
332 val result = referenceTimeslot -> fullChargeslots
338 * Align charge timeslots between algorithms and pricelists. As algorithm
339 * and pricelists can have different effectivity periods, this method
340 * examines them and splits them as necessary.
342 private[logic] def splitChargeChunks(alg: SortedMap[Timeslot, DSLAlgorithm],
343 price: SortedMap[Timeslot, DSLPriceList]) :
344 (Map[Timeslot, DSLAlgorithm], Map[Timeslot, DSLPriceList]) = {
346 val zipped = alg.keySet.zip(price.keySet)
348 zipped.find(p => !p._1.equals(p._2)) match {
349 case None => (alg, price)
351 val algTimeslot = x._1
352 val priTimeslot = x._2
354 assert(algTimeslot.from == priTimeslot.from)
356 if (algTimeslot.endsAfter(priTimeslot)) {
357 val slices = algTimeslot.slice(priTimeslot.to)
358 val algo = alg.get(algTimeslot).get
359 val newalg = alg - algTimeslot ++ Map(slices.apply(0) -> algo) ++ Map(slices.apply(1) -> algo)
360 splitChargeChunks(newalg, price)
363 val slices = priTimeslot.slice(priTimeslot.to)
364 val pl = price.get(priTimeslot).get
365 val newPrice = price - priTimeslot ++ Map(slices.apply(0) -> pl) ++ Map(slices.apply(1) -> pl)
366 splitChargeChunks(alg, newPrice)
372 * Given two lists of timeslots, produce a list which contains the
373 * set of timeslot slices, as those are defined by
376 * For example, given the timeslots a and b below, split them as shown.
378 * a = |****************|
385 * result: List(Timeslot(a.from, b.to), Timeslot(b.to, a.to))
387 private[logic] def alignTimeslots(a: List[Timeslot],
388 b: List[Timeslot]): List[Timeslot] = {
390 def safeTail(foo: List[Timeslot]) = foo match {
392 case x :: Nil => List()
393 case x :: rest => rest
396 if (a.isEmpty) return b
397 if (b.isEmpty) return a
399 assert (a.head.from == b.head.from)
401 if (a.head.endsAfter(b.head)) {
402 val slice = a.head.slice(b.head.to)
403 slice.head :: alignTimeslots(slice.last :: a.tail, safeTail(b))
404 } else if (b.head.endsAfter(a.head)) {
405 val slice = b.head.slice(a.head.to)
406 slice.head :: alignTimeslots(safeTail(a), slice.last :: b.tail)
408 a.head :: alignTimeslots(safeTail(a), safeTail(b))