allocation_test.go 86 KB

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