allocation_test.go 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759
  1. package kubecost
  2. import (
  3. "fmt"
  4. "math"
  5. "reflect"
  6. "testing"
  7. "time"
  8. "github.com/opencost/opencost/pkg/util"
  9. "github.com/opencost/opencost/pkg/util/json"
  10. )
  11. func TestAllocation_Add(t *testing.T) {
  12. var nilAlloc *Allocation
  13. zeroAlloc := &Allocation{}
  14. // nil + nil == nil
  15. nilNilSum, err := nilAlloc.Add(nilAlloc)
  16. if err != nil {
  17. t.Fatalf("Allocation.Add unexpected error: %s", err)
  18. }
  19. if nilNilSum != nil {
  20. t.Fatalf("Allocation.Add failed; exp: nil; act: %s", nilNilSum)
  21. }
  22. // nil + zero == zero
  23. nilZeroSum, err := nilAlloc.Add(zeroAlloc)
  24. if err != nil {
  25. t.Fatalf("Allocation.Add unexpected error: %s", err)
  26. }
  27. if nilZeroSum == nil || nilZeroSum.TotalCost() != 0.0 {
  28. t.Fatalf("Allocation.Add failed; exp: 0.0; act: %s", nilZeroSum)
  29. }
  30. cpuPrice := 0.02
  31. gpuPrice := 2.00
  32. ramPrice := 0.01
  33. pvPrice := 0.00005
  34. gib := 1024.0 * 1024.0 * 1024.0
  35. s1 := time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC)
  36. e1 := time.Date(2021, time.January, 1, 12, 0, 0, 0, time.UTC)
  37. hrs1 := e1.Sub(s1).Hours()
  38. a1 := &Allocation{
  39. Start: s1,
  40. End: e1,
  41. Properties: &AllocationProperties{},
  42. CPUCoreHours: 2.0 * hrs1,
  43. CPUCoreRequestAverage: 2.0,
  44. CPUCoreUsageAverage: 1.0,
  45. CPUCost: 2.0 * hrs1 * cpuPrice,
  46. CPUCostAdjustment: 3.0,
  47. GPUHours: 1.0 * hrs1,
  48. GPUCost: 1.0 * hrs1 * gpuPrice,
  49. GPUCostAdjustment: 2.0,
  50. PVs: PVAllocations{
  51. disk: {
  52. ByteHours: 100.0 * gib * hrs1,
  53. Cost: 100.0 * hrs1 * pvPrice,
  54. },
  55. },
  56. PVCostAdjustment: 4.0,
  57. RAMByteHours: 8.0 * gib * hrs1,
  58. RAMBytesRequestAverage: 8.0 * gib,
  59. RAMBytesUsageAverage: 4.0 * gib,
  60. RAMCost: 8.0 * hrs1 * ramPrice,
  61. RAMCostAdjustment: 1.0,
  62. SharedCost: 2.00,
  63. ExternalCost: 1.00,
  64. RawAllocationOnly: &RawAllocationOnlyData{},
  65. }
  66. a1b := a1.Clone()
  67. s2 := time.Date(2021, time.January, 1, 6, 0, 0, 0, time.UTC)
  68. e2 := time.Date(2021, time.January, 1, 24, 0, 0, 0, time.UTC)
  69. hrs2 := e1.Sub(s1).Hours()
  70. a2 := &Allocation{
  71. Start: s2,
  72. End: e2,
  73. Properties: &AllocationProperties{},
  74. CPUCoreHours: 1.0 * hrs2,
  75. CPUCoreRequestAverage: 1.0,
  76. CPUCoreUsageAverage: 1.0,
  77. CPUCost: 1.0 * hrs2 * cpuPrice,
  78. GPUHours: 0.0,
  79. GPUCost: 0.0,
  80. RAMByteHours: 8.0 * gib * hrs2,
  81. RAMBytesRequestAverage: 0.0,
  82. RAMBytesUsageAverage: 8.0 * gib,
  83. RAMCost: 8.0 * hrs2 * ramPrice,
  84. NetworkCost: 0.01,
  85. LoadBalancerCost: 0.05,
  86. SharedCost: 0.00,
  87. ExternalCost: 1.00,
  88. RawAllocationOnly: &RawAllocationOnlyData{},
  89. }
  90. a2b := a2.Clone()
  91. act, err := a1.Add(a2)
  92. if err != nil {
  93. t.Fatalf("Allocation.Add: unexpected error: %s", err)
  94. }
  95. // Neither Allocation should be mutated
  96. if !a1.Equal(a1b) {
  97. t.Fatalf("Allocation.Add: a1 illegally mutated")
  98. }
  99. if !a2.Equal(a2b) {
  100. t.Fatalf("Allocation.Add: a1 illegally mutated")
  101. }
  102. // Costs should be cumulative
  103. if !util.IsApproximately(a1.TotalCost()+a2.TotalCost(), act.TotalCost()) {
  104. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.TotalCost()+a2.TotalCost(), act.TotalCost())
  105. }
  106. if !util.IsApproximately(a1.CPUCost+a2.CPUCost, act.CPUCost) {
  107. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.CPUCost+a2.CPUCost, act.CPUCost)
  108. }
  109. if !util.IsApproximately(a1.CPUCostAdjustment+a2.CPUCostAdjustment, act.CPUCostAdjustment) {
  110. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.CPUCostAdjustment+a2.CPUCostAdjustment, act.CPUCostAdjustment)
  111. }
  112. if !util.IsApproximately(a1.GPUCost+a2.GPUCost, act.GPUCost) {
  113. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.GPUCost+a2.GPUCost, act.GPUCost)
  114. }
  115. if !util.IsApproximately(a1.GPUCostAdjustment+a2.GPUCostAdjustment, act.GPUCostAdjustment) {
  116. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.GPUCostAdjustment+a2.GPUCostAdjustment, act.GPUCostAdjustment)
  117. }
  118. if !util.IsApproximately(a1.RAMCost+a2.RAMCost, act.RAMCost) {
  119. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.RAMCost+a2.RAMCost, act.RAMCost)
  120. }
  121. if !util.IsApproximately(a1.RAMCostAdjustment+a2.RAMCostAdjustment, act.RAMCostAdjustment) {
  122. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.RAMCostAdjustment+a2.RAMCostAdjustment, act.RAMCostAdjustment)
  123. }
  124. if !util.IsApproximately(a1.PVCost()+a2.PVCost(), act.PVCost()) {
  125. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.PVCost()+a2.PVCost(), act.PVCost())
  126. }
  127. if !util.IsApproximately(a1.NetworkCost+a2.NetworkCost, act.NetworkCost) {
  128. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.NetworkCost+a2.NetworkCost, act.NetworkCost)
  129. }
  130. if !util.IsApproximately(a1.LoadBalancerCost+a2.LoadBalancerCost, act.LoadBalancerCost) {
  131. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.LoadBalancerCost+a2.LoadBalancerCost, act.LoadBalancerCost)
  132. }
  133. if !util.IsApproximately(a1.SharedCost+a2.SharedCost, act.SharedCost) {
  134. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.SharedCost+a2.SharedCost, act.SharedCost)
  135. }
  136. if !util.IsApproximately(a1.ExternalCost+a2.ExternalCost, act.ExternalCost) {
  137. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.ExternalCost+a2.ExternalCost, act.ExternalCost)
  138. }
  139. // ResourceHours should be cumulative
  140. if !util.IsApproximately(a1.CPUCoreHours+a2.CPUCoreHours, act.CPUCoreHours) {
  141. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.CPUCoreHours+a2.CPUCoreHours, act.CPUCoreHours)
  142. }
  143. if !util.IsApproximately(a1.RAMByteHours+a2.RAMByteHours, act.RAMByteHours) {
  144. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.RAMByteHours+a2.RAMByteHours, act.RAMByteHours)
  145. }
  146. if !util.IsApproximately(a1.PVByteHours()+a2.PVByteHours(), act.PVByteHours()) {
  147. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.PVByteHours()+a2.PVByteHours(), act.PVByteHours())
  148. }
  149. // Minutes should be the duration between min(starts) and max(ends)
  150. if !act.Start.Equal(a1.Start) || !act.End.Equal(a2.End) {
  151. t.Fatalf("Allocation.Add: expected %s; actual %s", NewWindow(&a1.Start, &a2.End), NewWindow(&act.Start, &act.End))
  152. }
  153. if act.Minutes() != 1440.0 {
  154. t.Fatalf("Allocation.Add: expected %f; actual %f", 1440.0, act.Minutes())
  155. }
  156. // Requests and Usage should be averaged correctly
  157. // CPU requests = (2.0*12.0 + 1.0*18.0)/(24.0) = 1.75
  158. // CPU usage = (1.0*12.0 + 1.0*18.0)/(24.0) = 1.25
  159. // RAM requests = (8.0*12.0 + 0.0*18.0)/(24.0) = 4.00
  160. // RAM usage = (4.0*12.0 + 8.0*18.0)/(24.0) = 8.00
  161. if !util.IsApproximately(1.75, act.CPUCoreRequestAverage) {
  162. t.Fatalf("Allocation.Add: expected %f; actual %f", 1.75, act.CPUCoreRequestAverage)
  163. }
  164. if !util.IsApproximately(1.25, act.CPUCoreUsageAverage) {
  165. t.Fatalf("Allocation.Add: expected %f; actual %f", 1.25, act.CPUCoreUsageAverage)
  166. }
  167. if !util.IsApproximately(4.00*gib, act.RAMBytesRequestAverage) {
  168. t.Fatalf("Allocation.Add: expected %f; actual %f", 4.00*gib, act.RAMBytesRequestAverage)
  169. }
  170. if !util.IsApproximately(8.00*gib, act.RAMBytesUsageAverage) {
  171. t.Fatalf("Allocation.Add: expected %f; actual %f", 8.00*gib, act.RAMBytesUsageAverage)
  172. }
  173. // Efficiency should be computed accurately from new request/usage
  174. // CPU efficiency = 1.25/1.75 = 0.7142857
  175. // RAM efficiency = 8.00/4.00 = 2.0000000
  176. // Total efficiency = (0.7142857*0.72 + 2.0*1.92)/(2.64) = 1.6493506
  177. if !util.IsApproximately(0.7142857, act.CPUEfficiency()) {
  178. t.Fatalf("Allocation.Add: expected %f; actual %f", 0.7142857, act.CPUEfficiency())
  179. }
  180. if !util.IsApproximately(2.0000000, act.RAMEfficiency()) {
  181. t.Fatalf("Allocation.Add: expected %f; actual %f", 2.0000000, act.RAMEfficiency())
  182. }
  183. if !util.IsApproximately(1.279690, act.TotalEfficiency()) {
  184. t.Fatalf("Allocation.Add: expected %f; actual %f", 1.279690, act.TotalEfficiency())
  185. }
  186. if act.RawAllocationOnly != nil {
  187. t.Errorf("Allocation.Add: Raw only data must be nil after an add")
  188. }
  189. }
  190. func TestAllocation_Share(t *testing.T) {
  191. cpuPrice := 0.02
  192. gpuPrice := 2.00
  193. ramPrice := 0.01
  194. pvPrice := 0.00005
  195. gib := 1024.0 * 1024.0 * 1024.0
  196. s1 := time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC)
  197. e1 := time.Date(2021, time.January, 1, 12, 0, 0, 0, time.UTC)
  198. hrs1 := e1.Sub(s1).Hours()
  199. a1 := &Allocation{
  200. Start: s1,
  201. End: e1,
  202. Properties: &AllocationProperties{},
  203. CPUCoreHours: 2.0 * hrs1,
  204. CPUCoreRequestAverage: 2.0,
  205. CPUCoreUsageAverage: 1.0,
  206. CPUCost: 2.0 * hrs1 * cpuPrice,
  207. CPUCostAdjustment: 3.0,
  208. GPUHours: 1.0 * hrs1,
  209. GPUCost: 1.0 * hrs1 * gpuPrice,
  210. GPUCostAdjustment: 2.0,
  211. PVs: PVAllocations{
  212. disk: {
  213. ByteHours: 100.0 * gib * hrs1,
  214. Cost: 100.0 * hrs1 * pvPrice,
  215. },
  216. },
  217. PVCostAdjustment: 4.0,
  218. RAMByteHours: 8.0 * gib * hrs1,
  219. RAMBytesRequestAverage: 8.0 * gib,
  220. RAMBytesUsageAverage: 4.0 * gib,
  221. RAMCost: 8.0 * hrs1 * ramPrice,
  222. RAMCostAdjustment: 1.0,
  223. SharedCost: 2.00,
  224. ExternalCost: 1.00,
  225. }
  226. a1b := a1.Clone()
  227. s2 := time.Date(2021, time.January, 1, 6, 0, 0, 0, time.UTC)
  228. e2 := time.Date(2021, time.January, 1, 24, 0, 0, 0, time.UTC)
  229. hrs2 := e1.Sub(s1).Hours()
  230. a2 := &Allocation{
  231. Start: s2,
  232. End: e2,
  233. Properties: &AllocationProperties{},
  234. CPUCoreHours: 1.0 * hrs2,
  235. CPUCoreRequestAverage: 1.0,
  236. CPUCoreUsageAverage: 1.0,
  237. CPUCost: 1.0 * hrs2 * cpuPrice,
  238. GPUHours: 0.0,
  239. GPUCost: 0.0,
  240. RAMByteHours: 8.0 * gib * hrs2,
  241. RAMBytesRequestAverage: 0.0,
  242. RAMBytesUsageAverage: 8.0 * gib,
  243. RAMCost: 8.0 * hrs2 * ramPrice,
  244. NetworkCost: 0.01,
  245. LoadBalancerCost: 0.05,
  246. SharedCost: 0.00,
  247. ExternalCost: 1.00,
  248. }
  249. a2b := a2.Clone()
  250. act, err := a1.Share(a2)
  251. if err != nil {
  252. t.Fatalf("Allocation.Share: unexpected error: %s", err)
  253. }
  254. // Neither Allocation should be mutated
  255. if !a1.Equal(a1b) {
  256. t.Fatalf("Allocation.Share: a1 illegally mutated")
  257. }
  258. if !a2.Equal(a2b) {
  259. t.Fatalf("Allocation.Share: a1 illegally mutated")
  260. }
  261. // SharedCost and TotalCost should reflect increase by a2.TotalCost
  262. if !util.IsApproximately(a1.TotalCost()+a2.TotalCost(), act.TotalCost()) {
  263. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.TotalCost()+a2.TotalCost(), act.TotalCost())
  264. }
  265. if !util.IsApproximately(a1.SharedCost+a2.TotalCost(), act.SharedCost) {
  266. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.SharedCost+a2.TotalCost(), act.SharedCost)
  267. }
  268. // Costs should match before (expect TotalCost and SharedCost)
  269. if !util.IsApproximately(a1.CPUTotalCost(), act.CPUTotalCost()) {
  270. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUTotalCost(), act.CPUTotalCost())
  271. }
  272. if !util.IsApproximately(a1.GPUTotalCost(), act.GPUTotalCost()) {
  273. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.GPUTotalCost(), act.GPUTotalCost())
  274. }
  275. if !util.IsApproximately(a1.RAMTotalCost(), act.RAMTotalCost()) {
  276. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMTotalCost(), act.RAMTotalCost())
  277. }
  278. if !util.IsApproximately(a1.PVTotalCost(), act.PVTotalCost()) {
  279. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.PVTotalCost(), act.PVTotalCost())
  280. }
  281. if !util.IsApproximately(a1.NetworkCost, act.NetworkCost) {
  282. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.NetworkCost, act.NetworkCost)
  283. }
  284. if !util.IsApproximately(a1.LoadBalancerCost, act.LoadBalancerCost) {
  285. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.LoadBalancerCost, act.LoadBalancerCost)
  286. }
  287. if !util.IsApproximately(a1.ExternalCost, act.ExternalCost) {
  288. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.ExternalCost, act.ExternalCost)
  289. }
  290. // ResourceHours should match before
  291. if !util.IsApproximately(a1.CPUCoreHours, act.CPUCoreHours) {
  292. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUCoreHours, act.CPUCoreHours)
  293. }
  294. if !util.IsApproximately(a1.RAMByteHours, act.RAMByteHours) {
  295. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMByteHours, act.RAMByteHours)
  296. }
  297. if !util.IsApproximately(a1.PVByteHours(), act.PVByteHours()) {
  298. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.PVByteHours(), act.PVByteHours())
  299. }
  300. // Minutes should match before
  301. if !act.Start.Equal(a1.Start) || !act.End.Equal(a1.End) {
  302. t.Fatalf("Allocation.Share: expected %s; actual %s", NewWindow(&a1.Start, &a1.End), NewWindow(&act.Start, &act.End))
  303. }
  304. if act.Minutes() != a1.Minutes() {
  305. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.Minutes(), act.Minutes())
  306. }
  307. // Requests and Usage should match before
  308. if !util.IsApproximately(a1.CPUCoreRequestAverage, act.CPUCoreRequestAverage) {
  309. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUCoreRequestAverage, act.CPUCoreRequestAverage)
  310. }
  311. if !util.IsApproximately(a1.CPUCoreUsageAverage, act.CPUCoreUsageAverage) {
  312. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUCoreUsageAverage, act.CPUCoreUsageAverage)
  313. }
  314. if !util.IsApproximately(a1.RAMBytesRequestAverage, act.RAMBytesRequestAverage) {
  315. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMBytesRequestAverage, act.RAMBytesRequestAverage)
  316. }
  317. if !util.IsApproximately(a1.RAMBytesUsageAverage, act.RAMBytesUsageAverage) {
  318. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMBytesUsageAverage, act.RAMBytesUsageAverage)
  319. }
  320. // Efficiency should match before
  321. if !util.IsApproximately(a1.CPUEfficiency(), act.CPUEfficiency()) {
  322. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUEfficiency(), act.CPUEfficiency())
  323. }
  324. if !util.IsApproximately(a1.RAMEfficiency(), act.RAMEfficiency()) {
  325. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMEfficiency(), act.RAMEfficiency())
  326. }
  327. if !util.IsApproximately(a1.TotalEfficiency(), act.TotalEfficiency()) {
  328. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.TotalEfficiency(), act.TotalEfficiency())
  329. }
  330. }
  331. func TestAllocation_AddDifferentController(t *testing.T) {
  332. a1 := &Allocation{
  333. Properties: &AllocationProperties{
  334. Container: "container",
  335. Pod: "pod",
  336. Namespace: "ns",
  337. Cluster: "cluster",
  338. Controller: "controller 1",
  339. },
  340. }
  341. a2 := a1.Clone()
  342. a2.Properties.Controller = "controller 2"
  343. result, err := a1.Add(a2)
  344. if err != nil {
  345. t.Fatalf("Allocation.Add: unexpected error: %s", err)
  346. }
  347. if result.Properties.Controller == "" {
  348. t.Errorf("Adding allocations whose properties only differ in controller name should not result in an empty string controller name.")
  349. }
  350. }
  351. func TestAllocationSet_generateKey(t *testing.T) {
  352. var alloc *Allocation
  353. var key string
  354. props := []string{
  355. AllocationClusterProp,
  356. }
  357. key = alloc.generateKey(props, nil)
  358. if key != "" {
  359. t.Fatalf("generateKey: expected \"\"; actual \"%s\"", key)
  360. }
  361. alloc = &Allocation{}
  362. alloc.Properties = &AllocationProperties{
  363. Cluster: "cluster1",
  364. Labels: map[string]string{
  365. "app": "app1",
  366. "env": "env1",
  367. },
  368. }
  369. key = alloc.generateKey(props, nil)
  370. if key != "cluster1" {
  371. t.Fatalf("generateKey: expected \"cluster1\"; actual \"%s\"", key)
  372. }
  373. props = []string{
  374. AllocationClusterProp,
  375. AllocationNamespaceProp,
  376. "label:app",
  377. }
  378. key = alloc.generateKey(props, nil)
  379. if key != "cluster1//app1" {
  380. t.Fatalf("generateKey: expected \"cluster1//app1\"; actual \"%s\"", key)
  381. }
  382. alloc.Properties = &AllocationProperties{
  383. Cluster: "cluster1",
  384. Namespace: "namespace1",
  385. Labels: map[string]string{
  386. "app": "app1",
  387. "env": "env1",
  388. },
  389. }
  390. key = alloc.generateKey(props, nil)
  391. if key != "cluster1/namespace1/app1" {
  392. t.Fatalf("generateKey: expected \"cluster1/namespace1/app1\"; actual \"%s\"", key)
  393. }
  394. props = []string{
  395. AllocationDepartmentProp,
  396. AllocationEnvironmentProp,
  397. AllocationOwnerProp,
  398. AllocationProductProp,
  399. AllocationTeamProp,
  400. }
  401. labelConfig := NewLabelConfig()
  402. alloc.Properties = &AllocationProperties{
  403. Cluster: "cluster1",
  404. Namespace: "namespace1",
  405. Labels: map[string]string{
  406. labelConfig.DepartmentLabel: "dept1",
  407. labelConfig.EnvironmentLabel: "envt1",
  408. labelConfig.OwnerLabel: "ownr1",
  409. labelConfig.ProductLabel: "prod1",
  410. labelConfig.TeamLabel: "team1",
  411. },
  412. }
  413. key = alloc.generateKey(props, nil)
  414. if key != "dept1/envt1/ownr1/prod1/team1" {
  415. t.Fatalf("generateKey: expected \"dept1/envt1/ownr1/prod1/team1\"; actual \"%s\"", key)
  416. }
  417. // Ensure that labels with illegal Prometheus characters in LabelConfig
  418. // still match their sanitized values. Ensure also that multiple comma-
  419. // separated values work.
  420. labelConfig.DepartmentLabel = "prom/illegal-department"
  421. labelConfig.EnvironmentLabel = " env "
  422. labelConfig.OwnerLabel = "$owner%"
  423. labelConfig.ProductLabel = "app.kubernetes.io/app"
  424. labelConfig.TeamLabel = "team,app.kubernetes.io/team,k8s-team"
  425. alloc.Properties = &AllocationProperties{
  426. Cluster: "cluster1",
  427. Namespace: "namespace1",
  428. Labels: map[string]string{
  429. "prom_illegal_department": "dept1",
  430. "env": "envt1",
  431. "_owner_": "ownr1",
  432. "team": "team1",
  433. "app_kubernetes_io_app": "prod1",
  434. "app_kubernetes_io_team": "team2",
  435. },
  436. }
  437. props = []string{
  438. AllocationDepartmentProp,
  439. AllocationEnvironmentProp,
  440. AllocationOwnerProp,
  441. AllocationProductProp,
  442. AllocationTeamProp,
  443. }
  444. key = alloc.generateKey(props, labelConfig)
  445. if key != "dept1/envt1/ownr1/prod1/team1/team2/__unallocated__" {
  446. t.Fatalf("generateKey: expected \"dept1/envt1/ownr1/prod1/team1/team2/__unallocated__\"; actual \"%s\"", key)
  447. }
  448. }
  449. func TestNewAllocationSet(t *testing.T) {
  450. // TODO niko/etl
  451. }
  452. func assertAllocationSetTotals(t *testing.T, as *AllocationSet, msg string, err error, length int, totalCost float64) {
  453. if err != nil {
  454. t.Fatalf("AllocationSet.AggregateBy[%s]: unexpected error: %s", msg, err)
  455. }
  456. if as.Length() != length {
  457. t.Fatalf("AllocationSet.AggregateBy[%s]: expected set of length %d, actual %d", msg, length, as.Length())
  458. }
  459. if math.Round(as.TotalCost()*100) != math.Round(totalCost*100) {
  460. t.Fatalf("AllocationSet.AggregateBy[%s]: expected total cost %.2f, actual %.2f", msg, totalCost, as.TotalCost())
  461. }
  462. }
  463. func assertParcResults(t *testing.T, as *AllocationSet, msg string, exps map[string]ProportionalAssetResourceCosts) {
  464. for allocKey, a := range as.Allocations {
  465. for key, actualParc := range a.ProportionalAssetResourceCosts {
  466. expectedParcs := exps[allocKey]
  467. if !reflect.DeepEqual(expectedParcs[key], actualParc) {
  468. t.Fatalf("actual PARC %v did not match expected PARC %v", actualParc, expectedParcs[key])
  469. }
  470. }
  471. }
  472. }
  473. func assertAllocationTotals(t *testing.T, as *AllocationSet, msg string, exps map[string]float64) {
  474. for _, a := range as.Allocations {
  475. if exp, ok := exps[a.Name]; ok {
  476. if math.Round(a.TotalCost()*100) != math.Round(exp*100) {
  477. t.Fatalf("AllocationSet.AggregateBy[%s]: expected total cost %f, actual %f", msg, exp, a.TotalCost())
  478. }
  479. } else {
  480. t.Fatalf("AllocationSet.AggregateBy[%s]: unexpected allocation: %s", msg, a.Name)
  481. }
  482. }
  483. }
  484. func assertAllocationWindow(t *testing.T, as *AllocationSet, msg string, expStart, expEnd time.Time, expMinutes float64) {
  485. for _, a := range as.Allocations {
  486. if !a.Start.Equal(expStart) {
  487. t.Fatalf("AllocationSet.AggregateBy[%s]: expected start %s, actual %s", msg, expStart, a.Start)
  488. }
  489. if !a.End.Equal(expEnd) {
  490. t.Fatalf("AllocationSet.AggregateBy[%s]: expected end %s, actual %s", msg, expEnd, a.End)
  491. }
  492. if a.Minutes() != expMinutes {
  493. t.Fatalf("AllocationSet.AggregateBy[%s]: expected minutes %f, actual %f", msg, expMinutes, a.Minutes())
  494. }
  495. }
  496. }
  497. func printAllocationSet(msg string, as *AllocationSet) {
  498. fmt.Printf("--- %s ---\n", msg)
  499. for _, a := range as.Allocations {
  500. fmt.Printf(" > %s\n", a)
  501. }
  502. }
  503. func TestAllocationSet_AggregateBy(t *testing.T) {
  504. // Test AggregateBy against the following workload topology, which is
  505. // generated by GenerateMockAllocationSet:
  506. // | Hierarchy | Cost | CPU | RAM | GPU | PV | Net | LB |
  507. // +----------------------------------------+------+------+------+------+------+------+------+
  508. // cluster1:
  509. // idle: 20.00 5.00 15.00 0.00 0.00 0.00 0.00
  510. // namespace1:
  511. // pod1:
  512. // container1: [app1, env1] 16.00 1.00 11.00 1.00 1.00 1.00 1.00
  513. // pod-abc: (deployment1)
  514. // container2: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  515. // pod-def: (deployment1)
  516. // container3: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  517. // namespace2:
  518. // pod-ghi: (deployment2)
  519. // container4: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  520. // container5: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  521. // pod-jkl: (daemonset1)
  522. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  523. // +-----------------------------------------+------+------+------+------+------+------+------+
  524. // cluster1 subtotal 66.00 11.00 31.00 6.00 6.00 6.00 6.00
  525. // +-----------------------------------------+------+------+------+------+------+------+------+
  526. // cluster2:
  527. // idle: 10.00 5.00 5.00 0.00 0.00 0.00 0.00
  528. // namespace2:
  529. // pod-mno: (deployment2)
  530. // container4: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  531. // container5: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  532. // pod-pqr: (daemonset1)
  533. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  534. // namespace3:
  535. // pod-stu: (deployment3)
  536. // container7: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  537. // pod-vwx: (statefulset1)
  538. // container8: an[team2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  539. // container9: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  540. // +----------------------------------------+------+------+------+------+------+------+------+
  541. // cluster2 subtotal 46.00 11.00 11.00 6.00 6.00 6.00 6.00
  542. // +----------------------------------------+------+------+------+------+------+------+------+
  543. // total 112.00 22.00 42.00 12.00 12.00 12.00 12.00
  544. // +----------------------------------------+------+------+------+------+------+------+------+
  545. // Scenarios to test:
  546. // 1 Single-aggregation
  547. // 1a AggregationProperties=(Cluster)
  548. // 1b AggregationProperties=(Namespace)
  549. // 1c AggregationProperties=(Pod)
  550. // 1d AggregationProperties=(Container)
  551. // 1e AggregationProperties=(ControllerKind)
  552. // 1f AggregationProperties=(Controller)
  553. // 1g AggregationProperties=(Service)
  554. // 1h AggregationProperties=(Label:app)
  555. // 2 Multi-aggregation
  556. // 2a AggregationProperties=(Cluster, Namespace)
  557. // 2b AggregationProperties=(Namespace, Label:app)
  558. // 2c AggregationProperties=(Cluster, Namespace, Pod, Container)
  559. // 2d AggregationProperties=(Label:app, Label:environment)
  560. // 3 Share idle
  561. // 3a AggregationProperties=(Namespace) ShareIdle=ShareWeighted
  562. // 3b AggregationProperties=(Namespace) ShareIdle=ShareEven (TODO niko/etl)
  563. // 4 Share resources
  564. // 4a Share namespace ShareEven
  565. // 4b Share cluster ShareWeighted
  566. // 4c Share label ShareEven
  567. // 4d Share overhead ShareWeighted
  568. // 5 Filters
  569. // 5a Filter by cluster with separate idle
  570. // 5b Filter by cluster with shared idle
  571. // TODO niko/idle more filter tests
  572. // 6 Combinations and options
  573. // 6a SplitIdle
  574. // 6b Share idle with filters
  575. // 6c Share resources with filters
  576. // 6d Share idle and share resources
  577. // 6e IdleByNode
  578. // 7 Edge cases and errors
  579. // 7a Empty AggregationProperties
  580. // 7b Filter all
  581. // 7c Share all
  582. // 7d Share and filter the same allocations
  583. // Definitions and set-up:
  584. var as *AllocationSet
  585. var err error
  586. endYesterday := time.Now().UTC().Truncate(day)
  587. startYesterday := endYesterday.Add(-day)
  588. numClusters := 2
  589. numNamespaces := 3
  590. numPods := 9
  591. numContainers := 9
  592. numControllerKinds := 3
  593. numControllers := 5
  594. numServices := 1
  595. numLabelApps := 2
  596. // By default, idle is reported as a single, merged allocation
  597. numIdle := 1
  598. // There will only ever be one __unallocated__
  599. numUnallocated := 1
  600. // There are two clusters, so each gets an idle entry when they are split
  601. numSplitIdleCluster := 2
  602. // There are two clusters, so each gets an idle entry when they are split
  603. numSplitIdleNode := 4
  604. activeTotalCost := 82.0
  605. idleTotalCost := 30.0
  606. sharedOverheadHourlyCost := 7.0
  607. // Match Functions
  608. isNamespace3 := func(a *Allocation) bool {
  609. ns := a.Properties.Namespace
  610. return ns == "namespace3"
  611. }
  612. isApp1 := func(a *Allocation) bool {
  613. ls := a.Properties.Labels
  614. if app, ok := ls["app"]; ok && app == "app1" {
  615. return true
  616. }
  617. return false
  618. }
  619. // Filters
  620. isNamespace := func(matchNamespace string) func(*Allocation) bool {
  621. return func(a *Allocation) bool {
  622. namespace := a.Properties.Namespace
  623. return namespace == matchNamespace
  624. }
  625. }
  626. end := time.Now().UTC().Truncate(day)
  627. start := end.Add(-day)
  628. // Tests:
  629. cases := map[string]struct {
  630. start time.Time
  631. aggBy []string
  632. aggOpts *AllocationAggregationOptions
  633. numResults int
  634. totalCost float64
  635. results map[string]float64
  636. windowStart time.Time
  637. windowEnd time.Time
  638. expMinutes float64
  639. expectedParcResults map[string]ProportionalAssetResourceCosts
  640. }{
  641. // 1 Single-aggregation
  642. // 1a AggregationProperties=(Cluster)
  643. "1a": {
  644. start: start,
  645. aggBy: []string{AllocationClusterProp},
  646. aggOpts: nil,
  647. numResults: numClusters + numIdle,
  648. totalCost: activeTotalCost + idleTotalCost,
  649. results: map[string]float64{
  650. "cluster1": 46.00,
  651. "cluster2": 36.00,
  652. IdleSuffix: 30.00,
  653. },
  654. windowStart: startYesterday,
  655. windowEnd: endYesterday,
  656. expMinutes: 1440.0,
  657. },
  658. // 1b AggregationProperties=(Namespace)
  659. "1b": {
  660. start: start,
  661. aggBy: []string{AllocationNamespaceProp},
  662. aggOpts: nil,
  663. numResults: numNamespaces + numIdle,
  664. totalCost: activeTotalCost + idleTotalCost,
  665. results: map[string]float64{
  666. "namespace1": 28.00,
  667. "namespace2": 36.00,
  668. "namespace3": 18.00,
  669. IdleSuffix: 30.00,
  670. },
  671. windowStart: startYesterday,
  672. windowEnd: endYesterday,
  673. expMinutes: 1440.0,
  674. },
  675. // 1c AggregationProperties=(Pod)
  676. "1c": {
  677. start: start,
  678. aggBy: []string{AllocationPodProp},
  679. aggOpts: nil,
  680. numResults: numPods + numIdle,
  681. totalCost: activeTotalCost + idleTotalCost,
  682. results: map[string]float64{
  683. "pod-jkl": 6.00,
  684. "pod-stu": 6.00,
  685. "pod-abc": 6.00,
  686. "pod-pqr": 6.00,
  687. "pod-def": 6.00,
  688. "pod-vwx": 12.00,
  689. "pod1": 16.00,
  690. "pod-mno": 12.00,
  691. "pod-ghi": 12.00,
  692. IdleSuffix: 30.00,
  693. },
  694. windowStart: startYesterday,
  695. windowEnd: endYesterday,
  696. expMinutes: 1440.0,
  697. },
  698. // 1d AggregationProperties=(Container)
  699. "1d": {
  700. start: start,
  701. aggBy: []string{AllocationContainerProp},
  702. aggOpts: nil,
  703. numResults: numContainers + numIdle,
  704. totalCost: activeTotalCost + idleTotalCost,
  705. results: map[string]float64{
  706. "container2": 6.00,
  707. "container9": 6.00,
  708. "container6": 12.00,
  709. "container3": 6.00,
  710. "container4": 12.00,
  711. "container7": 6.00,
  712. "container8": 6.00,
  713. "container5": 12.00,
  714. "container1": 16.00,
  715. IdleSuffix: 30.00,
  716. },
  717. windowStart: startYesterday,
  718. windowEnd: endYesterday,
  719. expMinutes: 1440.0,
  720. },
  721. // 1e AggregationProperties=(ControllerKind)
  722. "1e": {
  723. start: start,
  724. aggBy: []string{AllocationControllerKindProp},
  725. aggOpts: nil,
  726. numResults: numControllerKinds + numIdle + numUnallocated,
  727. totalCost: activeTotalCost + idleTotalCost,
  728. results: map[string]float64{
  729. "daemonset": 12.00,
  730. "deployment": 42.00,
  731. "statefulset": 12.00,
  732. IdleSuffix: 30.00,
  733. UnallocatedSuffix: 16.00,
  734. },
  735. windowStart: startYesterday,
  736. windowEnd: endYesterday,
  737. expMinutes: 1440.0,
  738. },
  739. // 1f AggregationProperties=(Controller)
  740. "1f": {
  741. start: start,
  742. aggBy: []string{AllocationControllerProp},
  743. aggOpts: nil,
  744. numResults: numControllers + numIdle + numUnallocated,
  745. totalCost: activeTotalCost + idleTotalCost,
  746. results: map[string]float64{
  747. "deployment:deployment2": 24.00,
  748. "daemonset:daemonset1": 12.00,
  749. "deployment:deployment3": 6.00,
  750. "statefulset:statefulset1": 12.00,
  751. "deployment:deployment1": 12.00,
  752. IdleSuffix: 30.00,
  753. UnallocatedSuffix: 16.00,
  754. },
  755. windowStart: startYesterday,
  756. windowEnd: endYesterday,
  757. expMinutes: 1440.0,
  758. },
  759. // 1g AggregationProperties=(Service)
  760. "1g": {
  761. start: start,
  762. aggBy: []string{AllocationServiceProp},
  763. aggOpts: nil,
  764. numResults: numServices + numIdle + numUnallocated,
  765. totalCost: activeTotalCost + idleTotalCost,
  766. results: map[string]float64{
  767. "service1": 12.00,
  768. IdleSuffix: 30.00,
  769. UnallocatedSuffix: 70.00,
  770. },
  771. windowStart: startYesterday,
  772. windowEnd: endYesterday,
  773. expMinutes: 1440.0,
  774. },
  775. // 1h AggregationProperties=(Label:app)
  776. "1h": {
  777. start: start,
  778. aggBy: []string{"label:app"},
  779. aggOpts: nil,
  780. numResults: numLabelApps + numIdle + numUnallocated,
  781. totalCost: activeTotalCost + idleTotalCost,
  782. results: map[string]float64{
  783. "app1": 16.00,
  784. "app2": 24.00,
  785. IdleSuffix: 30.00,
  786. UnallocatedSuffix: 42.00,
  787. },
  788. windowStart: startYesterday,
  789. windowEnd: endYesterday,
  790. expMinutes: 1440.0,
  791. },
  792. // 1i AggregationProperties=(deployment)
  793. "1i": {
  794. start: start,
  795. aggBy: []string{AllocationDeploymentProp},
  796. aggOpts: nil,
  797. numResults: 3 + numIdle + numUnallocated,
  798. totalCost: activeTotalCost + idleTotalCost,
  799. results: map[string]float64{
  800. "deployment1": 12.00,
  801. "deployment2": 24.00,
  802. "deployment3": 6.00,
  803. IdleSuffix: 30.00,
  804. UnallocatedSuffix: 40.00,
  805. },
  806. windowStart: startYesterday,
  807. windowEnd: endYesterday,
  808. expMinutes: 1440.0,
  809. },
  810. // 1j AggregationProperties=(Annotation:team)
  811. "1j": {
  812. start: start,
  813. aggBy: []string{"annotation:team"},
  814. aggOpts: nil,
  815. numResults: 2 + numIdle + numUnallocated,
  816. totalCost: activeTotalCost + idleTotalCost,
  817. results: map[string]float64{
  818. "team1": 12.00,
  819. "team2": 6.00,
  820. IdleSuffix: 30.00,
  821. UnallocatedSuffix: 64.00,
  822. },
  823. windowStart: startYesterday,
  824. windowEnd: endYesterday,
  825. expMinutes: 1440.0,
  826. },
  827. // 1k AggregationProperties=(daemonSet)
  828. "1k": {
  829. start: start,
  830. aggBy: []string{AllocationDaemonSetProp},
  831. aggOpts: nil,
  832. numResults: 1 + numIdle + numUnallocated,
  833. totalCost: activeTotalCost + idleTotalCost,
  834. results: map[string]float64{
  835. "daemonset1": 12.00,
  836. IdleSuffix: 30.00,
  837. UnallocatedSuffix: 70.00,
  838. },
  839. windowStart: startYesterday,
  840. windowEnd: endYesterday,
  841. expMinutes: 1440.0,
  842. },
  843. // 1l AggregationProperties=(statefulSet)
  844. "1l": {
  845. start: start,
  846. aggBy: []string{AllocationStatefulSetProp},
  847. aggOpts: nil,
  848. numResults: 1 + numIdle + numUnallocated,
  849. totalCost: activeTotalCost + idleTotalCost,
  850. results: map[string]float64{
  851. "statefulset1": 12.00,
  852. IdleSuffix: 30.00,
  853. UnallocatedSuffix: 70.00,
  854. },
  855. windowStart: startYesterday,
  856. windowEnd: endYesterday,
  857. expMinutes: 1440.0,
  858. },
  859. // 2 Multi-aggregation
  860. // 2a AggregationProperties=(Cluster, Namespace)
  861. // 2b AggregationProperties=(Namespace, Label:app)
  862. // 2c AggregationProperties=(Cluster, Namespace, Pod, Container)
  863. // 2d AggregationProperties=(Label:app, Label:environment)
  864. "2d": {
  865. start: start,
  866. aggBy: []string{"label:app", "label:env"},
  867. aggOpts: nil,
  868. numResults: 3 + numIdle + numUnallocated,
  869. totalCost: activeTotalCost + idleTotalCost,
  870. // sets should be {idle, unallocated, app1/env1, app2/env2, app2/unallocated}
  871. results: map[string]float64{
  872. "app1/env1": 16.00,
  873. "app2/env2": 12.00,
  874. "app2/" + UnallocatedSuffix: 12.00,
  875. IdleSuffix: 30.00,
  876. UnallocatedSuffix + "/" + UnallocatedSuffix: 42.00,
  877. },
  878. windowStart: startYesterday,
  879. windowEnd: endYesterday,
  880. expMinutes: 1440.0,
  881. },
  882. // 2e AggregationProperties=(Cluster, Label:app, Label:environment)
  883. "2e": {
  884. start: start,
  885. aggBy: []string{AllocationClusterProp, "label:app", "label:env"},
  886. aggOpts: nil,
  887. numResults: 6,
  888. totalCost: activeTotalCost + idleTotalCost,
  889. results: map[string]float64{
  890. "cluster1/app2/env2": 12.00,
  891. "__idle__": 30.00,
  892. "cluster1/app1/env1": 16.00,
  893. "cluster1/" + UnallocatedSuffix + "/" + UnallocatedSuffix: 18.00,
  894. "cluster2/app2/" + UnallocatedSuffix: 12.00,
  895. "cluster2/" + UnallocatedSuffix + "/" + UnallocatedSuffix: 24.00,
  896. },
  897. windowStart: startYesterday,
  898. windowEnd: endYesterday,
  899. expMinutes: 1440.0,
  900. },
  901. // 2f AggregationProperties=(annotation:team, pod)
  902. "2f": {
  903. start: start,
  904. aggBy: []string{AllocationPodProp, "annotation:team"},
  905. aggOpts: nil,
  906. numResults: 11,
  907. totalCost: activeTotalCost + idleTotalCost,
  908. results: map[string]float64{
  909. "pod-jkl/" + UnallocatedSuffix: 6.00,
  910. "pod-stu/team1": 6.00,
  911. "pod-abc/" + UnallocatedSuffix: 6.00,
  912. "pod-pqr/" + UnallocatedSuffix: 6.00,
  913. "pod-def/" + UnallocatedSuffix: 6.00,
  914. "pod-vwx/team1": 6.00,
  915. "pod-vwx/team2": 6.00,
  916. "pod1/" + UnallocatedSuffix: 16.00,
  917. "pod-mno/" + UnallocatedSuffix: 12.00,
  918. "pod-ghi/" + UnallocatedSuffix: 12.00,
  919. IdleSuffix: 30.00,
  920. },
  921. windowStart: startYesterday,
  922. windowEnd: endYesterday,
  923. expMinutes: 1440.0,
  924. },
  925. // 3 Share idle
  926. // 3a AggregationProperties=(Namespace) ShareIdle=ShareWeighted
  927. // namespace1: 42.6875 = 28.00 + 5.00*(3.00/6.00) + 15.0*(13.0/16.0)
  928. // namespace2: 46.3125 = 36.00 + 5.0*(3.0/6.0) + 15.0*(3.0/16.0) + 5.0*(3.0/6.0) + 5.0*(3.0/6.0)
  929. // namespace3: 23.0000 = 18.00 + 5.0*(3.0/6.0) + 5.0*(3.0/6.0)
  930. "3a": {
  931. start: start,
  932. aggBy: []string{AllocationNamespaceProp},
  933. aggOpts: &AllocationAggregationOptions{ShareIdle: ShareWeighted},
  934. numResults: numNamespaces,
  935. totalCost: activeTotalCost + idleTotalCost,
  936. results: map[string]float64{
  937. "namespace1": 42.69,
  938. "namespace2": 46.31,
  939. "namespace3": 23.00,
  940. },
  941. windowStart: startYesterday,
  942. windowEnd: endYesterday,
  943. expMinutes: 1440.0,
  944. },
  945. // 3b: sharing idle evenly is deprecated
  946. // 4 Share resources
  947. // 4a Share namespace ShareEven
  948. // namespace1: 37.5000 = 28.00 + 18.00*(1.0/2.0)
  949. // namespace2: 45.5000 = 36.00 + 18.00*(1.0/2.0)
  950. // idle: 30.0000
  951. "4a": {
  952. start: start,
  953. aggBy: []string{AllocationNamespaceProp},
  954. aggOpts: &AllocationAggregationOptions{
  955. ShareFuncs: []AllocationMatchFunc{isNamespace3},
  956. ShareSplit: ShareEven,
  957. },
  958. numResults: numNamespaces,
  959. totalCost: activeTotalCost + idleTotalCost,
  960. results: map[string]float64{
  961. "namespace1": 37.00,
  962. "namespace2": 45.00,
  963. IdleSuffix: 30.00,
  964. },
  965. windowStart: startYesterday,
  966. windowEnd: endYesterday,
  967. expMinutes: 1440.0,
  968. },
  969. // 4b Share namespace ShareWeighted
  970. // namespace1: 32.5000 =
  971. // namespace2: 37.5000 =
  972. // idle: 30.0000
  973. "4b": {
  974. start: start,
  975. aggBy: []string{AllocationNamespaceProp},
  976. aggOpts: &AllocationAggregationOptions{
  977. ShareFuncs: []AllocationMatchFunc{isNamespace3},
  978. ShareSplit: ShareWeighted,
  979. IncludeProportionalAssetResourceCosts: true,
  980. },
  981. numResults: numNamespaces,
  982. totalCost: activeTotalCost + idleTotalCost,
  983. results: map[string]float64{
  984. "namespace1": 35.88,
  985. "namespace2": 46.125,
  986. IdleSuffix: 30.00,
  987. },
  988. windowStart: startYesterday,
  989. windowEnd: endYesterday,
  990. expMinutes: 1440.0,
  991. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  992. "namespace1": ProportionalAssetResourceCosts{
  993. "cluster1": ProportionalAssetResourceCost{
  994. Cluster: "cluster1",
  995. Node: "",
  996. ProviderID: "",
  997. CPUPercentage: 0.5,
  998. GPUPercentage: 0.5,
  999. RAMPercentage: 0.8125,
  1000. },
  1001. },
  1002. "namespace2": ProportionalAssetResourceCosts{
  1003. "cluster1": ProportionalAssetResourceCost{
  1004. Cluster: "cluster1",
  1005. Node: "",
  1006. ProviderID: "",
  1007. CPUPercentage: 0.5,
  1008. GPUPercentage: 0.5,
  1009. RAMPercentage: 0.1875,
  1010. },
  1011. "cluster2": ProportionalAssetResourceCost{
  1012. Cluster: "cluster2",
  1013. Node: "",
  1014. ProviderID: "",
  1015. CPUPercentage: 0.5,
  1016. GPUPercentage: 0.5,
  1017. RAMPercentage: 0.5,
  1018. },
  1019. },
  1020. },
  1021. },
  1022. // 4c Share label ShareEven
  1023. // namespace1: 17.3333 = 28.00 - 16.00 + 16.00*(1.0/3.0)
  1024. // namespace2: 41.3333 = 36.00 + 16.00*(1.0/3.0)
  1025. // namespace3: 23.3333 = 18.00 + 16.00*(1.0/3.0)
  1026. // idle: 30.0000
  1027. "4c": {
  1028. start: start,
  1029. aggBy: []string{AllocationNamespaceProp},
  1030. aggOpts: &AllocationAggregationOptions{
  1031. ShareFuncs: []AllocationMatchFunc{isApp1},
  1032. ShareSplit: ShareEven,
  1033. },
  1034. numResults: numNamespaces + numIdle,
  1035. totalCost: activeTotalCost + idleTotalCost,
  1036. results: map[string]float64{
  1037. "namespace1": 17.33,
  1038. "namespace2": 41.33,
  1039. "namespace3": 23.33,
  1040. IdleSuffix: 30.00,
  1041. },
  1042. windowStart: startYesterday,
  1043. windowEnd: endYesterday,
  1044. expMinutes: 1440.0,
  1045. },
  1046. // 4d Share overhead ShareWeighted
  1047. // namespace1: 85.366 = 28.00 + (7.0*24.0)*(28.00/82.00)
  1048. // namespace2: 109.756 = 36.00 + (7.0*24.0)*(36.00/82.00)
  1049. // namespace3: 54.878 = 18.00 + (7.0*24.0)*(18.00/82.00)
  1050. // idle: 30.0000
  1051. "4d": {
  1052. start: start,
  1053. aggBy: []string{AllocationNamespaceProp},
  1054. aggOpts: &AllocationAggregationOptions{
  1055. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1056. ShareSplit: ShareWeighted,
  1057. },
  1058. numResults: numNamespaces + numIdle,
  1059. totalCost: activeTotalCost + idleTotalCost + (sharedOverheadHourlyCost * 24.0),
  1060. results: map[string]float64{
  1061. "namespace1": 85.366,
  1062. "namespace2": 109.756,
  1063. "namespace3": 54.878,
  1064. IdleSuffix: 30.00,
  1065. },
  1066. windowStart: startYesterday,
  1067. windowEnd: endYesterday,
  1068. expMinutes: 1440.0,
  1069. },
  1070. // 5 Filters
  1071. // 5a Filter by cluster with separate idle
  1072. "5a": {
  1073. start: start,
  1074. aggBy: []string{AllocationClusterProp},
  1075. aggOpts: &AllocationAggregationOptions{
  1076. Filter: AllocationFilterCondition{
  1077. Field: FilterClusterID,
  1078. Op: FilterEquals,
  1079. Value: "cluster1",
  1080. },
  1081. ShareIdle: ShareNone,
  1082. },
  1083. numResults: 1 + numIdle,
  1084. totalCost: 66.0,
  1085. results: map[string]float64{
  1086. "cluster1": 46.00,
  1087. IdleSuffix: 20.00,
  1088. },
  1089. windowStart: startYesterday,
  1090. windowEnd: endYesterday,
  1091. expMinutes: 1440.0,
  1092. },
  1093. // 5b Filter by cluster with shared idle
  1094. "5b": {
  1095. start: start,
  1096. aggBy: []string{AllocationClusterProp},
  1097. aggOpts: &AllocationAggregationOptions{
  1098. Filter: AllocationFilterCondition{Field: FilterClusterID, Op: FilterEquals, Value: "cluster1"},
  1099. ShareIdle: ShareWeighted,
  1100. },
  1101. numResults: 1,
  1102. totalCost: 66.0,
  1103. results: map[string]float64{
  1104. "cluster1": 66.00,
  1105. },
  1106. windowStart: startYesterday,
  1107. windowEnd: endYesterday,
  1108. expMinutes: 1440.0,
  1109. },
  1110. // 5c Filter by cluster, agg by namespace, with separate idle
  1111. "5c": {
  1112. start: start,
  1113. aggBy: []string{AllocationNamespaceProp},
  1114. aggOpts: &AllocationAggregationOptions{
  1115. Filter: AllocationFilterCondition{Field: FilterClusterID, Op: FilterEquals, Value: "cluster1"},
  1116. ShareIdle: ShareNone,
  1117. },
  1118. numResults: 2 + numIdle,
  1119. totalCost: 66.0,
  1120. results: map[string]float64{
  1121. "namespace1": 28.00,
  1122. "namespace2": 18.00,
  1123. IdleSuffix: 20.00,
  1124. },
  1125. windowStart: startYesterday,
  1126. windowEnd: endYesterday,
  1127. expMinutes: 1440.0,
  1128. },
  1129. // 5d Filter by namespace, agg by cluster, with separate idle
  1130. "5d": {
  1131. start: start,
  1132. aggBy: []string{AllocationClusterProp},
  1133. aggOpts: &AllocationAggregationOptions{
  1134. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1135. ShareIdle: ShareNone,
  1136. },
  1137. numResults: numClusters + numIdle,
  1138. totalCost: 46.31,
  1139. results: map[string]float64{
  1140. "cluster1": 18.00,
  1141. "cluster2": 18.00,
  1142. IdleSuffix: 10.31,
  1143. },
  1144. windowStart: startYesterday,
  1145. windowEnd: endYesterday,
  1146. expMinutes: 1440.0,
  1147. },
  1148. // 6 Combinations and options
  1149. // 6a SplitIdle
  1150. "6a": {
  1151. start: start,
  1152. aggBy: []string{AllocationNamespaceProp},
  1153. aggOpts: &AllocationAggregationOptions{
  1154. SplitIdle: true,
  1155. },
  1156. numResults: numNamespaces + numSplitIdleCluster,
  1157. totalCost: activeTotalCost + idleTotalCost,
  1158. results: map[string]float64{
  1159. "namespace1": 28.00,
  1160. "namespace2": 36.00,
  1161. "namespace3": 18.00,
  1162. fmt.Sprintf("cluster1/%s", IdleSuffix): 20.00,
  1163. fmt.Sprintf("cluster2/%s", IdleSuffix): 10.00,
  1164. },
  1165. windowStart: startYesterday,
  1166. windowEnd: endYesterday,
  1167. expMinutes: 1440.0,
  1168. },
  1169. // 6b Share idle weighted with filters
  1170. // Should match values from unfiltered aggregation (3a)
  1171. // namespace2: 46.3125 = 36.00 + 5.0*(3.0/6.0) + 15.0*(3.0/16.0) + 5.0*(3.0/6.0) + 5.0*(3.0/6.0)
  1172. "6b": {
  1173. start: start,
  1174. aggBy: []string{AllocationNamespaceProp},
  1175. aggOpts: &AllocationAggregationOptions{
  1176. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1177. ShareIdle: ShareWeighted,
  1178. },
  1179. numResults: 1,
  1180. totalCost: 46.31,
  1181. results: map[string]float64{
  1182. "namespace2": 46.31,
  1183. },
  1184. windowStart: startYesterday,
  1185. windowEnd: endYesterday,
  1186. expMinutes: 1440.0,
  1187. },
  1188. // 6c Share idle even with filters (share idle even is deprecated)
  1189. // 6d Share overhead with filters
  1190. // namespace1: 85.366 = 28.00 + (7.0*24.0)*(28.00/82.00)
  1191. // namespace2: 109.756 = 36.00 + (7.0*24.0)*(36.00/82.00)
  1192. // namespace3: 54.878 = 18.00 + (7.0*24.0)*(18.00/82.00)
  1193. // idle: 10.3125 = % of idle paired with namespace2
  1194. // Then namespace 2 is filtered.
  1195. "6d": {
  1196. start: start,
  1197. aggBy: []string{AllocationNamespaceProp},
  1198. aggOpts: &AllocationAggregationOptions{
  1199. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1200. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1201. ShareSplit: ShareWeighted,
  1202. },
  1203. numResults: 1 + numIdle,
  1204. totalCost: 120.0686,
  1205. results: map[string]float64{
  1206. "namespace2": 109.7561,
  1207. IdleSuffix: 10.3125,
  1208. },
  1209. windowStart: startYesterday,
  1210. windowEnd: endYesterday,
  1211. expMinutes: 1440.0,
  1212. },
  1213. // 6e Share resources with filters
  1214. "6e": {
  1215. start: start,
  1216. aggBy: []string{AllocationNamespaceProp},
  1217. aggOpts: &AllocationAggregationOptions{
  1218. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1219. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1220. ShareSplit: ShareWeighted,
  1221. },
  1222. numResults: 1 + numIdle,
  1223. totalCost: 79.6667, // should be 74.7708, but I'm punting -- too difficult (NK)
  1224. results: map[string]float64{
  1225. "namespace2": 54.6667,
  1226. IdleSuffix: 25.000, // should be 20.1042, but I'm punting -- too difficult (NK)
  1227. },
  1228. windowStart: startYesterday,
  1229. windowEnd: endYesterday,
  1230. expMinutes: 1440.0,
  1231. },
  1232. // 6f Share resources with filters and share idle
  1233. "6f": {
  1234. start: start,
  1235. aggBy: []string{AllocationNamespaceProp},
  1236. aggOpts: &AllocationAggregationOptions{
  1237. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1238. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1239. ShareSplit: ShareWeighted,
  1240. ShareIdle: ShareWeighted,
  1241. },
  1242. numResults: 1,
  1243. totalCost: 74.77083,
  1244. results: map[string]float64{
  1245. "namespace2": 74.77083,
  1246. },
  1247. windowStart: startYesterday,
  1248. windowEnd: endYesterday,
  1249. expMinutes: 1440.0,
  1250. },
  1251. // 6g Share idle weighted and share resources weighted
  1252. //
  1253. // First, share idle weighted produces:
  1254. //
  1255. // namespace1: 42.6875
  1256. // initial cost 28.0000
  1257. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1258. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1259. //
  1260. // namespace2: 46.3125
  1261. // initial cost 36.0000
  1262. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1263. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1264. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1265. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1266. //
  1267. // namespace3: 23.0000
  1268. // initial cost 18.0000
  1269. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1270. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1271. //
  1272. // Then, sharing namespace1 means sharing 39.6875 according to coefficients
  1273. // computed before allocating idle (so that weighting idle differently
  1274. // doesn't adversely affect the sharing mechanism):
  1275. //
  1276. // namespace2: 74.7708
  1277. // initial cost 30.0000
  1278. // idle cost 10.3125
  1279. // shared cost 28.4583 = (42.6875)*(36.0/54.0)
  1280. //
  1281. // namespace3: 37.2292
  1282. // initial cost 18.0000
  1283. // idle cost 5.0000
  1284. // shared cost 14.2292 = (42.6875)*(18.0/54.0)
  1285. "6g": {
  1286. start: start,
  1287. aggBy: []string{AllocationNamespaceProp},
  1288. aggOpts: &AllocationAggregationOptions{
  1289. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1290. ShareSplit: ShareWeighted,
  1291. ShareIdle: ShareWeighted,
  1292. },
  1293. numResults: 2,
  1294. totalCost: activeTotalCost + idleTotalCost,
  1295. results: map[string]float64{
  1296. "namespace2": 74.77,
  1297. "namespace3": 37.23,
  1298. },
  1299. windowStart: startYesterday,
  1300. windowEnd: endYesterday,
  1301. expMinutes: 1440.0,
  1302. },
  1303. // 6h Share idle, share resources, and filter
  1304. //
  1305. // First, share idle weighted produces:
  1306. //
  1307. // namespace1: 42.6875
  1308. // initial cost 28.0000
  1309. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1310. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1311. //
  1312. // namespace2: 46.3125
  1313. // initial cost 36.0000
  1314. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1315. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1316. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1317. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1318. //
  1319. // namespace3: 23.0000
  1320. // initial cost 18.0000
  1321. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1322. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1323. //
  1324. // Then, sharing namespace1 means sharing 39.6875 according to coefficients
  1325. // computed before allocating idle (so that weighting idle differently
  1326. // doesn't adversely affect the sharing mechanism):
  1327. //
  1328. // namespace2: 74.7708
  1329. // initial cost 36.0000
  1330. // idle cost 10.3125
  1331. // shared cost 28.4583 = (42.6875)*(36.0/54.0)
  1332. //
  1333. // namespace3: 37.2292
  1334. // initial cost 18.0000
  1335. // idle cost 5.0000
  1336. // shared cost 14.2292 = (42.6875)*(18.0/54.0)
  1337. //
  1338. // Then, filter for namespace2: 74.7708
  1339. "6h": {
  1340. start: start,
  1341. aggBy: []string{AllocationNamespaceProp},
  1342. aggOpts: &AllocationAggregationOptions{
  1343. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1344. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1345. ShareSplit: ShareWeighted,
  1346. ShareIdle: ShareWeighted,
  1347. },
  1348. numResults: 1,
  1349. totalCost: 74.77,
  1350. results: map[string]float64{
  1351. "namespace2": 74.77,
  1352. },
  1353. windowStart: startYesterday,
  1354. windowEnd: endYesterday,
  1355. expMinutes: 1440.0,
  1356. },
  1357. // 6i Share idle, share resources, share overhead
  1358. //
  1359. // Share idle weighted:
  1360. //
  1361. // namespace1: 42.6875
  1362. // initial cost 28.0000
  1363. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1364. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1365. //
  1366. // namespace2: 46.3125
  1367. // initial cost 36.0000
  1368. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1369. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1370. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1371. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1372. //
  1373. // namespace3: 23.0000
  1374. // initial cost 18.0000
  1375. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1376. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1377. //
  1378. // Then share overhead:
  1379. //
  1380. // namespace1: 100.0533 = 42.6875 + (7.0*24.0)*(28.00/82.00)
  1381. // namespace2: 120.0686 = 46.3125 + (7.0*24.0)*(36.00/82.00)
  1382. // namespace3: 59.8780 = 23.0000 + (7.0*24.0)*(18.00/82.00)
  1383. //
  1384. // Then namespace 2 is filtered.
  1385. "6i": {
  1386. start: start,
  1387. aggBy: []string{AllocationNamespaceProp},
  1388. aggOpts: &AllocationAggregationOptions{
  1389. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1390. ShareSplit: ShareWeighted,
  1391. ShareIdle: ShareWeighted,
  1392. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1393. },
  1394. numResults: 1,
  1395. totalCost: 120.07,
  1396. results: map[string]float64{
  1397. "namespace2": 120.07,
  1398. },
  1399. windowStart: startYesterday,
  1400. windowEnd: endYesterday,
  1401. expMinutes: 1440.0,
  1402. },
  1403. // 6j Idle by Node
  1404. "6j": {
  1405. start: start,
  1406. aggBy: []string{AllocationNamespaceProp},
  1407. aggOpts: &AllocationAggregationOptions{
  1408. IdleByNode: true,
  1409. IncludeProportionalAssetResourceCosts: true,
  1410. },
  1411. numResults: numNamespaces + numIdle,
  1412. totalCost: activeTotalCost + idleTotalCost,
  1413. results: map[string]float64{
  1414. "namespace1": 28.00,
  1415. "namespace2": 36.00,
  1416. "namespace3": 18.00,
  1417. IdleSuffix: 30.00,
  1418. },
  1419. windowStart: startYesterday,
  1420. windowEnd: endYesterday,
  1421. expMinutes: 1440.0,
  1422. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  1423. "namespace1": {
  1424. "cluster1,c1nodes": ProportionalAssetResourceCost{
  1425. Cluster: "cluster1",
  1426. Node: "c1nodes",
  1427. ProviderID: "c1nodes",
  1428. CPUPercentage: 0.5,
  1429. GPUPercentage: 0.5,
  1430. RAMPercentage: 0.8125,
  1431. },
  1432. "cluster2,node2": ProportionalAssetResourceCost{
  1433. Cluster: "cluster2",
  1434. Node: "node2",
  1435. ProviderID: "node2",
  1436. CPUPercentage: 0.5,
  1437. GPUPercentage: 0.5,
  1438. RAMPercentage: 0.5,
  1439. },
  1440. },
  1441. "namespace2": {
  1442. "cluster1,c1nodes": ProportionalAssetResourceCost{
  1443. Cluster: "cluster1",
  1444. Node: "c1nodes",
  1445. ProviderID: "c1nodes",
  1446. CPUPercentage: 0.5,
  1447. GPUPercentage: 0.5,
  1448. RAMPercentage: 0.1875,
  1449. },
  1450. "cluster2,node1": ProportionalAssetResourceCost{
  1451. Cluster: "cluster2",
  1452. Node: "node1",
  1453. ProviderID: "node1",
  1454. CPUPercentage: 1,
  1455. GPUPercentage: 1,
  1456. RAMPercentage: 1,
  1457. },
  1458. "cluster2,node2": ProportionalAssetResourceCost{
  1459. Cluster: "cluster2",
  1460. Node: "node2",
  1461. ProviderID: "node2",
  1462. CPUPercentage: 0.5,
  1463. GPUPercentage: 0.5,
  1464. RAMPercentage: 0.5,
  1465. },
  1466. },
  1467. "namespace3": {
  1468. "cluster2,node3": ProportionalAssetResourceCost{
  1469. Cluster: "cluster2",
  1470. Node: "node3",
  1471. ProviderID: "node3",
  1472. CPUPercentage: 1,
  1473. GPUPercentage: 1,
  1474. RAMPercentage: 1,
  1475. },
  1476. "cluster2,node2": ProportionalAssetResourceCost{
  1477. Cluster: "cluster2",
  1478. Node: "node2",
  1479. ProviderID: "node2",
  1480. CPUPercentage: 0.5,
  1481. GPUPercentage: 0.5,
  1482. RAMPercentage: 0.5,
  1483. },
  1484. },
  1485. },
  1486. },
  1487. // 6k Split Idle, Idle by Node
  1488. "6k": {
  1489. start: start,
  1490. aggBy: []string{AllocationNamespaceProp},
  1491. aggOpts: &AllocationAggregationOptions{
  1492. SplitIdle: true,
  1493. IdleByNode: true,
  1494. },
  1495. numResults: numNamespaces + numSplitIdleNode,
  1496. totalCost: activeTotalCost + idleTotalCost,
  1497. results: map[string]float64{
  1498. "namespace1": 28.00,
  1499. "namespace2": 36.00,
  1500. "namespace3": 18.00,
  1501. fmt.Sprintf("c1nodes/%s", IdleSuffix): 20.00,
  1502. fmt.Sprintf("node1/%s", IdleSuffix): 3.333333,
  1503. fmt.Sprintf("node2/%s", IdleSuffix): 3.333333,
  1504. fmt.Sprintf("node3/%s", IdleSuffix): 3.333333,
  1505. },
  1506. windowStart: startYesterday,
  1507. windowEnd: endYesterday,
  1508. expMinutes: 1440.0,
  1509. },
  1510. // Old 6k Share idle Even Idle by Node (share idle even deprecated)
  1511. // 6l Share idle weighted with filters, Idle by Node
  1512. // Should match values from unfiltered aggregation (3a)
  1513. // namespace2: 46.3125 = 36.00 + 5.0*(3.0/6.0) + 15.0*(3.0/16.0) + 5.0*(3.0/6.0) + 5.0*(3.0/6.0)
  1514. "6l": {
  1515. start: start,
  1516. aggBy: []string{AllocationNamespaceProp},
  1517. aggOpts: &AllocationAggregationOptions{
  1518. Filter: AllocationFilterCondition{Field: FilterNamespace, Op: FilterEquals, Value: "namespace2"},
  1519. ShareIdle: ShareWeighted,
  1520. IdleByNode: true,
  1521. },
  1522. numResults: 1,
  1523. totalCost: 46.31,
  1524. results: map[string]float64{
  1525. "namespace2": 46.31,
  1526. },
  1527. windowStart: startYesterday,
  1528. windowEnd: endYesterday,
  1529. expMinutes: 1440.0,
  1530. },
  1531. // 7 Edge cases and errors
  1532. // 7a Empty AggregationProperties
  1533. // 7b Filter all
  1534. // 7c Share all
  1535. // 7d Share and filter the same allocations
  1536. }
  1537. for name, testcase := range cases {
  1538. t.Run(name, func(t *testing.T) {
  1539. if testcase.aggOpts != nil && testcase.aggOpts.IdleByNode {
  1540. as = GenerateMockAllocationSetNodeIdle(testcase.start)
  1541. } else {
  1542. as = GenerateMockAllocationSetClusterIdle(testcase.start)
  1543. }
  1544. err = as.AggregateBy(testcase.aggBy, testcase.aggOpts)
  1545. assertAllocationSetTotals(t, as, name, err, testcase.numResults, testcase.totalCost)
  1546. assertAllocationTotals(t, as, name, testcase.results)
  1547. assertParcResults(t, as, name, testcase.expectedParcResults)
  1548. assertAllocationWindow(t, as, name, testcase.windowStart, testcase.windowEnd, testcase.expMinutes)
  1549. })
  1550. }
  1551. }
  1552. // TODO niko/etl
  1553. //func TestAllocationSet_Clone(t *testing.T) {}
  1554. // TODO niko/etl
  1555. //func TestAllocationSet_Delete(t *testing.T) {}
  1556. // TODO niko/etl
  1557. //func TestAllocationSet_End(t *testing.T) {}
  1558. // TODO niko/etl
  1559. //func TestAllocationSet_IdleAllocations(t *testing.T) {}
  1560. // TODO niko/etl
  1561. //func TestAllocationSet_Insert(t *testing.T) {}
  1562. // Asserts that all Allocations within an AllocationSet have a Window that
  1563. // matches that of the AllocationSet.
  1564. func TestAllocationSet_insertMatchingWindow(t *testing.T) {
  1565. setStart := time.Now().Round(time.Hour)
  1566. setEnd := setStart.Add(1 * time.Hour)
  1567. a1WindowStart := setStart.Add(5 * time.Minute)
  1568. a1WindowEnd := setStart.Add(50 * time.Minute)
  1569. a2WindowStart := setStart.Add(17 * time.Minute)
  1570. a2WindowEnd := setStart.Add(34 * time.Minute)
  1571. a1 := &Allocation{
  1572. Name: "allocation-1",
  1573. Window: Window(NewClosedWindow(a1WindowStart, a1WindowEnd)),
  1574. }
  1575. a2 := &Allocation{
  1576. Name: "allocation-2",
  1577. Window: Window(NewClosedWindow(a2WindowStart, a2WindowEnd)),
  1578. }
  1579. as := NewAllocationSet(setStart, setEnd)
  1580. as.Insert(a1)
  1581. as.Insert(a2)
  1582. if as.Length() != 2 {
  1583. t.Errorf("AS length got %d, expected %d", as.Length(), 2)
  1584. }
  1585. for _, a := range as.Allocations {
  1586. if !(*a.Window.Start()).Equal(setStart) {
  1587. t.Errorf("Allocation %s window start is %s, expected %s", a.Name, *a.Window.Start(), setStart)
  1588. }
  1589. if !(*a.Window.End()).Equal(setEnd) {
  1590. t.Errorf("Allocation %s window end is %s, expected %s", a.Name, *a.Window.End(), setEnd)
  1591. }
  1592. }
  1593. }
  1594. // TODO niko/etl
  1595. //func TestAllocationSet_IsEmpty(t *testing.T) {}
  1596. // TODO niko/etl
  1597. //func TestAllocationSet_Length(t *testing.T) {}
  1598. // TODO niko/etl
  1599. //func TestAllocationSet_Map(t *testing.T) {}
  1600. // TODO niko/etl
  1601. //func TestAllocationSet_MarshalJSON(t *testing.T) {}
  1602. // TODO niko/etl
  1603. //func TestAllocationSet_Resolution(t *testing.T) {}
  1604. // TODO niko/etl
  1605. //func TestAllocationSet_Seconds(t *testing.T) {}
  1606. // TODO niko/etl
  1607. //func TestAllocationSet_Set(t *testing.T) {}
  1608. // TODO niko/etl
  1609. //func TestAllocationSet_Start(t *testing.T) {}
  1610. // TODO niko/etl
  1611. //func TestAllocationSet_TotalCost(t *testing.T) {}
  1612. // TODO niko/etl
  1613. //func TestNewAllocationSetRange(t *testing.T) {}
  1614. func TestAllocationSetRange_AccumulateRepeat(t *testing.T) {
  1615. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1616. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1617. today := time.Now().UTC().Truncate(day)
  1618. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1619. a := GenerateMockAllocationSet(ago2d)
  1620. b := GenerateMockAllocationSet(yesterday)
  1621. c := GenerateMockAllocationSet(today)
  1622. d := GenerateMockAllocationSet(tomorrow)
  1623. asr := NewAllocationSetRange(a, b, c, d)
  1624. // Take Total Cost
  1625. totalCost := asr.TotalCost()
  1626. // NewAccumulation does not mutate
  1627. result, err := asr.newAccumulation()
  1628. if err != nil {
  1629. t.Fatal(err)
  1630. }
  1631. asr2 := NewAllocationSetRange(result)
  1632. // Ensure Costs Match
  1633. if totalCost != asr2.TotalCost() {
  1634. t.Fatalf("Accumulated Total Cost does not match original Total Cost")
  1635. }
  1636. // Next NewAccumulation() call should prove that there is no mutation of inner data
  1637. result, err = asr.newAccumulation()
  1638. if err != nil {
  1639. t.Fatal(err)
  1640. }
  1641. asr3 := NewAllocationSetRange(result)
  1642. // Costs should be correct, as multiple calls to NewAccumulation() should not alter
  1643. // the internals of the AllocationSetRange
  1644. if totalCost != asr3.TotalCost() {
  1645. t.Fatalf("Accumulated Total Cost does not match original Total Cost. %f != %f", totalCost, asr3.TotalCost())
  1646. }
  1647. }
  1648. func TestAllocationSetRange_Accumulate(t *testing.T) {
  1649. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1650. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1651. today := time.Now().UTC().Truncate(day)
  1652. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1653. // Accumulating any combination of nil and/or empty set should result in empty set
  1654. result, err := NewAllocationSetRange(nil).accumulate()
  1655. if err != nil {
  1656. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  1657. }
  1658. if !result.IsEmpty() {
  1659. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  1660. }
  1661. result, err = NewAllocationSetRange(nil, nil).accumulate()
  1662. if err != nil {
  1663. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  1664. }
  1665. if !result.IsEmpty() {
  1666. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  1667. }
  1668. result, err = NewAllocationSetRange(NewAllocationSet(yesterday, today)).accumulate()
  1669. if err != nil {
  1670. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  1671. }
  1672. if !result.IsEmpty() {
  1673. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  1674. }
  1675. result, err = NewAllocationSetRange(nil, NewAllocationSet(ago2d, yesterday), nil, NewAllocationSet(today, tomorrow), nil).accumulate()
  1676. if err != nil {
  1677. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  1678. }
  1679. if !result.IsEmpty() {
  1680. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  1681. }
  1682. todayAS := NewAllocationSet(today, tomorrow)
  1683. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1684. yesterdayAS := NewAllocationSet(yesterday, today)
  1685. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1686. // Accumulate non-nil with nil should result in copy of non-nil, regardless of order
  1687. result, err = NewAllocationSetRange(nil, todayAS).accumulate()
  1688. if err != nil {
  1689. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  1690. }
  1691. if result == nil {
  1692. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  1693. }
  1694. if result.TotalCost() != 6.0 {
  1695. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  1696. }
  1697. result, err = NewAllocationSetRange(todayAS, nil).accumulate()
  1698. if err != nil {
  1699. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  1700. }
  1701. if result == nil {
  1702. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  1703. }
  1704. if result.TotalCost() != 6.0 {
  1705. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  1706. }
  1707. result, err = NewAllocationSetRange(nil, todayAS, nil).accumulate()
  1708. if err != nil {
  1709. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  1710. }
  1711. if result == nil {
  1712. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  1713. }
  1714. if result.TotalCost() != 6.0 {
  1715. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  1716. }
  1717. // Accumulate two non-nil should result in sum of both with appropriate start, end
  1718. result, err = NewAllocationSetRange(yesterdayAS, todayAS).accumulate()
  1719. if err != nil {
  1720. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  1721. }
  1722. if result == nil {
  1723. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  1724. }
  1725. if result.TotalCost() != 12.0 {
  1726. t.Fatalf("accumulating AllocationSetRange: expected total cost 12.0; actual %f", result.TotalCost())
  1727. }
  1728. allocMap := result.Allocations
  1729. if len(allocMap) != 1 {
  1730. t.Fatalf("accumulating AllocationSetRange: expected length 1; actual length %d", len(allocMap))
  1731. }
  1732. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  1733. if alloc == nil {
  1734. t.Fatalf("accumulating AllocationSetRange: expected allocation 'cluster1/namespace1/pod1/container1'")
  1735. }
  1736. if alloc.CPUCoreHours != 2.0 {
  1737. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", result.TotalCost())
  1738. }
  1739. if alloc.CPUCost != 2.0 {
  1740. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.CPUCost)
  1741. }
  1742. if alloc.CPUEfficiency() != 1.0 {
  1743. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.CPUEfficiency())
  1744. }
  1745. if alloc.GPUHours != 2.0 {
  1746. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.GPUHours)
  1747. }
  1748. if alloc.GPUCost != 2.0 {
  1749. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.GPUCost)
  1750. }
  1751. if alloc.NetworkCost != 2.0 {
  1752. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.NetworkCost)
  1753. }
  1754. if alloc.LoadBalancerCost != 2.0 {
  1755. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.LoadBalancerCost)
  1756. }
  1757. if alloc.PVByteHours() != 2.0 {
  1758. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.PVByteHours())
  1759. }
  1760. if alloc.PVCost() != 2.0 {
  1761. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.PVCost())
  1762. }
  1763. if alloc.RAMByteHours != 2.0 {
  1764. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.RAMByteHours)
  1765. }
  1766. if alloc.RAMCost != 2.0 {
  1767. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.RAMCost)
  1768. }
  1769. if alloc.RAMEfficiency() != 1.0 {
  1770. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.RAMEfficiency())
  1771. }
  1772. if alloc.TotalCost() != 12.0 {
  1773. t.Fatalf("accumulating AllocationSetRange: expected 12.0; actual %f", alloc.TotalCost())
  1774. }
  1775. if alloc.TotalEfficiency() != 1.0 {
  1776. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.TotalEfficiency())
  1777. }
  1778. if !alloc.Start.Equal(yesterday) {
  1779. t.Fatalf("accumulating AllocationSetRange: expected to start %s; actual %s", yesterday, alloc.Start)
  1780. }
  1781. if !alloc.End.Equal(tomorrow) {
  1782. t.Fatalf("accumulating AllocationSetRange: expected to end %s; actual %s", tomorrow, alloc.End)
  1783. }
  1784. if alloc.Minutes() != 2880.0 {
  1785. t.Fatalf("accumulating AllocationSetRange: expected %f minutes; actual %f", 2880.0, alloc.Minutes())
  1786. }
  1787. }
  1788. func TestAllocationSetRange_AccumulateBy_None(t *testing.T) {
  1789. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1790. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1791. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1792. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1793. today := time.Now().UTC().Truncate(day)
  1794. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1795. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1796. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1797. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1798. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1799. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1800. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1801. yesterdayAS := NewAllocationSet(yesterday, today)
  1802. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1803. todayAS := NewAllocationSet(today, tomorrow)
  1804. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1805. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1806. asr, err := asr.Accumulate(AccumulateOptionNone)
  1807. if err != nil {
  1808. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1809. }
  1810. if len(asr.Allocations) != 5 {
  1811. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  1812. }
  1813. }
  1814. func TestAllocationSetRange_AccumulateBy_All(t *testing.T) {
  1815. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1816. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1817. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1818. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1819. today := time.Now().UTC().Truncate(day)
  1820. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1821. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1822. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1823. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1824. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1825. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1826. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1827. yesterdayAS := NewAllocationSet(yesterday, today)
  1828. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1829. todayAS := NewAllocationSet(today, tomorrow)
  1830. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1831. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1832. asr, err := asr.Accumulate(AccumulateOptionAll)
  1833. if err != nil {
  1834. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1835. }
  1836. if len(asr.Allocations) != 1 {
  1837. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  1838. }
  1839. allocMap := asr.Allocations[0].Allocations
  1840. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  1841. if alloc.Minutes() != 4320.0 {
  1842. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 4320.0, alloc.Minutes())
  1843. }
  1844. }
  1845. func TestAllocationSetRange_AccumulateBy_Hour(t *testing.T) {
  1846. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  1847. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  1848. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  1849. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  1850. currentHour := time.Now().UTC().Truncate(time.Hour)
  1851. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  1852. ago4hAS := NewAllocationSet(ago4h, ago3h)
  1853. ago4hAS.Set(NewMockUnitAllocation("4", ago4h, time.Hour, nil))
  1854. ago3hAS := NewAllocationSet(ago3h, ago2h)
  1855. ago3hAS.Set(NewMockUnitAllocation("a", ago3h, time.Hour, nil))
  1856. ago2hAS := NewAllocationSet(ago2h, ago1h)
  1857. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  1858. ago1hAS := NewAllocationSet(ago1h, currentHour)
  1859. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  1860. currentHourAS := NewAllocationSet(currentHour, nextHour)
  1861. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  1862. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  1863. asr, err := asr.Accumulate(AccumulateOptionHour)
  1864. if err != nil {
  1865. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1866. }
  1867. if len(asr.Allocations) != 5 {
  1868. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  1869. }
  1870. allocMap := asr.Allocations[0].Allocations
  1871. alloc := allocMap["4"]
  1872. if alloc.Minutes() != 60.0 {
  1873. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 60.0, alloc.Minutes())
  1874. }
  1875. }
  1876. func TestAllocationSetRange_AccumulateBy_Day_From_Day(t *testing.T) {
  1877. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1878. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1879. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1880. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1881. today := time.Now().UTC().Truncate(day)
  1882. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1883. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1884. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1885. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1886. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1887. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1888. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1889. yesterdayAS := NewAllocationSet(yesterday, today)
  1890. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1891. todayAS := NewAllocationSet(today, tomorrow)
  1892. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1893. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1894. asr, err := asr.Accumulate(AccumulateOptionDay)
  1895. if err != nil {
  1896. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1897. }
  1898. if len(asr.Allocations) != 5 {
  1899. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  1900. }
  1901. allocMap := asr.Allocations[0].Allocations
  1902. alloc := allocMap["4"]
  1903. if alloc.Minutes() != 1440.0 {
  1904. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 1440.0, alloc.Minutes())
  1905. }
  1906. }
  1907. func TestAllocationSetRange_AccumulateBy_Day_From_Hours(t *testing.T) {
  1908. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  1909. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  1910. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  1911. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  1912. currentHour := time.Now().UTC().Truncate(time.Hour)
  1913. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  1914. ago4hAS := NewAllocationSet(ago4h, ago3h)
  1915. ago4hAS.Set(NewMockUnitAllocation("", ago4h, time.Hour, nil))
  1916. ago3hAS := NewAllocationSet(ago3h, ago2h)
  1917. ago3hAS.Set(NewMockUnitAllocation("", ago3h, time.Hour, nil))
  1918. ago2hAS := NewAllocationSet(ago2h, ago1h)
  1919. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  1920. ago1hAS := NewAllocationSet(ago1h, currentHour)
  1921. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  1922. currentHourAS := NewAllocationSet(currentHour, nextHour)
  1923. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  1924. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  1925. asr, err := asr.Accumulate(AccumulateOptionDay)
  1926. if err != nil {
  1927. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1928. }
  1929. if len(asr.Allocations) != 1 && len(asr.Allocations) != 2 {
  1930. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  1931. }
  1932. allocMap := asr.Allocations[0].Allocations
  1933. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  1934. if alloc.Minutes() > 300.0 {
  1935. t.Errorf("accumulating AllocationSetRange: expected %f or less minutes; actual %f", 300.0, alloc.Minutes())
  1936. }
  1937. }
  1938. func TestAllocationSetRange_AccumulateBy_Week(t *testing.T) {
  1939. ago9d := time.Now().UTC().Truncate(day).Add(-9 * day)
  1940. ago8d := time.Now().UTC().Truncate(day).Add(-8 * day)
  1941. ago7d := time.Now().UTC().Truncate(day).Add(-7 * day)
  1942. ago6d := time.Now().UTC().Truncate(day).Add(-6 * day)
  1943. ago5d := time.Now().UTC().Truncate(day).Add(-5 * day)
  1944. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1945. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1946. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1947. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1948. today := time.Now().UTC().Truncate(day)
  1949. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1950. ago9dAS := NewAllocationSet(ago9d, ago8d)
  1951. ago9dAS.Set(NewMockUnitAllocation("4", ago9d, day, nil))
  1952. ago8dAS := NewAllocationSet(ago8d, ago7d)
  1953. ago8dAS.Set(NewMockUnitAllocation("4", ago8d, day, nil))
  1954. ago7dAS := NewAllocationSet(ago7d, ago6d)
  1955. ago7dAS.Set(NewMockUnitAllocation("4", ago7d, day, nil))
  1956. ago6dAS := NewAllocationSet(ago6d, ago5d)
  1957. ago6dAS.Set(NewMockUnitAllocation("4", ago6d, day, nil))
  1958. ago5dAS := NewAllocationSet(ago5d, ago4d)
  1959. ago5dAS.Set(NewMockUnitAllocation("4", ago5d, day, nil))
  1960. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1961. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1962. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1963. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1964. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1965. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1966. yesterdayAS := NewAllocationSet(yesterday, today)
  1967. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1968. todayAS := NewAllocationSet(today, tomorrow)
  1969. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1970. asr := NewAllocationSetRange(ago9dAS, ago8dAS, ago7dAS, ago6dAS, ago5dAS, ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1971. asr, err := asr.Accumulate(AccumulateOptionWeek)
  1972. if err != nil {
  1973. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1974. }
  1975. if len(asr.Allocations) != 2 && len(asr.Allocations) != 3 {
  1976. t.Fatalf("expected 2 or 3 allocation sets, got:%d", len(asr.Allocations))
  1977. }
  1978. for _, as := range asr.Allocations {
  1979. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*7 {
  1980. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  1981. }
  1982. }
  1983. }
  1984. func TestAllocationSetRange_AccumulateBy_Month(t *testing.T) {
  1985. prevMonth1stDay := time.Date(2020, 01, 29, 0, 0, 0, 0, time.UTC)
  1986. prevMonth2ndDay := time.Date(2020, 01, 30, 0, 0, 0, 0, time.UTC)
  1987. prevMonth3ndDay := time.Date(2020, 01, 31, 0, 0, 0, 0, time.UTC)
  1988. nextMonth1stDay := time.Date(2020, 02, 01, 0, 0, 0, 0, time.UTC)
  1989. nextMonth2ndDay := time.Date(2020, 02, 02, 0, 0, 0, 0, time.UTC)
  1990. prev1AS := NewAllocationSet(prevMonth1stDay, prevMonth2ndDay)
  1991. prev1AS.Set(NewMockUnitAllocation("", prevMonth1stDay, day, nil))
  1992. prev2AS := NewAllocationSet(prevMonth2ndDay, prevMonth3ndDay)
  1993. prev2AS.Set(NewMockUnitAllocation("", prevMonth2ndDay, day, nil))
  1994. prev3AS := NewAllocationSet(prevMonth3ndDay, nextMonth1stDay)
  1995. prev3AS.Set(NewMockUnitAllocation("", prevMonth3ndDay, day, nil))
  1996. nextAS := NewAllocationSet(nextMonth1stDay, nextMonth2ndDay)
  1997. nextAS.Set(NewMockUnitAllocation("", nextMonth1stDay, day, nil))
  1998. asr := NewAllocationSetRange(prev1AS, prev2AS, prev3AS, nextAS)
  1999. asr, err := asr.Accumulate(AccumulateOptionMonth)
  2000. if err != nil {
  2001. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2002. }
  2003. if len(asr.Allocations) != 2 {
  2004. t.Fatalf("expected 2 allocation sets, got:%d", len(asr.Allocations))
  2005. }
  2006. for _, as := range asr.Allocations {
  2007. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*31 {
  2008. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  2009. }
  2010. }
  2011. }
  2012. // TODO niko/etl
  2013. // func TestAllocationSetRange_AggregateBy(t *testing.T) {}
  2014. // TODO niko/etl
  2015. // func TestAllocationSetRange_Append(t *testing.T) {}
  2016. // TODO niko/etl
  2017. // func TestAllocationSetRange_Each(t *testing.T) {}
  2018. // TODO niko/etl
  2019. // func TestAllocationSetRange_Get(t *testing.T) {}
  2020. func TestAllocationSetRange_InsertRange(t *testing.T) {
  2021. // Set up
  2022. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2023. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2024. today := time.Now().UTC().Truncate(day)
  2025. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2026. unit := NewMockUnitAllocation("", today, day, nil)
  2027. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2028. ago2dAS.Set(NewMockUnitAllocation("a", ago2d, day, nil))
  2029. ago2dAS.Set(NewMockUnitAllocation("b", ago2d, day, nil))
  2030. ago2dAS.Set(NewMockUnitAllocation("c", ago2d, day, nil))
  2031. yesterdayAS := NewAllocationSet(yesterday, today)
  2032. yesterdayAS.Set(NewMockUnitAllocation("a", yesterday, day, nil))
  2033. yesterdayAS.Set(NewMockUnitAllocation("b", yesterday, day, nil))
  2034. yesterdayAS.Set(NewMockUnitAllocation("c", yesterday, day, nil))
  2035. todayAS := NewAllocationSet(today, tomorrow)
  2036. todayAS.Set(NewMockUnitAllocation("a", today, day, nil))
  2037. todayAS.Set(NewMockUnitAllocation("b", today, day, nil))
  2038. todayAS.Set(NewMockUnitAllocation("c", today, day, nil))
  2039. var nilASR *AllocationSetRange
  2040. thisASR := NewAllocationSetRange(yesterdayAS.Clone(), todayAS.Clone())
  2041. thatASR := NewAllocationSetRange(yesterdayAS.Clone())
  2042. longASR := NewAllocationSetRange(ago2dAS.Clone(), yesterdayAS.Clone(), todayAS.Clone())
  2043. var err error
  2044. // Expect an error calling InsertRange on nil
  2045. err = nilASR.InsertRange(thatASR)
  2046. if err == nil {
  2047. t.Fatalf("expected error, got nil")
  2048. }
  2049. // Expect nothing to happen calling InsertRange(nil) on non-nil ASR
  2050. err = thisASR.InsertRange(nil)
  2051. if err != nil {
  2052. t.Fatalf("unexpected error: %s", err)
  2053. }
  2054. for _, as := range thisASR.Allocations {
  2055. for k, a := range as.Allocations {
  2056. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2057. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2058. }
  2059. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2060. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2061. }
  2062. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2063. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2064. }
  2065. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2066. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2067. }
  2068. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2069. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2070. }
  2071. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2072. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2073. }
  2074. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2075. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2076. }
  2077. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2078. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2079. }
  2080. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2081. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2082. }
  2083. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2084. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2085. }
  2086. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2087. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2088. }
  2089. }
  2090. }
  2091. // Expect an error calling InsertRange with a range exceeding the receiver
  2092. err = thisASR.InsertRange(longASR)
  2093. if err == nil {
  2094. t.Fatalf("expected error calling InsertRange with a range exceeding the receiver")
  2095. }
  2096. // Expect each Allocation in "today" to stay the same, but "yesterday" to
  2097. // precisely double when inserting a range that only has a duplicate of
  2098. // "yesterday", but no entry for "today"
  2099. err = thisASR.InsertRange(thatASR)
  2100. if err != nil {
  2101. t.Fatalf("unexpected error: %s", err)
  2102. }
  2103. yAS, err := thisASR.Get(0)
  2104. for k, a := range yAS.Allocations {
  2105. if !util.IsApproximately(a.CPUCoreHours, 2*unit.CPUCoreHours) {
  2106. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2107. }
  2108. if !util.IsApproximately(a.CPUCost, 2*unit.CPUCost) {
  2109. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2110. }
  2111. if !util.IsApproximately(a.RAMByteHours, 2*unit.RAMByteHours) {
  2112. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2113. }
  2114. if !util.IsApproximately(a.RAMCost, 2*unit.RAMCost) {
  2115. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2116. }
  2117. if !util.IsApproximately(a.GPUHours, 2*unit.GPUHours) {
  2118. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2119. }
  2120. if !util.IsApproximately(a.GPUCost, 2*unit.GPUCost) {
  2121. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2122. }
  2123. if !util.IsApproximately(a.PVByteHours(), 2*unit.PVByteHours()) {
  2124. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2125. }
  2126. if !util.IsApproximately(a.PVCost(), 2*unit.PVCost()) {
  2127. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2128. }
  2129. if !util.IsApproximately(a.NetworkCost, 2*unit.NetworkCost) {
  2130. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2131. }
  2132. if !util.IsApproximately(a.LoadBalancerCost, 2*unit.LoadBalancerCost) {
  2133. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2134. }
  2135. if !util.IsApproximately(a.TotalCost(), 2*unit.TotalCost()) {
  2136. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2137. }
  2138. }
  2139. tAS, err := thisASR.Get(1)
  2140. for k, a := range tAS.Allocations {
  2141. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2142. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2143. }
  2144. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2145. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2146. }
  2147. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2148. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2149. }
  2150. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2151. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2152. }
  2153. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2154. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2155. }
  2156. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2157. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2158. }
  2159. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2160. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2161. }
  2162. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2163. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2164. }
  2165. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2166. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2167. }
  2168. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2169. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2170. }
  2171. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2172. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2173. }
  2174. }
  2175. }
  2176. // TODO niko/etl
  2177. // func TestAllocationSetRange_Length(t *testing.T) {}
  2178. func TestAllocationSetRange_MarshalJSON(t *testing.T) {
  2179. tests := []struct {
  2180. name string
  2181. arg *AllocationSetRange
  2182. expected *AllocationSetRange
  2183. }{
  2184. {
  2185. name: "Nil ASR",
  2186. arg: nil,
  2187. },
  2188. {
  2189. name: "Nil AS in ASR",
  2190. arg: NewAllocationSetRange(nil),
  2191. },
  2192. {
  2193. name: "Normal ASR",
  2194. arg: &AllocationSetRange{
  2195. Allocations: []*AllocationSet{
  2196. {
  2197. Allocations: map[string]*Allocation{
  2198. "a": {
  2199. Start: time.Now().UTC().Truncate(day),
  2200. },
  2201. },
  2202. },
  2203. },
  2204. },
  2205. },
  2206. }
  2207. for _, test := range tests {
  2208. bytes, err := json.Marshal(test.arg)
  2209. if err != nil {
  2210. t.Fatalf("ASR Marshal: test %s, unexpected error: %s", test.name, err)
  2211. }
  2212. var testASR []*AllocationSet
  2213. marshaled := &testASR
  2214. err = json.Unmarshal(bytes, marshaled)
  2215. if err != nil {
  2216. t.Fatalf("ASR Unmarshal: test %s: unexpected error: %s", test.name, err)
  2217. }
  2218. if test.arg.Length() != len(testASR) {
  2219. t.Fatalf("ASR Unmarshal: test %s: length mutated in encoding: expected %d but got %d", test.name, test.arg.Length(), len(testASR))
  2220. }
  2221. // Allocations don't unmarshal back from json
  2222. }
  2223. }
  2224. // TODO niko/etl
  2225. // func TestAllocationSetRange_Slice(t *testing.T) {}
  2226. // TODO niko/etl
  2227. // func TestAllocationSetRange_Window(t *testing.T) {}
  2228. func TestAllocationSetRange_Start(t *testing.T) {
  2229. tests := []struct {
  2230. name string
  2231. arg *AllocationSetRange
  2232. expectError bool
  2233. expected time.Time
  2234. }{
  2235. {
  2236. name: "Empty ASR",
  2237. arg: nil,
  2238. expectError: true,
  2239. },
  2240. {
  2241. name: "Single allocation",
  2242. arg: &AllocationSetRange{
  2243. Allocations: []*AllocationSet{
  2244. {
  2245. Allocations: map[string]*Allocation{
  2246. "a": {
  2247. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2248. },
  2249. },
  2250. },
  2251. },
  2252. },
  2253. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2254. },
  2255. {
  2256. name: "Two allocations",
  2257. arg: &AllocationSetRange{
  2258. Allocations: []*AllocationSet{
  2259. {
  2260. Allocations: map[string]*Allocation{
  2261. "a": {
  2262. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2263. },
  2264. "b": {
  2265. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2266. },
  2267. },
  2268. },
  2269. },
  2270. },
  2271. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2272. },
  2273. {
  2274. name: "Two AllocationSets",
  2275. arg: &AllocationSetRange{
  2276. Allocations: []*AllocationSet{
  2277. {
  2278. Allocations: map[string]*Allocation{
  2279. "a": {
  2280. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2281. },
  2282. },
  2283. },
  2284. {
  2285. Allocations: map[string]*Allocation{
  2286. "b": {
  2287. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2288. },
  2289. },
  2290. },
  2291. },
  2292. },
  2293. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2294. },
  2295. }
  2296. for _, test := range tests {
  2297. result, err := test.arg.Start()
  2298. if test.expectError && err != nil {
  2299. continue
  2300. }
  2301. if test.expectError && err == nil {
  2302. t.Errorf("%s: expected error and got none", test.name)
  2303. } else if result != test.expected {
  2304. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2305. }
  2306. }
  2307. }
  2308. func TestAllocationSetRange_End(t *testing.T) {
  2309. tests := []struct {
  2310. name string
  2311. arg *AllocationSetRange
  2312. expectError bool
  2313. expected time.Time
  2314. }{
  2315. {
  2316. name: "Empty ASR",
  2317. arg: nil,
  2318. expectError: true,
  2319. },
  2320. {
  2321. name: "Single allocation",
  2322. arg: &AllocationSetRange{
  2323. Allocations: []*AllocationSet{
  2324. {
  2325. Allocations: map[string]*Allocation{
  2326. "a": {
  2327. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2328. },
  2329. },
  2330. },
  2331. },
  2332. },
  2333. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2334. },
  2335. {
  2336. name: "Two allocations",
  2337. arg: &AllocationSetRange{
  2338. Allocations: []*AllocationSet{
  2339. {
  2340. Allocations: map[string]*Allocation{
  2341. "a": {
  2342. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2343. },
  2344. "b": {
  2345. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2346. },
  2347. },
  2348. },
  2349. },
  2350. },
  2351. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2352. },
  2353. {
  2354. name: "Two AllocationSets",
  2355. arg: &AllocationSetRange{
  2356. Allocations: []*AllocationSet{
  2357. {
  2358. Allocations: map[string]*Allocation{
  2359. "a": {
  2360. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2361. },
  2362. },
  2363. },
  2364. {
  2365. Allocations: map[string]*Allocation{
  2366. "b": {
  2367. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2368. },
  2369. },
  2370. },
  2371. },
  2372. },
  2373. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2374. },
  2375. }
  2376. for _, test := range tests {
  2377. result, err := test.arg.End()
  2378. if test.expectError && err != nil {
  2379. continue
  2380. }
  2381. if test.expectError && err == nil {
  2382. t.Errorf("%s: expected error and got none", test.name)
  2383. } else if result != test.expected {
  2384. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2385. }
  2386. }
  2387. }
  2388. func TestAllocationSetRange_Minutes(t *testing.T) {
  2389. tests := []struct {
  2390. name string
  2391. arg *AllocationSetRange
  2392. expected float64
  2393. }{
  2394. {
  2395. name: "Empty ASR",
  2396. arg: nil,
  2397. expected: 0,
  2398. },
  2399. {
  2400. name: "Single allocation",
  2401. arg: &AllocationSetRange{
  2402. Allocations: []*AllocationSet{
  2403. {
  2404. Allocations: map[string]*Allocation{
  2405. "a": {
  2406. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2407. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2408. },
  2409. },
  2410. },
  2411. },
  2412. },
  2413. expected: 24 * 60,
  2414. },
  2415. {
  2416. name: "Two allocations",
  2417. arg: &AllocationSetRange{
  2418. Allocations: []*AllocationSet{
  2419. {
  2420. Allocations: map[string]*Allocation{
  2421. "a": {
  2422. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2423. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2424. },
  2425. "b": {
  2426. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2427. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  2428. },
  2429. },
  2430. },
  2431. },
  2432. },
  2433. expected: 2 * 24 * 60,
  2434. },
  2435. {
  2436. name: "Two AllocationSets",
  2437. arg: &AllocationSetRange{
  2438. Allocations: []*AllocationSet{
  2439. {
  2440. Allocations: map[string]*Allocation{
  2441. "a": {
  2442. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2443. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2444. },
  2445. },
  2446. },
  2447. {
  2448. Allocations: map[string]*Allocation{
  2449. "b": {
  2450. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2451. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  2452. },
  2453. },
  2454. },
  2455. },
  2456. },
  2457. expected: 2 * 24 * 60,
  2458. },
  2459. }
  2460. for _, test := range tests {
  2461. result := test.arg.Minutes()
  2462. if result != test.expected {
  2463. t.Errorf("%s: expected %f but got %f", test.name, test.expected, result)
  2464. }
  2465. }
  2466. }
  2467. func TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate(t *testing.T) {
  2468. today := time.Now().Round(day)
  2469. start := today.AddDate(0, 0, -4)
  2470. var allocationSets []*AllocationSet
  2471. for i := 0; i < 4; i++ {
  2472. allocationSets = append(allocationSets, GenerateMockAllocationSet(start))
  2473. start = start.AddDate(0, 0, 1)
  2474. }
  2475. var originalAllocationSets []*AllocationSet
  2476. for _, as := range allocationSets {
  2477. originalAllocationSets = append(originalAllocationSets, as.Clone())
  2478. }
  2479. asr := NewAllocationSetRange()
  2480. for _, as := range allocationSets {
  2481. asr.Append(as.Clone())
  2482. }
  2483. expected, err := asr.accumulate()
  2484. if err != nil {
  2485. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: AllocationSetRange.Accumulate() returned an error\n")
  2486. }
  2487. var got *AllocationSet
  2488. for i := 0; i < len(allocationSets); i++ {
  2489. got, err = got.Accumulate(allocationSets[i])
  2490. if err != nil {
  2491. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Accumulate(allocationSets[%d]) returned an error\n", i)
  2492. }
  2493. }
  2494. // compare the got and expected Allocation sets, ensure that they match
  2495. if len(got.Allocations) != len(expected.Allocations) {
  2496. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.Allocations does not match length of expected.Allocations\n")
  2497. }
  2498. for key, a := range got.Allocations {
  2499. if _, ok := expected.Allocations[key]; !ok {
  2500. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] not found in expected.Allocations\n", key)
  2501. }
  2502. if !a.Equal(expected.Allocations[key]) {
  2503. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] did not match expected.Allocations[%[1]s]", key)
  2504. }
  2505. }
  2506. if len(got.ExternalKeys) != len(expected.ExternalKeys) {
  2507. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.ExternalKeys does not match length of expected.ExternalKeys\n")
  2508. }
  2509. if len(got.IdleKeys) != len(expected.IdleKeys) {
  2510. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.IdleKeys does not match length of expected.IdleKeys\n")
  2511. }
  2512. if !got.Window.Start().UTC().Equal(expected.Window.Start().UTC()) {
  2513. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.start: got:%s, expected:%s\n", got.Window.Start(), expected.Window.Start())
  2514. }
  2515. if !got.Window.End().UTC().Equal(expected.Window.End().UTC()) {
  2516. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.end: got:%s, expected:%s\n", got.Window.End(), expected.Window.End())
  2517. }
  2518. for i := range allocationSets {
  2519. for key, allocation := range allocationSets[i].Allocations {
  2520. if !allocation.Equal(originalAllocationSets[i].Allocations[key]) {
  2521. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: allocationSet has been mutated in Accumulate; allocationSet: %d, allocation: %s\n", i, key)
  2522. }
  2523. }
  2524. }
  2525. }