allocation_test.go 102 KB

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