allocation_test.go 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647
  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_None(t *testing.T) {
  1680. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1681. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  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. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1687. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1688. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1689. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1690. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1691. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1692. yesterdayAS := NewAllocationSet(yesterday, today)
  1693. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1694. todayAS := NewAllocationSet(today, tomorrow)
  1695. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1696. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1697. asr, err := asr.Accumulate(AccumulateOptionNone)
  1698. if err != nil {
  1699. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1700. }
  1701. if len(asr.Allocations) != 5 {
  1702. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  1703. }
  1704. }
  1705. func TestAllocationSetRange_AccumulateBy_All(t *testing.T) {
  1706. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1707. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1708. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1709. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1710. today := time.Now().UTC().Truncate(day)
  1711. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1712. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1713. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1714. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1715. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1716. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1717. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1718. yesterdayAS := NewAllocationSet(yesterday, today)
  1719. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1720. todayAS := NewAllocationSet(today, tomorrow)
  1721. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1722. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1723. asr, err := asr.Accumulate(AccumulateOptionAll)
  1724. if err != nil {
  1725. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1726. }
  1727. if len(asr.Allocations) != 1 {
  1728. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  1729. }
  1730. allocMap := asr.Allocations[0].Allocations
  1731. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  1732. if alloc.Minutes() != 4320.0 {
  1733. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 4320.0, alloc.Minutes())
  1734. }
  1735. }
  1736. func TestAllocationSetRange_AccumulateBy_Hour(t *testing.T) {
  1737. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  1738. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  1739. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  1740. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  1741. currentHour := time.Now().UTC().Truncate(time.Hour)
  1742. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  1743. ago4hAS := NewAllocationSet(ago4h, ago3h)
  1744. ago4hAS.Set(NewMockUnitAllocation("4", ago4h, time.Hour, nil))
  1745. ago3hAS := NewAllocationSet(ago3h, ago2h)
  1746. ago3hAS.Set(NewMockUnitAllocation("a", ago3h, time.Hour, nil))
  1747. ago2hAS := NewAllocationSet(ago2h, ago1h)
  1748. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  1749. ago1hAS := NewAllocationSet(ago1h, currentHour)
  1750. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  1751. currentHourAS := NewAllocationSet(currentHour, nextHour)
  1752. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  1753. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  1754. asr, err := asr.Accumulate(AccumulateOptionHour)
  1755. if err != nil {
  1756. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1757. }
  1758. if len(asr.Allocations) != 5 {
  1759. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  1760. }
  1761. allocMap := asr.Allocations[0].Allocations
  1762. alloc := allocMap["4"]
  1763. if alloc.Minutes() != 60.0 {
  1764. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 60.0, alloc.Minutes())
  1765. }
  1766. }
  1767. func TestAllocationSetRange_AccumulateBy_Day_From_Day(t *testing.T) {
  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. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1785. asr, err := asr.Accumulate(AccumulateOptionDay)
  1786. if err != nil {
  1787. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1788. }
  1789. if len(asr.Allocations) != 5 {
  1790. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  1791. }
  1792. allocMap := asr.Allocations[0].Allocations
  1793. alloc := allocMap["4"]
  1794. if alloc.Minutes() != 1440.0 {
  1795. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 1440.0, alloc.Minutes())
  1796. }
  1797. }
  1798. func TestAllocationSetRange_AccumulateBy_Day_From_Hours(t *testing.T) {
  1799. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  1800. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  1801. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  1802. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  1803. currentHour := time.Now().UTC().Truncate(time.Hour)
  1804. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  1805. ago4hAS := NewAllocationSet(ago4h, ago3h)
  1806. ago4hAS.Set(NewMockUnitAllocation("", ago4h, time.Hour, nil))
  1807. ago3hAS := NewAllocationSet(ago3h, ago2h)
  1808. ago3hAS.Set(NewMockUnitAllocation("", ago3h, time.Hour, nil))
  1809. ago2hAS := NewAllocationSet(ago2h, ago1h)
  1810. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  1811. ago1hAS := NewAllocationSet(ago1h, currentHour)
  1812. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  1813. currentHourAS := NewAllocationSet(currentHour, nextHour)
  1814. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  1815. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  1816. asr, err := asr.Accumulate(AccumulateOptionDay)
  1817. if err != nil {
  1818. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1819. }
  1820. if len(asr.Allocations) != 1 && len(asr.Allocations) != 2 {
  1821. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  1822. }
  1823. allocMap := asr.Allocations[0].Allocations
  1824. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  1825. if alloc.Minutes() > 300.0 {
  1826. t.Errorf("accumulating AllocationSetRange: expected %f or less minutes; actual %f", 300.0, alloc.Minutes())
  1827. }
  1828. }
  1829. func TestAllocationSetRange_AccumulateBy_Week(t *testing.T) {
  1830. ago9d := time.Now().UTC().Truncate(day).Add(-9 * day)
  1831. ago8d := time.Now().UTC().Truncate(day).Add(-8 * day)
  1832. ago7d := time.Now().UTC().Truncate(day).Add(-7 * day)
  1833. ago6d := time.Now().UTC().Truncate(day).Add(-6 * day)
  1834. ago5d := time.Now().UTC().Truncate(day).Add(-5 * day)
  1835. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  1836. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  1837. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1838. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1839. today := time.Now().UTC().Truncate(day)
  1840. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1841. ago9dAS := NewAllocationSet(ago9d, ago8d)
  1842. ago9dAS.Set(NewMockUnitAllocation("4", ago9d, day, nil))
  1843. ago8dAS := NewAllocationSet(ago8d, ago7d)
  1844. ago8dAS.Set(NewMockUnitAllocation("4", ago8d, day, nil))
  1845. ago7dAS := NewAllocationSet(ago7d, ago6d)
  1846. ago7dAS.Set(NewMockUnitAllocation("4", ago7d, day, nil))
  1847. ago6dAS := NewAllocationSet(ago6d, ago5d)
  1848. ago6dAS.Set(NewMockUnitAllocation("4", ago6d, day, nil))
  1849. ago5dAS := NewAllocationSet(ago5d, ago4d)
  1850. ago5dAS.Set(NewMockUnitAllocation("4", ago5d, day, nil))
  1851. ago4dAS := NewAllocationSet(ago4d, ago3d)
  1852. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  1853. ago3dAS := NewAllocationSet(ago3d, ago2d)
  1854. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  1855. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1856. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  1857. yesterdayAS := NewAllocationSet(yesterday, today)
  1858. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  1859. todayAS := NewAllocationSet(today, tomorrow)
  1860. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  1861. asr := NewAllocationSetRange(ago9dAS, ago8dAS, ago7dAS, ago6dAS, ago5dAS, ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  1862. asr, err := asr.Accumulate(AccumulateOptionWeek)
  1863. if err != nil {
  1864. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1865. }
  1866. if len(asr.Allocations) != 2 && len(asr.Allocations) != 3 {
  1867. t.Fatalf("expected 2 or 3 allocation sets, got:%d", len(asr.Allocations))
  1868. }
  1869. for _, as := range asr.Allocations {
  1870. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*7 {
  1871. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  1872. }
  1873. }
  1874. }
  1875. func TestAllocationSetRange_AccumulateBy_Month(t *testing.T) {
  1876. prevMonth1stDay := time.Date(2020, 01, 29, 0, 0, 0, 0, time.UTC)
  1877. prevMonth2ndDay := time.Date(2020, 01, 30, 0, 0, 0, 0, time.UTC)
  1878. prevMonth3ndDay := time.Date(2020, 01, 31, 0, 0, 0, 0, time.UTC)
  1879. nextMonth1stDay := time.Date(2020, 02, 01, 0, 0, 0, 0, time.UTC)
  1880. nextMonth2ndDay := time.Date(2020, 02, 02, 0, 0, 0, 0, time.UTC)
  1881. prev1AS := NewAllocationSet(prevMonth1stDay, prevMonth2ndDay)
  1882. prev1AS.Set(NewMockUnitAllocation("", prevMonth1stDay, day, nil))
  1883. prev2AS := NewAllocationSet(prevMonth2ndDay, prevMonth3ndDay)
  1884. prev2AS.Set(NewMockUnitAllocation("", prevMonth2ndDay, day, nil))
  1885. prev3AS := NewAllocationSet(prevMonth3ndDay, nextMonth1stDay)
  1886. prev3AS.Set(NewMockUnitAllocation("", prevMonth3ndDay, day, nil))
  1887. nextAS := NewAllocationSet(nextMonth1stDay, nextMonth2ndDay)
  1888. nextAS.Set(NewMockUnitAllocation("", nextMonth1stDay, day, nil))
  1889. asr := NewAllocationSetRange(prev1AS, prev2AS, prev3AS, nextAS)
  1890. asr, err := asr.Accumulate(AccumulateOptionMonth)
  1891. if err != nil {
  1892. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  1893. }
  1894. if len(asr.Allocations) != 2 {
  1895. t.Fatalf("expected 2 allocation sets, got:%d", len(asr.Allocations))
  1896. }
  1897. for _, as := range asr.Allocations {
  1898. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*31 {
  1899. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  1900. }
  1901. }
  1902. }
  1903. // TODO niko/etl
  1904. // func TestAllocationSetRange_AggregateBy(t *testing.T) {}
  1905. // TODO niko/etl
  1906. // func TestAllocationSetRange_Append(t *testing.T) {}
  1907. // TODO niko/etl
  1908. // func TestAllocationSetRange_Each(t *testing.T) {}
  1909. // TODO niko/etl
  1910. // func TestAllocationSetRange_Get(t *testing.T) {}
  1911. func TestAllocationSetRange_InsertRange(t *testing.T) {
  1912. // Set up
  1913. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1914. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1915. today := time.Now().UTC().Truncate(day)
  1916. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1917. unit := NewMockUnitAllocation("", today, day, nil)
  1918. ago2dAS := NewAllocationSet(ago2d, yesterday)
  1919. ago2dAS.Set(NewMockUnitAllocation("a", ago2d, day, nil))
  1920. ago2dAS.Set(NewMockUnitAllocation("b", ago2d, day, nil))
  1921. ago2dAS.Set(NewMockUnitAllocation("c", ago2d, day, nil))
  1922. yesterdayAS := NewAllocationSet(yesterday, today)
  1923. yesterdayAS.Set(NewMockUnitAllocation("a", yesterday, day, nil))
  1924. yesterdayAS.Set(NewMockUnitAllocation("b", yesterday, day, nil))
  1925. yesterdayAS.Set(NewMockUnitAllocation("c", yesterday, day, nil))
  1926. todayAS := NewAllocationSet(today, tomorrow)
  1927. todayAS.Set(NewMockUnitAllocation("a", today, day, nil))
  1928. todayAS.Set(NewMockUnitAllocation("b", today, day, nil))
  1929. todayAS.Set(NewMockUnitAllocation("c", today, day, nil))
  1930. var nilASR *AllocationSetRange
  1931. thisASR := NewAllocationSetRange(yesterdayAS.Clone(), todayAS.Clone())
  1932. thatASR := NewAllocationSetRange(yesterdayAS.Clone())
  1933. longASR := NewAllocationSetRange(ago2dAS.Clone(), yesterdayAS.Clone(), todayAS.Clone())
  1934. var err error
  1935. // Expect an error calling InsertRange on nil
  1936. err = nilASR.InsertRange(thatASR)
  1937. if err == nil {
  1938. t.Fatalf("expected error, got nil")
  1939. }
  1940. // Expect nothing to happen calling InsertRange(nil) on non-nil ASR
  1941. err = thisASR.InsertRange(nil)
  1942. if err != nil {
  1943. t.Fatalf("unexpected error: %s", err)
  1944. }
  1945. for _, as := range thisASR.Allocations {
  1946. for k, a := range as.Allocations {
  1947. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  1948. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  1949. }
  1950. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  1951. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  1952. }
  1953. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  1954. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  1955. }
  1956. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  1957. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  1958. }
  1959. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  1960. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  1961. }
  1962. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  1963. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  1964. }
  1965. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  1966. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  1967. }
  1968. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  1969. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  1970. }
  1971. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  1972. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  1973. }
  1974. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  1975. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  1976. }
  1977. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  1978. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  1979. }
  1980. }
  1981. }
  1982. // Expect an error calling InsertRange with a range exceeding the receiver
  1983. err = thisASR.InsertRange(longASR)
  1984. if err == nil {
  1985. t.Fatalf("expected error calling InsertRange with a range exceeding the receiver")
  1986. }
  1987. // Expect each Allocation in "today" to stay the same, but "yesterday" to
  1988. // precisely double when inserting a range that only has a duplicate of
  1989. // "yesterday", but no entry for "today"
  1990. err = thisASR.InsertRange(thatASR)
  1991. if err != nil {
  1992. t.Fatalf("unexpected error: %s", err)
  1993. }
  1994. yAS, err := thisASR.Get(0)
  1995. for k, a := range yAS.Allocations {
  1996. if !util.IsApproximately(a.CPUCoreHours, 2*unit.CPUCoreHours) {
  1997. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  1998. }
  1999. if !util.IsApproximately(a.CPUCost, 2*unit.CPUCost) {
  2000. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2001. }
  2002. if !util.IsApproximately(a.RAMByteHours, 2*unit.RAMByteHours) {
  2003. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2004. }
  2005. if !util.IsApproximately(a.RAMCost, 2*unit.RAMCost) {
  2006. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2007. }
  2008. if !util.IsApproximately(a.GPUHours, 2*unit.GPUHours) {
  2009. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2010. }
  2011. if !util.IsApproximately(a.GPUCost, 2*unit.GPUCost) {
  2012. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2013. }
  2014. if !util.IsApproximately(a.PVByteHours(), 2*unit.PVByteHours()) {
  2015. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2016. }
  2017. if !util.IsApproximately(a.PVCost(), 2*unit.PVCost()) {
  2018. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2019. }
  2020. if !util.IsApproximately(a.NetworkCost, 2*unit.NetworkCost) {
  2021. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2022. }
  2023. if !util.IsApproximately(a.LoadBalancerCost, 2*unit.LoadBalancerCost) {
  2024. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2025. }
  2026. if !util.IsApproximately(a.TotalCost(), 2*unit.TotalCost()) {
  2027. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2028. }
  2029. }
  2030. tAS, err := thisASR.Get(1)
  2031. for k, a := range tAS.Allocations {
  2032. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2033. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2034. }
  2035. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2036. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2037. }
  2038. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2039. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2040. }
  2041. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2042. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2043. }
  2044. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2045. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2046. }
  2047. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2048. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2049. }
  2050. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2051. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2052. }
  2053. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2054. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2055. }
  2056. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2057. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2058. }
  2059. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2060. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2061. }
  2062. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2063. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2064. }
  2065. }
  2066. }
  2067. // TODO niko/etl
  2068. // func TestAllocationSetRange_Length(t *testing.T) {}
  2069. func TestAllocationSetRange_MarshalJSON(t *testing.T) {
  2070. tests := []struct {
  2071. name string
  2072. arg *AllocationSetRange
  2073. expected *AllocationSetRange
  2074. }{
  2075. {
  2076. name: "Nil ASR",
  2077. arg: nil,
  2078. },
  2079. {
  2080. name: "Nil AS in ASR",
  2081. arg: NewAllocationSetRange(nil),
  2082. },
  2083. {
  2084. name: "Normal ASR",
  2085. arg: &AllocationSetRange{
  2086. Allocations: []*AllocationSet{
  2087. {
  2088. Allocations: map[string]*Allocation{
  2089. "a": {
  2090. Start: time.Now().UTC().Truncate(day),
  2091. },
  2092. },
  2093. },
  2094. },
  2095. },
  2096. },
  2097. }
  2098. for _, test := range tests {
  2099. bytes, err := json.Marshal(test.arg)
  2100. if err != nil {
  2101. t.Fatalf("ASR Marshal: test %s, unexpected error: %s", test.name, err)
  2102. }
  2103. var testASR []*AllocationSet
  2104. marshaled := &testASR
  2105. err = json.Unmarshal(bytes, marshaled)
  2106. if err != nil {
  2107. t.Fatalf("ASR Unmarshal: test %s: unexpected error: %s", test.name, err)
  2108. }
  2109. if test.arg.Length() != len(testASR) {
  2110. t.Fatalf("ASR Unmarshal: test %s: length mutated in encoding: expected %d but got %d", test.name, test.arg.Length(), len(testASR))
  2111. }
  2112. // Allocations don't unmarshal back from json
  2113. }
  2114. }
  2115. // TODO niko/etl
  2116. // func TestAllocationSetRange_Slice(t *testing.T) {}
  2117. // TODO niko/etl
  2118. // func TestAllocationSetRange_Window(t *testing.T) {}
  2119. func TestAllocationSetRange_Start(t *testing.T) {
  2120. tests := []struct {
  2121. name string
  2122. arg *AllocationSetRange
  2123. expectError bool
  2124. expected time.Time
  2125. }{
  2126. {
  2127. name: "Empty ASR",
  2128. arg: nil,
  2129. expectError: true,
  2130. },
  2131. {
  2132. name: "Single allocation",
  2133. arg: &AllocationSetRange{
  2134. Allocations: []*AllocationSet{
  2135. {
  2136. Allocations: map[string]*Allocation{
  2137. "a": {
  2138. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2139. },
  2140. },
  2141. },
  2142. },
  2143. },
  2144. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2145. },
  2146. {
  2147. name: "Two allocations",
  2148. arg: &AllocationSetRange{
  2149. Allocations: []*AllocationSet{
  2150. {
  2151. Allocations: map[string]*Allocation{
  2152. "a": {
  2153. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2154. },
  2155. "b": {
  2156. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2157. },
  2158. },
  2159. },
  2160. },
  2161. },
  2162. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2163. },
  2164. {
  2165. name: "Two AllocationSets",
  2166. arg: &AllocationSetRange{
  2167. Allocations: []*AllocationSet{
  2168. {
  2169. Allocations: map[string]*Allocation{
  2170. "a": {
  2171. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2172. },
  2173. },
  2174. },
  2175. {
  2176. Allocations: map[string]*Allocation{
  2177. "b": {
  2178. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2179. },
  2180. },
  2181. },
  2182. },
  2183. },
  2184. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2185. },
  2186. }
  2187. for _, test := range tests {
  2188. result, err := test.arg.Start()
  2189. if test.expectError && err != nil {
  2190. continue
  2191. }
  2192. if test.expectError && err == nil {
  2193. t.Errorf("%s: expected error and got none", test.name)
  2194. } else if result != test.expected {
  2195. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2196. }
  2197. }
  2198. }
  2199. func TestAllocationSetRange_End(t *testing.T) {
  2200. tests := []struct {
  2201. name string
  2202. arg *AllocationSetRange
  2203. expectError bool
  2204. expected time.Time
  2205. }{
  2206. {
  2207. name: "Empty ASR",
  2208. arg: nil,
  2209. expectError: true,
  2210. },
  2211. {
  2212. name: "Single allocation",
  2213. arg: &AllocationSetRange{
  2214. Allocations: []*AllocationSet{
  2215. {
  2216. Allocations: map[string]*Allocation{
  2217. "a": {
  2218. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2219. },
  2220. },
  2221. },
  2222. },
  2223. },
  2224. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2225. },
  2226. {
  2227. name: "Two allocations",
  2228. arg: &AllocationSetRange{
  2229. Allocations: []*AllocationSet{
  2230. {
  2231. Allocations: map[string]*Allocation{
  2232. "a": {
  2233. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2234. },
  2235. "b": {
  2236. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2237. },
  2238. },
  2239. },
  2240. },
  2241. },
  2242. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2243. },
  2244. {
  2245. name: "Two AllocationSets",
  2246. arg: &AllocationSetRange{
  2247. Allocations: []*AllocationSet{
  2248. {
  2249. Allocations: map[string]*Allocation{
  2250. "a": {
  2251. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2252. },
  2253. },
  2254. },
  2255. {
  2256. Allocations: map[string]*Allocation{
  2257. "b": {
  2258. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2259. },
  2260. },
  2261. },
  2262. },
  2263. },
  2264. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2265. },
  2266. }
  2267. for _, test := range tests {
  2268. result, err := test.arg.End()
  2269. if test.expectError && err != nil {
  2270. continue
  2271. }
  2272. if test.expectError && err == nil {
  2273. t.Errorf("%s: expected error and got none", test.name)
  2274. } else if result != test.expected {
  2275. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2276. }
  2277. }
  2278. }
  2279. func TestAllocationSetRange_Minutes(t *testing.T) {
  2280. tests := []struct {
  2281. name string
  2282. arg *AllocationSetRange
  2283. expected float64
  2284. }{
  2285. {
  2286. name: "Empty ASR",
  2287. arg: nil,
  2288. expected: 0,
  2289. },
  2290. {
  2291. name: "Single allocation",
  2292. arg: &AllocationSetRange{
  2293. Allocations: []*AllocationSet{
  2294. {
  2295. Allocations: map[string]*Allocation{
  2296. "a": {
  2297. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2298. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2299. },
  2300. },
  2301. },
  2302. },
  2303. },
  2304. expected: 24 * 60,
  2305. },
  2306. {
  2307. name: "Two allocations",
  2308. arg: &AllocationSetRange{
  2309. Allocations: []*AllocationSet{
  2310. {
  2311. Allocations: map[string]*Allocation{
  2312. "a": {
  2313. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2314. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2315. },
  2316. "b": {
  2317. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2318. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  2319. },
  2320. },
  2321. },
  2322. },
  2323. },
  2324. expected: 2 * 24 * 60,
  2325. },
  2326. {
  2327. name: "Two AllocationSets",
  2328. arg: &AllocationSetRange{
  2329. Allocations: []*AllocationSet{
  2330. {
  2331. Allocations: map[string]*Allocation{
  2332. "a": {
  2333. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2334. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2335. },
  2336. },
  2337. },
  2338. {
  2339. Allocations: map[string]*Allocation{
  2340. "b": {
  2341. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2342. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  2343. },
  2344. },
  2345. },
  2346. },
  2347. },
  2348. expected: 2 * 24 * 60,
  2349. },
  2350. }
  2351. for _, test := range tests {
  2352. result := test.arg.Minutes()
  2353. if result != test.expected {
  2354. t.Errorf("%s: expected %f but got %f", test.name, test.expected, result)
  2355. }
  2356. }
  2357. }
  2358. func TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate(t *testing.T) {
  2359. today := time.Now().Round(day)
  2360. start := today.AddDate(0, 0, -4)
  2361. var allocationSets []*AllocationSet
  2362. for i := 0; i < 4; i++ {
  2363. allocationSets = append(allocationSets, GenerateMockAllocationSet(start))
  2364. start = start.AddDate(0, 0, 1)
  2365. }
  2366. var originalAllocationSets []*AllocationSet
  2367. for _, as := range allocationSets {
  2368. originalAllocationSets = append(originalAllocationSets, as.Clone())
  2369. }
  2370. asr := NewAllocationSetRange()
  2371. for _, as := range allocationSets {
  2372. asr.Append(as.Clone())
  2373. }
  2374. expected, err := asr.accumulate()
  2375. if err != nil {
  2376. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: AllocationSetRange.Accumulate() returned an error\n")
  2377. }
  2378. var got *AllocationSet
  2379. for i := 0; i < len(allocationSets); i++ {
  2380. got, err = got.Accumulate(allocationSets[i])
  2381. if err != nil {
  2382. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Accumulate(allocationSets[%d]) returned an error\n", i)
  2383. }
  2384. }
  2385. // compare the got and expected Allocation sets, ensure that they match
  2386. if len(got.Allocations) != len(expected.Allocations) {
  2387. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.Allocations does not match length of expected.Allocations\n")
  2388. }
  2389. for key, a := range got.Allocations {
  2390. if _, ok := expected.Allocations[key]; !ok {
  2391. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] not found in expected.Allocations\n", key)
  2392. }
  2393. if !a.Equal(expected.Allocations[key]) {
  2394. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] did not match expected.Allocations[%[1]s]", key)
  2395. }
  2396. }
  2397. if len(got.ExternalKeys) != len(expected.ExternalKeys) {
  2398. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.ExternalKeys does not match length of expected.ExternalKeys\n")
  2399. }
  2400. if len(got.IdleKeys) != len(expected.IdleKeys) {
  2401. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.IdleKeys does not match length of expected.IdleKeys\n")
  2402. }
  2403. if !got.Window.Start().UTC().Equal(expected.Window.Start().UTC()) {
  2404. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.start: got:%s, expected:%s\n", got.Window.Start(), expected.Window.Start())
  2405. }
  2406. if !got.Window.End().UTC().Equal(expected.Window.End().UTC()) {
  2407. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.end: got:%s, expected:%s\n", got.Window.End(), expected.Window.End())
  2408. }
  2409. for i := range allocationSets {
  2410. for key, allocation := range allocationSets[i].Allocations {
  2411. if !allocation.Equal(originalAllocationSets[i].Allocations[key]) {
  2412. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: allocationSet has been mutated in Accumulate; allocationSet: %d, allocation: %s\n", i, key)
  2413. }
  2414. }
  2415. }
  2416. }