allocation_test.go 132 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072
  1. package opencost
  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/core/pkg/filter"
  11. "github.com/opencost/opencost/core/pkg/filter/allocation"
  12. "github.com/opencost/opencost/core/pkg/filter/ast"
  13. "github.com/opencost/opencost/core/pkg/filter/ops"
  14. "github.com/opencost/opencost/core/pkg/log"
  15. "github.com/opencost/opencost/core/pkg/util"
  16. "github.com/opencost/opencost/core/pkg/util/json"
  17. "github.com/opencost/opencost/core/pkg/util/timeutil"
  18. )
  19. var filterParser = allocation.NewAllocationFilterParser()
  20. var matcherCompiler = NewAllocationMatchCompiler(nil)
  21. // useful for creating filters on the fly when testing. panics
  22. // on parse errors!
  23. func mustParseFilter(s string) filter.Filter {
  24. filter, err := filterParser.Parse(s)
  25. if err != nil {
  26. panic(err)
  27. }
  28. return filter
  29. }
  30. // useful for creating filters on the fly when testing. panics
  31. // on parse or compile errors!
  32. func mustCompileFilter(s string) AllocationMatcher {
  33. filter := mustParseFilter(s)
  34. m, err := matcherCompiler.Compile(filter)
  35. if err != nil {
  36. panic(err)
  37. }
  38. return m
  39. }
  40. func TestAllocation_Add(t *testing.T) {
  41. var nilAlloc *Allocation
  42. zeroAlloc := &Allocation{}
  43. // nil + nil == nil
  44. nilNilSum, err := nilAlloc.Add(nilAlloc)
  45. if err != nil {
  46. t.Fatalf("Allocation.Add unexpected error: %s", err)
  47. }
  48. if nilNilSum != nil {
  49. t.Fatalf("Allocation.Add failed; exp: nil; act: %s", nilNilSum)
  50. }
  51. // nil + zero == zero
  52. nilZeroSum, err := nilAlloc.Add(zeroAlloc)
  53. if err != nil {
  54. t.Fatalf("Allocation.Add unexpected error: %s", err)
  55. }
  56. if nilZeroSum == nil || nilZeroSum.TotalCost() != 0.0 {
  57. t.Fatalf("Allocation.Add failed; exp: 0.0; act: %s", nilZeroSum)
  58. }
  59. cpuPrice := 0.02
  60. gpuPrice := 2.00
  61. ramPrice := 0.01
  62. pvPrice := 0.00005
  63. gib := 1024.0 * 1024.0 * 1024.0
  64. s1 := time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC)
  65. e1 := time.Date(2021, time.January, 1, 12, 0, 0, 0, time.UTC)
  66. hrs1 := e1.Sub(s1).Hours()
  67. a1 := &Allocation{
  68. Start: s1,
  69. End: e1,
  70. Properties: &AllocationProperties{},
  71. CPUCoreHours: 2.0 * hrs1,
  72. CPUCoreRequestAverage: 2.0,
  73. CPUCoreUsageAverage: 1.0,
  74. CPUCost: 2.0 * hrs1 * cpuPrice,
  75. CPUCostAdjustment: 3.0,
  76. GPUHours: 1.0 * hrs1,
  77. GPUCost: 1.0 * hrs1 * gpuPrice,
  78. GPUCostAdjustment: 2.0,
  79. PVs: PVAllocations{
  80. disk: {
  81. ByteHours: 100.0 * gib * hrs1,
  82. Cost: 100.0 * hrs1 * pvPrice,
  83. },
  84. },
  85. PVCostAdjustment: 4.0,
  86. RAMByteHours: 8.0 * gib * hrs1,
  87. RAMBytesRequestAverage: 8.0 * gib,
  88. RAMBytesUsageAverage: 4.0 * gib,
  89. RAMCost: 8.0 * hrs1 * ramPrice,
  90. RAMCostAdjustment: 1.0,
  91. SharedCost: 2.00,
  92. ExternalCost: 1.00,
  93. RawAllocationOnly: &RawAllocationOnlyData{},
  94. }
  95. a1b := a1.Clone()
  96. s2 := time.Date(2021, time.January, 1, 6, 0, 0, 0, time.UTC)
  97. e2 := time.Date(2021, time.January, 1, 24, 0, 0, 0, time.UTC)
  98. hrs2 := e1.Sub(s1).Hours()
  99. a2 := &Allocation{
  100. Start: s2,
  101. End: e2,
  102. Properties: &AllocationProperties{},
  103. CPUCoreHours: 1.0 * hrs2,
  104. CPUCoreRequestAverage: 1.0,
  105. CPUCoreUsageAverage: 1.0,
  106. CPUCost: 1.0 * hrs2 * cpuPrice,
  107. GPUHours: 0.0,
  108. GPUCost: 0.0,
  109. RAMByteHours: 8.0 * gib * hrs2,
  110. RAMBytesRequestAverage: 0.0,
  111. RAMBytesUsageAverage: 8.0 * gib,
  112. RAMCost: 8.0 * hrs2 * ramPrice,
  113. NetworkCost: 0.01,
  114. LoadBalancerCost: 0.05,
  115. SharedCost: 0.00,
  116. ExternalCost: 1.00,
  117. RawAllocationOnly: &RawAllocationOnlyData{},
  118. }
  119. a2b := a2.Clone()
  120. act, err := a1.Add(a2)
  121. if err != nil {
  122. t.Fatalf("Allocation.Add: unexpected error: %s", err)
  123. }
  124. // Neither Allocation should be mutated
  125. if !a1.Equal(a1b) {
  126. t.Fatalf("Allocation.Add: a1 illegally mutated")
  127. }
  128. if !a2.Equal(a2b) {
  129. t.Fatalf("Allocation.Add: a1 illegally mutated")
  130. }
  131. // Costs should be cumulative
  132. if !util.IsApproximately(a1.TotalCost()+a2.TotalCost(), act.TotalCost()) {
  133. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.TotalCost()+a2.TotalCost(), act.TotalCost())
  134. }
  135. if !util.IsApproximately(a1.CPUCost+a2.CPUCost, act.CPUCost) {
  136. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.CPUCost+a2.CPUCost, act.CPUCost)
  137. }
  138. if !util.IsApproximately(a1.CPUCostAdjustment+a2.CPUCostAdjustment, act.CPUCostAdjustment) {
  139. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.CPUCostAdjustment+a2.CPUCostAdjustment, act.CPUCostAdjustment)
  140. }
  141. if !util.IsApproximately(a1.GPUCost+a2.GPUCost, act.GPUCost) {
  142. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.GPUCost+a2.GPUCost, act.GPUCost)
  143. }
  144. if !util.IsApproximately(a1.GPUCostAdjustment+a2.GPUCostAdjustment, act.GPUCostAdjustment) {
  145. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.GPUCostAdjustment+a2.GPUCostAdjustment, act.GPUCostAdjustment)
  146. }
  147. if !util.IsApproximately(a1.RAMCost+a2.RAMCost, act.RAMCost) {
  148. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.RAMCost+a2.RAMCost, act.RAMCost)
  149. }
  150. if !util.IsApproximately(a1.RAMCostAdjustment+a2.RAMCostAdjustment, act.RAMCostAdjustment) {
  151. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.RAMCostAdjustment+a2.RAMCostAdjustment, act.RAMCostAdjustment)
  152. }
  153. if !util.IsApproximately(a1.PVCost()+a2.PVCost(), act.PVCost()) {
  154. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.PVCost()+a2.PVCost(), act.PVCost())
  155. }
  156. if !util.IsApproximately(a1.NetworkCost+a2.NetworkCost, act.NetworkCost) {
  157. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.NetworkCost+a2.NetworkCost, act.NetworkCost)
  158. }
  159. if !util.IsApproximately(a1.LoadBalancerCost+a2.LoadBalancerCost, act.LoadBalancerCost) {
  160. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.LoadBalancerCost+a2.LoadBalancerCost, act.LoadBalancerCost)
  161. }
  162. if !util.IsApproximately(a1.SharedCost+a2.SharedCost, act.SharedCost) {
  163. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.SharedCost+a2.SharedCost, act.SharedCost)
  164. }
  165. if !util.IsApproximately(a1.ExternalCost+a2.ExternalCost, act.ExternalCost) {
  166. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.ExternalCost+a2.ExternalCost, act.ExternalCost)
  167. }
  168. // ResourceHours should be cumulative
  169. if !util.IsApproximately(a1.CPUCoreHours+a2.CPUCoreHours, act.CPUCoreHours) {
  170. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.CPUCoreHours+a2.CPUCoreHours, act.CPUCoreHours)
  171. }
  172. if !util.IsApproximately(a1.RAMByteHours+a2.RAMByteHours, act.RAMByteHours) {
  173. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.RAMByteHours+a2.RAMByteHours, act.RAMByteHours)
  174. }
  175. if !util.IsApproximately(a1.PVByteHours()+a2.PVByteHours(), act.PVByteHours()) {
  176. t.Fatalf("Allocation.Add: expected %f; actual %f", a1.PVByteHours()+a2.PVByteHours(), act.PVByteHours())
  177. }
  178. // Minutes should be the duration between min(starts) and max(ends)
  179. if !act.Start.Equal(a1.Start) || !act.End.Equal(a2.End) {
  180. t.Fatalf("Allocation.Add: expected %s; actual %s", NewWindow(&a1.Start, &a2.End), NewWindow(&act.Start, &act.End))
  181. }
  182. if act.Minutes() != 1440.0 {
  183. t.Fatalf("Allocation.Add: expected %f; actual %f", 1440.0, act.Minutes())
  184. }
  185. // Requests and Usage should be averaged correctly
  186. // CPU requests = (2.0*12.0 + 1.0*18.0)/(24.0) = 1.75
  187. // CPU usage = (1.0*12.0 + 1.0*18.0)/(24.0) = 1.25
  188. // RAM requests = (8.0*12.0 + 0.0*18.0)/(24.0) = 4.00
  189. // RAM usage = (4.0*12.0 + 8.0*18.0)/(24.0) = 8.00
  190. if !util.IsApproximately(1.75, act.CPUCoreRequestAverage) {
  191. t.Fatalf("Allocation.Add: expected %f; actual %f", 1.75, act.CPUCoreRequestAverage)
  192. }
  193. if !util.IsApproximately(1.25, act.CPUCoreUsageAverage) {
  194. t.Fatalf("Allocation.Add: expected %f; actual %f", 1.25, act.CPUCoreUsageAverage)
  195. }
  196. if !util.IsApproximately(4.00*gib, act.RAMBytesRequestAverage) {
  197. t.Fatalf("Allocation.Add: expected %f; actual %f", 4.00*gib, act.RAMBytesRequestAverage)
  198. }
  199. if !util.IsApproximately(8.00*gib, act.RAMBytesUsageAverage) {
  200. t.Fatalf("Allocation.Add: expected %f; actual %f", 8.00*gib, act.RAMBytesUsageAverage)
  201. }
  202. // Efficiency should be computed accurately from new request/usage
  203. // CPU efficiency = 1.25/1.75 = 0.7142857
  204. // RAM efficiency = 8.00/4.00 = 2.0000000
  205. // Total efficiency = (0.7142857*0.72 + 2.0*1.92)/(2.64) = 1.6493506
  206. if !util.IsApproximately(0.7142857, act.CPUEfficiency()) {
  207. t.Fatalf("Allocation.Add: expected %f; actual %f", 0.7142857, act.CPUEfficiency())
  208. }
  209. if !util.IsApproximately(2.0000000, act.RAMEfficiency()) {
  210. t.Fatalf("Allocation.Add: expected %f; actual %f", 2.0000000, act.RAMEfficiency())
  211. }
  212. if !util.IsApproximately(1.279690, act.TotalEfficiency()) {
  213. t.Fatalf("Allocation.Add: expected %f; actual %f", 1.279690, act.TotalEfficiency())
  214. }
  215. if act.RawAllocationOnly != nil {
  216. t.Errorf("Allocation.Add: Raw only data must be nil after an add")
  217. }
  218. // Test GPUAllocation merging edge cases:
  219. // Case A: Receiver has nil GPUAllocation, incoming has non-nil GPUAllocation
  220. g1 := &Allocation{
  221. Start: s1,
  222. End: e1,
  223. Window: NewWindow(&s1, &e1),
  224. Properties: &AllocationProperties{},
  225. }
  226. gpuReqVal := 1.0
  227. gpuUseVal := 0.5
  228. g2 := &Allocation{
  229. Start: s2,
  230. End: e2,
  231. Window: NewWindow(&s2, &e2),
  232. Properties: &AllocationProperties{},
  233. GPUAllocation: &GPUAllocation{
  234. GPUDevice: "nvidia-tesla-t4",
  235. GPURequestAverage: &gpuReqVal,
  236. GPUUsageAverage: &gpuUseVal,
  237. },
  238. }
  239. actG, err := g1.Add(g2)
  240. if err != nil {
  241. t.Fatalf("Allocation.Add: unexpected error: %s", err)
  242. }
  243. if actG.GPUAllocation == nil {
  244. t.Fatalf("Allocation.Add: expected non-nil GPUAllocation from merge")
  245. }
  246. if actG.GPUAllocation.GPUDevice != "nvidia-tesla-t4" {
  247. t.Errorf("Allocation.Add: expected GPUDevice 'nvidia-tesla-t4', got %s", actG.GPUAllocation.GPUDevice)
  248. }
  249. if actG.GPUAllocation.GPURequestAverage == nil || !util.IsApproximately(0.75, *actG.GPUAllocation.GPURequestAverage) {
  250. t.Errorf("Allocation.Add: expected GPURequestAverage 0.75, got %v", actG.GPUAllocation.GPURequestAverage)
  251. }
  252. if actG.GPUAllocation.GPUUsageAverage == nil || !util.IsApproximately(0.375, *actG.GPUAllocation.GPUUsageAverage) {
  253. t.Errorf("Allocation.Add: expected GPUUsageAverage 0.375, got %v", actG.GPUAllocation.GPUUsageAverage)
  254. }
  255. }
  256. func TestAllocation_Share(t *testing.T) {
  257. cpuPrice := 0.02
  258. gpuPrice := 2.00
  259. ramPrice := 0.01
  260. pvPrice := 0.00005
  261. gib := 1024.0 * 1024.0 * 1024.0
  262. s1 := time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC)
  263. e1 := time.Date(2021, time.January, 1, 12, 0, 0, 0, time.UTC)
  264. hrs1 := e1.Sub(s1).Hours()
  265. a1 := &Allocation{
  266. Start: s1,
  267. End: e1,
  268. Properties: &AllocationProperties{},
  269. CPUCoreHours: 2.0 * hrs1,
  270. CPUCoreRequestAverage: 2.0,
  271. CPUCoreUsageAverage: 1.0,
  272. CPUCost: 2.0 * hrs1 * cpuPrice,
  273. CPUCostAdjustment: 3.0,
  274. GPUHours: 1.0 * hrs1,
  275. GPUCost: 1.0 * hrs1 * gpuPrice,
  276. GPUCostAdjustment: 2.0,
  277. PVs: PVAllocations{
  278. disk: {
  279. ByteHours: 100.0 * gib * hrs1,
  280. Cost: 100.0 * hrs1 * pvPrice,
  281. },
  282. },
  283. PVCostAdjustment: 4.0,
  284. RAMByteHours: 8.0 * gib * hrs1,
  285. RAMBytesRequestAverage: 8.0 * gib,
  286. RAMBytesUsageAverage: 4.0 * gib,
  287. RAMCost: 8.0 * hrs1 * ramPrice,
  288. RAMCostAdjustment: 1.0,
  289. SharedCost: 2.00,
  290. ExternalCost: 1.00,
  291. }
  292. a1b := a1.Clone()
  293. s2 := time.Date(2021, time.January, 1, 6, 0, 0, 0, time.UTC)
  294. e2 := time.Date(2021, time.January, 1, 24, 0, 0, 0, time.UTC)
  295. hrs2 := e1.Sub(s1).Hours()
  296. a2 := &Allocation{
  297. Start: s2,
  298. End: e2,
  299. Properties: &AllocationProperties{},
  300. CPUCoreHours: 1.0 * hrs2,
  301. CPUCoreRequestAverage: 1.0,
  302. CPUCoreUsageAverage: 1.0,
  303. CPUCost: 1.0 * hrs2 * cpuPrice,
  304. GPUHours: 0.0,
  305. GPUCost: 0.0,
  306. RAMByteHours: 8.0 * gib * hrs2,
  307. RAMBytesRequestAverage: 0.0,
  308. RAMBytesUsageAverage: 8.0 * gib,
  309. RAMCost: 8.0 * hrs2 * ramPrice,
  310. NetworkCost: 0.01,
  311. LoadBalancerCost: 0.05,
  312. SharedCost: 0.00,
  313. ExternalCost: 1.00,
  314. }
  315. a2b := a2.Clone()
  316. act, err := a1.Share(a2)
  317. if err != nil {
  318. t.Fatalf("Allocation.Share: unexpected error: %s", err)
  319. }
  320. // Neither Allocation should be mutated
  321. if !a1.Equal(a1b) {
  322. t.Fatalf("Allocation.Share: a1 illegally mutated")
  323. }
  324. if !a2.Equal(a2b) {
  325. t.Fatalf("Allocation.Share: a1 illegally mutated")
  326. }
  327. // SharedCost and TotalCost should reflect increase by a2.TotalCost
  328. if !util.IsApproximately(a1.TotalCost()+a2.TotalCost(), act.TotalCost()) {
  329. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.TotalCost()+a2.TotalCost(), act.TotalCost())
  330. }
  331. if !util.IsApproximately(a1.SharedCost+a2.TotalCost(), act.SharedCost) {
  332. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.SharedCost+a2.TotalCost(), act.SharedCost)
  333. }
  334. // Costs should match before (expect TotalCost and SharedCost)
  335. if !util.IsApproximately(a1.CPUTotalCost(), act.CPUTotalCost()) {
  336. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUTotalCost(), act.CPUTotalCost())
  337. }
  338. if !util.IsApproximately(a1.GPUTotalCost(), act.GPUTotalCost()) {
  339. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.GPUTotalCost(), act.GPUTotalCost())
  340. }
  341. if !util.IsApproximately(a1.RAMTotalCost(), act.RAMTotalCost()) {
  342. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMTotalCost(), act.RAMTotalCost())
  343. }
  344. if !util.IsApproximately(a1.PVTotalCost(), act.PVTotalCost()) {
  345. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.PVTotalCost(), act.PVTotalCost())
  346. }
  347. if !util.IsApproximately(a1.NetworkCost, act.NetworkCost) {
  348. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.NetworkCost, act.NetworkCost)
  349. }
  350. if !util.IsApproximately(a1.LoadBalancerCost, act.LoadBalancerCost) {
  351. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.LoadBalancerCost, act.LoadBalancerCost)
  352. }
  353. if !util.IsApproximately(a1.ExternalCost, act.ExternalCost) {
  354. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.ExternalCost, act.ExternalCost)
  355. }
  356. // ResourceHours should match before
  357. if !util.IsApproximately(a1.CPUCoreHours, act.CPUCoreHours) {
  358. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUCoreHours, act.CPUCoreHours)
  359. }
  360. if !util.IsApproximately(a1.RAMByteHours, act.RAMByteHours) {
  361. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMByteHours, act.RAMByteHours)
  362. }
  363. if !util.IsApproximately(a1.PVByteHours(), act.PVByteHours()) {
  364. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.PVByteHours(), act.PVByteHours())
  365. }
  366. // Minutes should match before
  367. if !act.Start.Equal(a1.Start) || !act.End.Equal(a1.End) {
  368. t.Fatalf("Allocation.Share: expected %s; actual %s", NewWindow(&a1.Start, &a1.End), NewWindow(&act.Start, &act.End))
  369. }
  370. if act.Minutes() != a1.Minutes() {
  371. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.Minutes(), act.Minutes())
  372. }
  373. // Requests and Usage should match before
  374. if !util.IsApproximately(a1.CPUCoreRequestAverage, act.CPUCoreRequestAverage) {
  375. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUCoreRequestAverage, act.CPUCoreRequestAverage)
  376. }
  377. if !util.IsApproximately(a1.CPUCoreUsageAverage, act.CPUCoreUsageAverage) {
  378. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUCoreUsageAverage, act.CPUCoreUsageAverage)
  379. }
  380. if !util.IsApproximately(a1.RAMBytesRequestAverage, act.RAMBytesRequestAverage) {
  381. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMBytesRequestAverage, act.RAMBytesRequestAverage)
  382. }
  383. if !util.IsApproximately(a1.RAMBytesUsageAverage, act.RAMBytesUsageAverage) {
  384. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMBytesUsageAverage, act.RAMBytesUsageAverage)
  385. }
  386. // Efficiency should match before
  387. if !util.IsApproximately(a1.CPUEfficiency(), act.CPUEfficiency()) {
  388. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.CPUEfficiency(), act.CPUEfficiency())
  389. }
  390. if !util.IsApproximately(a1.RAMEfficiency(), act.RAMEfficiency()) {
  391. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.RAMEfficiency(), act.RAMEfficiency())
  392. }
  393. if !util.IsApproximately(a1.TotalEfficiency(), act.TotalEfficiency()) {
  394. t.Fatalf("Allocation.Share: expected %f; actual %f", a1.TotalEfficiency(), act.TotalEfficiency())
  395. }
  396. }
  397. func TestAllocation_AddDifferentController(t *testing.T) {
  398. a1 := &Allocation{
  399. Properties: &AllocationProperties{
  400. Container: "container",
  401. Pod: "pod",
  402. Namespace: "ns",
  403. Cluster: "cluster",
  404. Controller: "controller 1",
  405. },
  406. }
  407. a2 := a1.Clone()
  408. a2.Properties.Controller = "controller 2"
  409. result, err := a1.Add(a2)
  410. if err != nil {
  411. t.Fatalf("Allocation.Add: unexpected error: %s", err)
  412. }
  413. if result.Properties.Controller == "" {
  414. t.Errorf("Adding allocations whose properties only differ in controller name should not result in an empty string controller name.")
  415. }
  416. }
  417. func TestAllocationSet_generateKey(t *testing.T) {
  418. var alloc *Allocation
  419. var key string
  420. props := []string{
  421. AllocationClusterProp,
  422. }
  423. key = alloc.generateKey(props, nil)
  424. if key != "" {
  425. t.Fatalf("generateKey: expected \"\"; actual \"%s\"", key)
  426. }
  427. alloc = &Allocation{}
  428. alloc.Properties = &AllocationProperties{
  429. Cluster: "cluster1",
  430. Labels: map[string]string{
  431. "app": "app1",
  432. "env": "env1",
  433. },
  434. }
  435. key = alloc.generateKey(props, nil)
  436. if key != "cluster1" {
  437. t.Fatalf("generateKey: expected \"cluster1\"; actual \"%s\"", key)
  438. }
  439. props = []string{
  440. AllocationClusterProp,
  441. AllocationNamespaceProp,
  442. "label:app",
  443. }
  444. key = alloc.generateKey(props, nil)
  445. if key != "cluster1//app1" {
  446. t.Fatalf("generateKey: expected \"cluster1//app1\"; actual \"%s\"", key)
  447. }
  448. alloc.Properties = &AllocationProperties{
  449. Cluster: "cluster1",
  450. Namespace: "namespace1",
  451. Labels: map[string]string{
  452. "app": "app1",
  453. "env": "env1",
  454. },
  455. }
  456. key = alloc.generateKey(props, nil)
  457. if key != "cluster1/namespace1/app1" {
  458. t.Fatalf("generateKey: expected \"cluster1/namespace1/app1\"; actual \"%s\"", key)
  459. }
  460. props = []string{
  461. AllocationDepartmentProp,
  462. AllocationEnvironmentProp,
  463. AllocationOwnerProp,
  464. AllocationProductProp,
  465. AllocationTeamProp,
  466. }
  467. labelConfig := NewLabelConfig()
  468. alloc.Properties = &AllocationProperties{
  469. Cluster: "cluster1",
  470. Namespace: "namespace1",
  471. Labels: map[string]string{
  472. labelConfig.DepartmentLabel: "dept1",
  473. labelConfig.EnvironmentLabel: "envt1",
  474. labelConfig.OwnerLabel: "ownr1",
  475. labelConfig.ProductLabel: "prod1",
  476. labelConfig.TeamLabel: "team1",
  477. },
  478. }
  479. key = alloc.generateKey(props, nil)
  480. if key != "dept1/envt1/ownr1/prod1/team1" {
  481. t.Fatalf("generateKey: expected \"dept1/envt1/ownr1/prod1/team1\"; actual \"%s\"", key)
  482. }
  483. // Ensure that labels with illegal Prometheus characters in LabelConfig
  484. // still match their sanitized values. Ensure also that multiple comma-
  485. // separated values work.
  486. labelConfig.DepartmentLabel = "prom/illegal-department"
  487. labelConfig.EnvironmentLabel = " env "
  488. labelConfig.OwnerLabel = "$owner%"
  489. labelConfig.ProductLabel = "app.kubernetes.io/app"
  490. labelConfig.TeamLabel = "team,app.kubernetes.io/team,k8s-team"
  491. alloc.Properties = &AllocationProperties{
  492. Cluster: "cluster1",
  493. Namespace: "namespace1",
  494. Labels: map[string]string{
  495. "prom_illegal_department": "dept1",
  496. "env": "envt1",
  497. "_owner_": "ownr1",
  498. "team": "team1",
  499. "app_kubernetes_io_app": "prod1",
  500. "app_kubernetes_io_team": "team2",
  501. },
  502. }
  503. props = []string{
  504. AllocationDepartmentProp,
  505. AllocationEnvironmentProp,
  506. AllocationOwnerProp,
  507. AllocationProductProp,
  508. AllocationTeamProp,
  509. }
  510. key = alloc.generateKey(props, labelConfig)
  511. if key != "dept1/envt1/ownr1/prod1/team1/team2/__unallocated__" {
  512. t.Fatalf("generateKey: expected \"dept1/envt1/ownr1/prod1/team1/team2/__unallocated__\"; actual \"%s\"", key)
  513. }
  514. }
  515. func TestNewAllocationSet(t *testing.T) {
  516. // TODO niko
  517. }
  518. func assertAllocationSetTotals(t *testing.T, as *AllocationSet, msg string, err error, length int, totalCost float64) {
  519. if err != nil {
  520. t.Fatalf("AllocationSet.AggregateBy[%s]: unexpected error: %s", msg, err)
  521. }
  522. if as.Length() != length {
  523. t.Fatalf("AllocationSet.AggregateBy[%s]: expected set of length %d, actual %d", msg, length, as.Length())
  524. }
  525. if math.Round(as.TotalCost()*100) != math.Round(totalCost*100) {
  526. t.Fatalf("AllocationSet.AggregateBy[%s]: expected total cost %.2f, actual %.2f", msg, totalCost, as.TotalCost())
  527. }
  528. }
  529. func assertParcResults(t *testing.T, as *AllocationSet, msg string, exps map[string]ProportionalAssetResourceCosts) {
  530. for allocKey, a := range as.Allocations {
  531. for key, actualParc := range a.ProportionalAssetResourceCosts {
  532. expectedParcs := exps[allocKey]
  533. // round to prevent floating point issues from failing tests at ultra high precision
  534. actualParc.NodeResourceCostPercentage = roundFloat(actualParc.NodeResourceCostPercentage)
  535. actualParc.CPUPercentage = roundFloat(actualParc.CPUPercentage)
  536. actualParc.RAMPercentage = roundFloat(actualParc.RAMPercentage)
  537. actualParc.GPUPercentage = roundFloat(actualParc.GPUPercentage)
  538. actualParc.PVPercentage = roundFloat(actualParc.PVPercentage)
  539. if !reflect.DeepEqual(expectedParcs[key], actualParc) {
  540. t.Fatalf("actual PARC %+v did not match expected PARC %+v", actualParc, expectedParcs[key])
  541. }
  542. }
  543. }
  544. }
  545. func roundFloat(val float64) float64 {
  546. ratio := math.Pow(10, float64(5))
  547. return math.Round(val*ratio) / ratio
  548. }
  549. func assertAllocationTotals(t *testing.T, as *AllocationSet, msg string, exps map[string]float64) {
  550. for _, a := range as.Allocations {
  551. if exp, ok := exps[a.Name]; ok {
  552. if math.Round(a.TotalCost()*100) != math.Round(exp*100) {
  553. t.Fatalf("AllocationSet.AggregateBy[%s]: expected total cost %f, actual %f", msg, exp, a.TotalCost())
  554. }
  555. } else {
  556. t.Fatalf("AllocationSet.AggregateBy[%s]: unexpected allocation: %s", msg, a.Name)
  557. }
  558. }
  559. }
  560. func assertAllocationWindow(t *testing.T, as *AllocationSet, msg string, expStart, expEnd time.Time, expMinutes float64) {
  561. for _, a := range as.Allocations {
  562. if !a.Start.Equal(expStart) {
  563. t.Fatalf("AllocationSet.AggregateBy[%s]: expected start %s, actual %s", msg, expStart, a.Start)
  564. }
  565. if !a.End.Equal(expEnd) {
  566. t.Fatalf("AllocationSet.AggregateBy[%s]: expected end %s, actual %s", msg, expEnd, a.End)
  567. }
  568. if a.Minutes() != expMinutes {
  569. t.Fatalf("AllocationSet.AggregateBy[%s]: expected minutes %f, actual %f", msg, expMinutes, a.Minutes())
  570. }
  571. }
  572. }
  573. func printAllocationSet(msg string, as *AllocationSet) {
  574. fmt.Printf("--- %s ---\n", msg)
  575. for _, a := range as.Allocations {
  576. fmt.Printf(" > %s\n", a)
  577. }
  578. }
  579. func TestAllocationSet_AggregateBy(t *testing.T) {
  580. // Test AggregateBy against the following workload topology, which is
  581. // generated by GenerateMockAllocationSet:
  582. // | Hierarchy | Cost | CPU | RAM | GPU | PV | Net | LB |
  583. // +----------------------------------------+------+------+------+------+------+------+------+
  584. // cluster1:
  585. // idle: 20.00 5.00 15.00 0.00 0.00 0.00 0.00
  586. // namespace1:
  587. // pod1:
  588. // container1: [app1, env1] 16.00 1.00 11.00 1.00 1.00 1.00 1.00
  589. // pod-abc: (deployment1)
  590. // container2: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  591. // pod-def: (deployment1)
  592. // container3: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  593. // namespace2:
  594. // pod-ghi: (deployment2)
  595. // container4: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  596. // container5: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  597. // pod-jkl: (daemonset1)
  598. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  599. // +-----------------------------------------+------+------+------+------+------+------+------+
  600. // cluster1 subtotal 66.00 11.00 31.00 6.00 6.00 6.00 6.00
  601. // +-----------------------------------------+------+------+------+------+------+------+------+
  602. // cluster2:
  603. // idle: 10.00 5.00 5.00 0.00 0.00 0.00 0.00
  604. // namespace2:
  605. // pod-mno: (deployment2)
  606. // container4: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  607. // container5: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  608. // pod-pqr: (daemonset1)
  609. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  610. // namespace3:
  611. // pod-stu: (deployment3)
  612. // container7: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  613. // pod-vwx: (statefulset1)
  614. // container8: an[team2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  615. // container9: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  616. // +----------------------------------------+------+------+------+------+------+------+------+
  617. // cluster2 subtotal 46.00 11.00 11.00 6.00 6.00 6.00 6.00
  618. // +----------------------------------------+------+------+------+------+------+------+------+
  619. // total 112.00 22.00 42.00 12.00 12.00 12.00 12.00
  620. // +----------------------------------------+------+------+------+------+------+------+------+
  621. // Scenarios to test:
  622. // 1 Single-aggregation
  623. // 1a AggregationProperties=(Cluster)
  624. // 1b AggregationProperties=(Namespace)
  625. // 1c AggregationProperties=(Pod)
  626. // 1d AggregationProperties=(Container)
  627. // 1e AggregationProperties=(ControllerKind)
  628. // 1f AggregationProperties=(Controller)
  629. // 1g AggregationProperties=(Service)
  630. // 1h AggregationProperties=(Label:app)
  631. // 2 Multi-aggregation
  632. // 2a AggregationProperties=(Cluster, Namespace)
  633. // 2b AggregationProperties=(Namespace, Label:app)
  634. // 2c AggregationProperties=(Cluster, Namespace, Pod, Container)
  635. // 2d AggregationProperties=(Label:app, Label:environment)
  636. // 3 Share idle
  637. // 3a AggregationProperties=(Namespace) ShareIdle=ShareWeighted
  638. // 3b AggregationProperties=(Namespace) ShareIdle=ShareEven (TODO niko)
  639. // 4 Share resources
  640. // 4a Share namespace ShareEven
  641. // 4b Share cluster ShareWeighted
  642. // 4c Share label ShareEven
  643. // 4d Share overhead ShareWeighted
  644. // 5 Filters
  645. // 5a Filter by cluster with separate idle
  646. // 5b Filter by cluster with shared idle
  647. // TODO niko/idle more filter tests
  648. // 6 Combinations and options
  649. // 6a SplitIdle
  650. // 6b Share idle with filters
  651. // 6c Share resources with filters
  652. // 6d Share idle and share resources
  653. // 6e IdleByNode
  654. // 7 Edge cases and errors
  655. // 7a Empty AggregationProperties
  656. // 7b Filter all
  657. // 7c Share all
  658. // 7d Share and filter the same allocations
  659. // Definitions and set-up:
  660. var as *AllocationSet
  661. var err error
  662. endYesterday := time.Now().UTC().Truncate(day)
  663. startYesterday := endYesterday.Add(-day)
  664. numClusters := 2
  665. numNamespaces := 3
  666. numPods := 9
  667. numContainers := 9
  668. numControllerKinds := 3
  669. numControllers := 5
  670. numServices := 1
  671. numLabelApps := 2
  672. // By default, idle is reported as a single, merged allocation
  673. numIdle := 1
  674. // There will only ever be one __unallocated__
  675. numUnallocated := 1
  676. // There are two clusters, so each gets an idle entry when they are split
  677. numSplitIdleCluster := 2
  678. // There are two clusters, so each gets an idle entry when they are split
  679. numSplitIdleNode := 4
  680. activeTotalCost := 82.0
  681. idleTotalCost := 30.0
  682. sharedOverheadHourlyCost := 7.0
  683. // Match filters
  684. // This is ugly, but required because cannot import filterutil due to import cycle
  685. namespaceEquals := func(ns string) *ast.EqualOp {
  686. return &ast.EqualOp{
  687. Left: ast.Identifier{
  688. Field: ast.NewField(allocation.FieldNamespace),
  689. Key: "",
  690. },
  691. Right: ns,
  692. }
  693. }
  694. // This is ugly, but required because cannot import filterutil due to import cycle
  695. labelEquals := func(name, value string) *ast.EqualOp {
  696. return &ast.EqualOp{
  697. Left: ast.Identifier{
  698. Field: ast.NewField(allocation.FieldLabel),
  699. Key: name,
  700. },
  701. Right: value,
  702. }
  703. }
  704. end := time.Now().UTC().Truncate(day)
  705. start := end.Add(-day)
  706. // Tests:
  707. cases := map[string]struct {
  708. start time.Time
  709. aggBy []string
  710. aggOpts *AllocationAggregationOptions
  711. numResults int
  712. totalCost float64
  713. results map[string]float64
  714. windowStart time.Time
  715. windowEnd time.Time
  716. expMinutes float64
  717. expectedParcResults map[string]ProportionalAssetResourceCosts
  718. }{
  719. // 1 Single-aggregation
  720. // 1a AggregationProperties=(Cluster)
  721. "1a": {
  722. start: start,
  723. aggBy: []string{AllocationClusterProp},
  724. aggOpts: &AllocationAggregationOptions{
  725. IncludeProportionalAssetResourceCosts: true,
  726. },
  727. numResults: numClusters + numIdle,
  728. totalCost: activeTotalCost + idleTotalCost,
  729. results: map[string]float64{
  730. "cluster1": 46.00,
  731. "cluster2": 36.00,
  732. IdleSuffix: 30.00,
  733. },
  734. windowStart: startYesterday,
  735. windowEnd: endYesterday,
  736. expMinutes: 1440.0,
  737. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  738. "cluster1": {
  739. "cluster1": ProportionalAssetResourceCost{
  740. Cluster: "cluster1",
  741. Name: "",
  742. Type: "",
  743. ProviderID: "",
  744. GPUProportionalCost: 6.0,
  745. CPUProportionalCost: 6.0,
  746. RAMProportionalCost: 16.0,
  747. PVProportionalCost: 6.0,
  748. },
  749. },
  750. "cluster2": {
  751. "cluster2": ProportionalAssetResourceCost{
  752. Cluster: "cluster2",
  753. Name: "",
  754. Type: "",
  755. ProviderID: "",
  756. GPUProportionalCost: 6,
  757. CPUProportionalCost: 6,
  758. RAMProportionalCost: 6,
  759. PVProportionalCost: 6,
  760. },
  761. },
  762. },
  763. },
  764. // 1b AggregationProperties=(Namespace)
  765. "1b": {
  766. start: start,
  767. aggBy: []string{AllocationNamespaceProp},
  768. aggOpts: nil,
  769. numResults: numNamespaces + numIdle,
  770. totalCost: activeTotalCost + idleTotalCost,
  771. results: map[string]float64{
  772. "namespace1": 28.00,
  773. "namespace2": 36.00,
  774. "namespace3": 18.00,
  775. IdleSuffix: 30.00,
  776. },
  777. windowStart: startYesterday,
  778. windowEnd: endYesterday,
  779. expMinutes: 1440.0,
  780. },
  781. // 1c AggregationProperties=(Pod)
  782. "1c": {
  783. start: start,
  784. aggBy: []string{AllocationPodProp},
  785. aggOpts: &AllocationAggregationOptions{
  786. IncludeProportionalAssetResourceCosts: true,
  787. },
  788. numResults: numPods + numIdle,
  789. totalCost: activeTotalCost + idleTotalCost,
  790. results: map[string]float64{
  791. "pod-jkl": 6.00,
  792. "pod-stu": 6.00,
  793. "pod-abc": 6.00,
  794. "pod-pqr": 6.00,
  795. "pod-def": 6.00,
  796. "pod-vwx": 12.00,
  797. "pod1": 16.00,
  798. "pod-mno": 12.00,
  799. "pod-ghi": 12.00,
  800. IdleSuffix: 30.00,
  801. },
  802. windowStart: startYesterday,
  803. windowEnd: endYesterday,
  804. expMinutes: 1440.0,
  805. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  806. "pod1": {
  807. "cluster1": ProportionalAssetResourceCost{
  808. Cluster: "cluster1",
  809. Name: "",
  810. Type: "",
  811. ProviderID: "",
  812. GPUProportionalCost: 1.0,
  813. CPUProportionalCost: 1.0,
  814. RAMProportionalCost: 11.0,
  815. PVProportionalCost: 1.0,
  816. },
  817. },
  818. "pod-abc": {
  819. "cluster1": ProportionalAssetResourceCost{
  820. Cluster: "cluster1",
  821. Name: "",
  822. Type: "",
  823. ProviderID: "",
  824. GPUProportionalCost: 1.0,
  825. CPUProportionalCost: 1.0,
  826. RAMProportionalCost: 1.0,
  827. PVProportionalCost: 1.0,
  828. },
  829. },
  830. "pod-def": {
  831. "cluster1": ProportionalAssetResourceCost{
  832. Cluster: "cluster1",
  833. Name: "",
  834. Type: "",
  835. ProviderID: "",
  836. GPUProportionalCost: 1.0,
  837. CPUProportionalCost: 1.0,
  838. RAMProportionalCost: 1.0,
  839. PVProportionalCost: 1.0,
  840. },
  841. },
  842. "pod-ghi": {
  843. "cluster1": ProportionalAssetResourceCost{
  844. Cluster: "cluster1",
  845. Name: "",
  846. Type: "",
  847. ProviderID: "",
  848. GPUProportionalCost: 2.0,
  849. CPUProportionalCost: 2.0,
  850. RAMProportionalCost: 2.0,
  851. PVProportionalCost: 2.0,
  852. },
  853. },
  854. "pod-jkl": {
  855. "cluster1": ProportionalAssetResourceCost{
  856. Cluster: "cluster1",
  857. Name: "",
  858. Type: "",
  859. ProviderID: "",
  860. GPUProportionalCost: 1.0,
  861. CPUProportionalCost: 1.0,
  862. RAMProportionalCost: 1.0,
  863. PVProportionalCost: 1.0,
  864. },
  865. },
  866. "pod-mno": {
  867. "cluster2": ProportionalAssetResourceCost{
  868. Cluster: "cluster2",
  869. Name: "",
  870. Type: "",
  871. ProviderID: "",
  872. GPUProportionalCost: 2.0,
  873. CPUProportionalCost: 2.0,
  874. RAMProportionalCost: 2.0,
  875. PVProportionalCost: 2.0,
  876. },
  877. },
  878. "pod-pqr": {
  879. "cluster2": ProportionalAssetResourceCost{
  880. Cluster: "cluster2",
  881. Name: "",
  882. Type: "",
  883. ProviderID: "",
  884. GPUProportionalCost: 1.0,
  885. CPUProportionalCost: 1.0,
  886. RAMProportionalCost: 1.0,
  887. PVProportionalCost: 1.0,
  888. },
  889. },
  890. "pod-stu": {
  891. "cluster2": ProportionalAssetResourceCost{
  892. Cluster: "cluster2",
  893. Name: "",
  894. Type: "",
  895. ProviderID: "",
  896. GPUProportionalCost: 1.0,
  897. CPUProportionalCost: 1.0,
  898. RAMProportionalCost: 1.0,
  899. PVProportionalCost: 1.0,
  900. },
  901. },
  902. "pod-vwx": {
  903. "cluster2": ProportionalAssetResourceCost{
  904. Cluster: "cluster2",
  905. Name: "",
  906. Type: "",
  907. ProviderID: "",
  908. GPUProportionalCost: 2.0,
  909. CPUProportionalCost: 2.0,
  910. RAMProportionalCost: 2.0,
  911. PVProportionalCost: 2.0,
  912. },
  913. },
  914. },
  915. },
  916. // 1d AggregationProperties=(Container)
  917. "1d": {
  918. start: start,
  919. aggBy: []string{AllocationContainerProp},
  920. aggOpts: nil,
  921. numResults: numContainers + numIdle,
  922. totalCost: activeTotalCost + idleTotalCost,
  923. results: map[string]float64{
  924. "container2": 6.00,
  925. "container9": 6.00,
  926. "container6": 12.00,
  927. "container3": 6.00,
  928. "container4": 12.00,
  929. "container7": 6.00,
  930. "container8": 6.00,
  931. "container5": 12.00,
  932. "container1": 16.00,
  933. IdleSuffix: 30.00,
  934. },
  935. windowStart: startYesterday,
  936. windowEnd: endYesterday,
  937. expMinutes: 1440.0,
  938. },
  939. // 1e AggregationProperties=(ControllerKind)
  940. "1e": {
  941. start: start,
  942. aggBy: []string{AllocationControllerKindProp},
  943. aggOpts: nil,
  944. numResults: numControllerKinds + numIdle + numUnallocated,
  945. totalCost: activeTotalCost + idleTotalCost,
  946. results: map[string]float64{
  947. "daemonset": 12.00,
  948. "deployment": 42.00,
  949. "statefulset": 12.00,
  950. IdleSuffix: 30.00,
  951. UnallocatedSuffix: 16.00,
  952. },
  953. windowStart: startYesterday,
  954. windowEnd: endYesterday,
  955. expMinutes: 1440.0,
  956. },
  957. // 1f AggregationProperties=(Controller)
  958. "1f": {
  959. start: start,
  960. aggBy: []string{AllocationControllerProp},
  961. aggOpts: nil,
  962. numResults: numControllers + numIdle + numUnallocated,
  963. totalCost: activeTotalCost + idleTotalCost,
  964. results: map[string]float64{
  965. "deployment:deployment2": 24.00,
  966. "daemonset:daemonset1": 12.00,
  967. "deployment:deployment3": 6.00,
  968. "statefulset:statefulset1": 12.00,
  969. "deployment:deployment1": 12.00,
  970. IdleSuffix: 30.00,
  971. UnallocatedSuffix: 16.00,
  972. },
  973. windowStart: startYesterday,
  974. windowEnd: endYesterday,
  975. expMinutes: 1440.0,
  976. },
  977. // 1g AggregationProperties=(Service)
  978. "1g": {
  979. start: start,
  980. aggBy: []string{AllocationServiceProp},
  981. aggOpts: nil,
  982. numResults: numServices + numIdle + numUnallocated,
  983. totalCost: activeTotalCost + idleTotalCost,
  984. results: map[string]float64{
  985. "service1": 12.00,
  986. IdleSuffix: 30.00,
  987. UnallocatedSuffix: 70.00,
  988. },
  989. windowStart: startYesterday,
  990. windowEnd: endYesterday,
  991. expMinutes: 1440.0,
  992. },
  993. // 1h AggregationProperties=(Label:app)
  994. "1h": {
  995. start: start,
  996. aggBy: []string{"label:app"},
  997. aggOpts: nil,
  998. numResults: numLabelApps + numIdle + numUnallocated,
  999. totalCost: activeTotalCost + idleTotalCost,
  1000. results: map[string]float64{
  1001. "app1": 16.00,
  1002. "app2": 24.00,
  1003. IdleSuffix: 30.00,
  1004. UnallocatedSuffix: 42.00,
  1005. },
  1006. windowStart: startYesterday,
  1007. windowEnd: endYesterday,
  1008. expMinutes: 1440.0,
  1009. },
  1010. // 1i AggregationProperties=(deployment)
  1011. "1i": {
  1012. start: start,
  1013. aggBy: []string{AllocationDeploymentProp},
  1014. aggOpts: nil,
  1015. numResults: 3 + numIdle + numUnallocated,
  1016. totalCost: activeTotalCost + idleTotalCost,
  1017. results: map[string]float64{
  1018. "deployment1": 12.00,
  1019. "deployment2": 24.00,
  1020. "deployment3": 6.00,
  1021. IdleSuffix: 30.00,
  1022. UnallocatedSuffix: 40.00,
  1023. },
  1024. windowStart: startYesterday,
  1025. windowEnd: endYesterday,
  1026. expMinutes: 1440.0,
  1027. },
  1028. // 1j AggregationProperties=(Annotation:team)
  1029. "1j": {
  1030. start: start,
  1031. aggBy: []string{"annotation:team"},
  1032. aggOpts: nil,
  1033. numResults: 2 + numIdle + numUnallocated,
  1034. totalCost: activeTotalCost + idleTotalCost,
  1035. results: map[string]float64{
  1036. "team1": 12.00,
  1037. "team2": 6.00,
  1038. IdleSuffix: 30.00,
  1039. UnallocatedSuffix: 64.00,
  1040. },
  1041. windowStart: startYesterday,
  1042. windowEnd: endYesterday,
  1043. expMinutes: 1440.0,
  1044. },
  1045. // 1k AggregationProperties=(daemonSet)
  1046. "1k": {
  1047. start: start,
  1048. aggBy: []string{AllocationDaemonSetProp},
  1049. aggOpts: nil,
  1050. numResults: 1 + numIdle + numUnallocated,
  1051. totalCost: activeTotalCost + idleTotalCost,
  1052. results: map[string]float64{
  1053. "daemonset1": 12.00,
  1054. IdleSuffix: 30.00,
  1055. UnallocatedSuffix: 70.00,
  1056. },
  1057. windowStart: startYesterday,
  1058. windowEnd: endYesterday,
  1059. expMinutes: 1440.0,
  1060. },
  1061. // 1l AggregationProperties=(statefulSet)
  1062. "1l": {
  1063. start: start,
  1064. aggBy: []string{AllocationStatefulSetProp},
  1065. aggOpts: nil,
  1066. numResults: 1 + numIdle + numUnallocated,
  1067. totalCost: activeTotalCost + idleTotalCost,
  1068. results: map[string]float64{
  1069. "statefulset1": 12.00,
  1070. IdleSuffix: 30.00,
  1071. UnallocatedSuffix: 70.00,
  1072. },
  1073. windowStart: startYesterday,
  1074. windowEnd: endYesterday,
  1075. expMinutes: 1440.0,
  1076. },
  1077. // 2 Multi-aggregation
  1078. // 2a AggregationProperties=(Cluster, Namespace)
  1079. // 2b AggregationProperties=(Namespace, Label:app)
  1080. // 2c AggregationProperties=(Cluster, Namespace, Pod, Container)
  1081. // 2d AggregationProperties=(Label:app, Label:environment)
  1082. "2d": {
  1083. start: start,
  1084. aggBy: []string{"label:app", "label:env"},
  1085. aggOpts: nil,
  1086. numResults: 3 + numIdle + numUnallocated,
  1087. totalCost: activeTotalCost + idleTotalCost,
  1088. // sets should be {idle, unallocated, app1/env1, app2/env2, app2/unallocated}
  1089. results: map[string]float64{
  1090. "app1/env1": 16.00,
  1091. "app2/env2": 12.00,
  1092. "app2/" + UnallocatedSuffix: 12.00,
  1093. IdleSuffix: 30.00,
  1094. UnallocatedSuffix + "/" + UnallocatedSuffix: 42.00,
  1095. },
  1096. windowStart: startYesterday,
  1097. windowEnd: endYesterday,
  1098. expMinutes: 1440.0,
  1099. },
  1100. // 2e AggregationProperties=(Cluster, Label:app, Label:environment)
  1101. "2e": {
  1102. start: start,
  1103. aggBy: []string{AllocationClusterProp, "label:app", "label:env"},
  1104. aggOpts: nil,
  1105. numResults: 6,
  1106. totalCost: activeTotalCost + idleTotalCost,
  1107. results: map[string]float64{
  1108. "cluster1/app2/env2": 12.00,
  1109. "__idle__": 30.00,
  1110. "cluster1/app1/env1": 16.00,
  1111. "cluster1/" + UnallocatedSuffix + "/" + UnallocatedSuffix: 18.00,
  1112. "cluster2/app2/" + UnallocatedSuffix: 12.00,
  1113. "cluster2/" + UnallocatedSuffix + "/" + UnallocatedSuffix: 24.00,
  1114. },
  1115. windowStart: startYesterday,
  1116. windowEnd: endYesterday,
  1117. expMinutes: 1440.0,
  1118. },
  1119. // 2f AggregationProperties=(annotation:team, pod)
  1120. "2f": {
  1121. start: start,
  1122. aggBy: []string{AllocationPodProp, "annotation:team"},
  1123. aggOpts: nil,
  1124. numResults: 11,
  1125. totalCost: activeTotalCost + idleTotalCost,
  1126. results: map[string]float64{
  1127. "pod-jkl/" + UnallocatedSuffix: 6.00,
  1128. "pod-stu/team1": 6.00,
  1129. "pod-abc/" + UnallocatedSuffix: 6.00,
  1130. "pod-pqr/" + UnallocatedSuffix: 6.00,
  1131. "pod-def/" + UnallocatedSuffix: 6.00,
  1132. "pod-vwx/team1": 6.00,
  1133. "pod-vwx/team2": 6.00,
  1134. "pod1/" + UnallocatedSuffix: 16.00,
  1135. "pod-mno/" + UnallocatedSuffix: 12.00,
  1136. "pod-ghi/" + UnallocatedSuffix: 12.00,
  1137. IdleSuffix: 30.00,
  1138. },
  1139. windowStart: startYesterday,
  1140. windowEnd: endYesterday,
  1141. expMinutes: 1440.0,
  1142. },
  1143. // 3 Share idle
  1144. // 3a AggregationProperties=(Namespace) ShareIdle=ShareWeighted
  1145. // namespace1: 42.6875 = 28.00 + 5.00*(3.00/6.00) + 15.0*(13.0/16.0)
  1146. // 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)
  1147. // namespace3: 23.0000 = 18.00 + 5.0*(3.0/6.0) + 5.0*(3.0/6.0)
  1148. "3a": {
  1149. start: start,
  1150. aggBy: []string{AllocationNamespaceProp},
  1151. aggOpts: &AllocationAggregationOptions{ShareIdle: ShareWeighted},
  1152. numResults: numNamespaces,
  1153. totalCost: activeTotalCost + idleTotalCost,
  1154. results: map[string]float64{
  1155. "namespace1": 42.69,
  1156. "namespace2": 46.31,
  1157. "namespace3": 23.00,
  1158. },
  1159. windowStart: startYesterday,
  1160. windowEnd: endYesterday,
  1161. expMinutes: 1440.0,
  1162. },
  1163. // 3b: sharing idle evenly is deprecated
  1164. // 4 Share resources
  1165. // 4a Share namespace ShareEven
  1166. // namespace1: 37.5000 = 28.00 + 18.00*(1.0/2.0)
  1167. // namespace2: 45.5000 = 36.00 + 18.00*(1.0/2.0)
  1168. // idle: 30.0000
  1169. "4a": {
  1170. start: start,
  1171. aggBy: []string{AllocationNamespaceProp},
  1172. aggOpts: &AllocationAggregationOptions{
  1173. Share: namespaceEquals("namespace3"),
  1174. ShareSplit: ShareEven,
  1175. },
  1176. numResults: numNamespaces,
  1177. totalCost: activeTotalCost + idleTotalCost,
  1178. results: map[string]float64{
  1179. "namespace1": 37.00,
  1180. "namespace2": 45.00,
  1181. IdleSuffix: 30.00,
  1182. },
  1183. windowStart: startYesterday,
  1184. windowEnd: endYesterday,
  1185. expMinutes: 1440.0,
  1186. },
  1187. // 4b Share namespace ShareWeighted
  1188. // namespace1: 32.5000 =
  1189. // namespace2: 37.5000 =
  1190. // idle: 30.0000
  1191. "4b": {
  1192. start: start,
  1193. aggBy: []string{AllocationNamespaceProp},
  1194. aggOpts: &AllocationAggregationOptions{
  1195. Share: namespaceEquals("namespace3"),
  1196. ShareSplit: ShareWeighted,
  1197. IncludeProportionalAssetResourceCosts: true,
  1198. },
  1199. numResults: numNamespaces,
  1200. totalCost: activeTotalCost + idleTotalCost,
  1201. results: map[string]float64{
  1202. "namespace1": 35.88,
  1203. "namespace2": 46.125,
  1204. IdleSuffix: 30.00,
  1205. },
  1206. windowStart: startYesterday,
  1207. windowEnd: endYesterday,
  1208. expMinutes: 1440.0,
  1209. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  1210. "namespace1": {
  1211. "cluster1": ProportionalAssetResourceCost{
  1212. Cluster: "cluster1",
  1213. Name: "",
  1214. Type: "",
  1215. ProviderID: "",
  1216. GPUProportionalCost: 3,
  1217. CPUProportionalCost: 3,
  1218. RAMProportionalCost: 13,
  1219. PVProportionalCost: 3,
  1220. },
  1221. },
  1222. "namespace2": {
  1223. "cluster1": ProportionalAssetResourceCost{
  1224. Cluster: "cluster1",
  1225. Name: "",
  1226. Type: "",
  1227. ProviderID: "",
  1228. GPUProportionalCost: 3,
  1229. CPUProportionalCost: 3,
  1230. RAMProportionalCost: 3,
  1231. PVProportionalCost: 3,
  1232. },
  1233. "cluster2": ProportionalAssetResourceCost{
  1234. Cluster: "cluster2",
  1235. Name: "",
  1236. Type: "",
  1237. ProviderID: "",
  1238. GPUProportionalCost: 3,
  1239. CPUProportionalCost: 3,
  1240. RAMProportionalCost: 3,
  1241. PVProportionalCost: 3,
  1242. },
  1243. },
  1244. },
  1245. },
  1246. // 4c Share label ShareEven
  1247. // namespace1: 17.3333 = 28.00 - 16.00 + 16.00*(1.0/3.0)
  1248. // namespace2: 41.3333 = 36.00 + 16.00*(1.0/3.0)
  1249. // namespace3: 23.3333 = 18.00 + 16.00*(1.0/3.0)
  1250. // idle: 30.0000
  1251. "4c": {
  1252. start: start,
  1253. aggBy: []string{AllocationNamespaceProp},
  1254. aggOpts: &AllocationAggregationOptions{
  1255. Share: labelEquals("app", "app1"),
  1256. ShareSplit: ShareEven,
  1257. },
  1258. numResults: numNamespaces + numIdle,
  1259. totalCost: activeTotalCost + idleTotalCost,
  1260. results: map[string]float64{
  1261. "namespace1": 17.33,
  1262. "namespace2": 41.33,
  1263. "namespace3": 23.33,
  1264. IdleSuffix: 30.00,
  1265. },
  1266. windowStart: startYesterday,
  1267. windowEnd: endYesterday,
  1268. expMinutes: 1440.0,
  1269. },
  1270. // 4d Share overhead ShareWeighted
  1271. // namespace1: 85.366 = 28.00 + (7.0*24.0)*(28.00/82.00)
  1272. // namespace2: 109.756 = 36.00 + (7.0*24.0)*(36.00/82.00)
  1273. // namespace3: 54.878 = 18.00 + (7.0*24.0)*(18.00/82.00)
  1274. // idle: 30.0000
  1275. "4d": {
  1276. start: start,
  1277. aggBy: []string{AllocationNamespaceProp},
  1278. aggOpts: &AllocationAggregationOptions{
  1279. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1280. ShareSplit: ShareWeighted,
  1281. },
  1282. numResults: numNamespaces + numIdle,
  1283. totalCost: activeTotalCost + idleTotalCost + (sharedOverheadHourlyCost * 24.0),
  1284. results: map[string]float64{
  1285. "namespace1": 85.366,
  1286. "namespace2": 109.756,
  1287. "namespace3": 54.878,
  1288. IdleSuffix: 30.00,
  1289. },
  1290. windowStart: startYesterday,
  1291. windowEnd: endYesterday,
  1292. expMinutes: 1440.0,
  1293. },
  1294. // 5 Filters
  1295. // 5a Filter by cluster with separate idle
  1296. "5a": {
  1297. start: start,
  1298. aggBy: []string{AllocationClusterProp},
  1299. aggOpts: &AllocationAggregationOptions{
  1300. Filter: mustParseFilter(`cluster:"cluster1"`),
  1301. ShareIdle: ShareNone,
  1302. },
  1303. numResults: 1 + numIdle,
  1304. totalCost: 66.0,
  1305. results: map[string]float64{
  1306. "cluster1": 46.00,
  1307. IdleSuffix: 20.00,
  1308. },
  1309. windowStart: startYesterday,
  1310. windowEnd: endYesterday,
  1311. expMinutes: 1440.0,
  1312. },
  1313. // 5b Filter by cluster with shared idle
  1314. "5b": {
  1315. start: start,
  1316. aggBy: []string{AllocationClusterProp},
  1317. aggOpts: &AllocationAggregationOptions{
  1318. Filter: mustParseFilter(`cluster:"cluster1"`),
  1319. ShareIdle: ShareWeighted,
  1320. },
  1321. numResults: 1,
  1322. totalCost: 66.0,
  1323. results: map[string]float64{
  1324. "cluster1": 66.00,
  1325. },
  1326. windowStart: startYesterday,
  1327. windowEnd: endYesterday,
  1328. expMinutes: 1440.0,
  1329. },
  1330. // 5c Filter by cluster, agg by namespace, with separate idle
  1331. "5c": {
  1332. start: start,
  1333. aggBy: []string{AllocationNamespaceProp},
  1334. aggOpts: &AllocationAggregationOptions{
  1335. Filter: mustParseFilter(`cluster:"cluster1"`),
  1336. ShareIdle: ShareNone,
  1337. },
  1338. numResults: 2 + numIdle,
  1339. totalCost: 66.0,
  1340. results: map[string]float64{
  1341. "namespace1": 28.00,
  1342. "namespace2": 18.00,
  1343. IdleSuffix: 20.00,
  1344. },
  1345. windowStart: startYesterday,
  1346. windowEnd: endYesterday,
  1347. expMinutes: 1440.0,
  1348. },
  1349. // 5d Filter by namespace, agg by cluster, with separate idle
  1350. "5d": {
  1351. start: start,
  1352. aggBy: []string{AllocationClusterProp},
  1353. aggOpts: &AllocationAggregationOptions{
  1354. Filter: mustParseFilter(`namespace:"namespace2"`),
  1355. ShareIdle: ShareNone,
  1356. },
  1357. numResults: numClusters + numIdle,
  1358. totalCost: 46.31,
  1359. results: map[string]float64{
  1360. "cluster1": 18.00,
  1361. "cluster2": 18.00,
  1362. IdleSuffix: 10.31,
  1363. },
  1364. windowStart: startYesterday,
  1365. windowEnd: endYesterday,
  1366. expMinutes: 1440.0,
  1367. },
  1368. // 6 Combinations and options
  1369. // 6a SplitIdle
  1370. "6a": {
  1371. start: start,
  1372. aggBy: []string{AllocationNamespaceProp},
  1373. aggOpts: &AllocationAggregationOptions{
  1374. SplitIdle: true,
  1375. },
  1376. numResults: numNamespaces + numSplitIdleCluster,
  1377. totalCost: activeTotalCost + idleTotalCost,
  1378. results: map[string]float64{
  1379. "namespace1": 28.00,
  1380. "namespace2": 36.00,
  1381. "namespace3": 18.00,
  1382. fmt.Sprintf("cluster1/%s", IdleSuffix): 20.00,
  1383. fmt.Sprintf("cluster2/%s", IdleSuffix): 10.00,
  1384. },
  1385. windowStart: startYesterday,
  1386. windowEnd: endYesterday,
  1387. expMinutes: 1440.0,
  1388. },
  1389. // 6b Share idle weighted with filters
  1390. // Should match values from unfiltered aggregation (3a)
  1391. // 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)
  1392. "6b": {
  1393. start: start,
  1394. aggBy: []string{AllocationNamespaceProp},
  1395. aggOpts: &AllocationAggregationOptions{
  1396. Filter: mustParseFilter(`namespace:"namespace2"`),
  1397. ShareIdle: ShareWeighted,
  1398. },
  1399. numResults: 1,
  1400. totalCost: 46.31,
  1401. results: map[string]float64{
  1402. "namespace2": 46.31,
  1403. },
  1404. windowStart: startYesterday,
  1405. windowEnd: endYesterday,
  1406. expMinutes: 1440.0,
  1407. },
  1408. // 6c Share idle even with filters (share idle even is deprecated)
  1409. // 6d Share overhead with filters
  1410. // namespace1: 85.366 = 28.00 + (7.0*24.0)*(28.00/82.00)
  1411. // namespace2: 109.756 = 36.00 + (7.0*24.0)*(36.00/82.00)
  1412. // namespace3: 54.878 = 18.00 + (7.0*24.0)*(18.00/82.00)
  1413. // idle: 10.3125 = % of idle paired with namespace2
  1414. // Then namespace 2 is filtered.
  1415. "6d": {
  1416. start: start,
  1417. aggBy: []string{AllocationNamespaceProp},
  1418. aggOpts: &AllocationAggregationOptions{
  1419. Filter: mustParseFilter(`namespace:"namespace2"`),
  1420. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1421. ShareSplit: ShareWeighted,
  1422. },
  1423. numResults: 1 + numIdle,
  1424. totalCost: 120.0686,
  1425. results: map[string]float64{
  1426. "namespace2": 109.7561,
  1427. IdleSuffix: 10.3125,
  1428. },
  1429. windowStart: startYesterday,
  1430. windowEnd: endYesterday,
  1431. expMinutes: 1440.0,
  1432. },
  1433. // 6e Share resources with filters
  1434. "6e": {
  1435. start: start,
  1436. aggBy: []string{AllocationNamespaceProp},
  1437. aggOpts: &AllocationAggregationOptions{
  1438. Filter: mustParseFilter(`namespace:"namespace2"`),
  1439. Share: namespaceEquals("namespace1"),
  1440. ShareSplit: ShareWeighted,
  1441. },
  1442. numResults: 1 + numIdle,
  1443. totalCost: 79.6667, // should be 74.7708, but I'm punting -- too difficult (NK)
  1444. results: map[string]float64{
  1445. "namespace2": 54.6667,
  1446. IdleSuffix: 25.000, // should be 20.1042, but I'm punting -- too difficult (NK)
  1447. },
  1448. windowStart: startYesterday,
  1449. windowEnd: endYesterday,
  1450. expMinutes: 1440.0,
  1451. },
  1452. // 6f Share resources with filters and share idle
  1453. "6f": {
  1454. start: start,
  1455. aggBy: []string{AllocationNamespaceProp},
  1456. aggOpts: &AllocationAggregationOptions{
  1457. Filter: mustParseFilter(`namespace:"namespace2"`),
  1458. Share: namespaceEquals("namespace1"),
  1459. ShareSplit: ShareWeighted,
  1460. ShareIdle: ShareWeighted,
  1461. },
  1462. numResults: 1,
  1463. totalCost: 74.77083,
  1464. results: map[string]float64{
  1465. "namespace2": 74.77083,
  1466. },
  1467. windowStart: startYesterday,
  1468. windowEnd: endYesterday,
  1469. expMinutes: 1440.0,
  1470. },
  1471. // 6g Share idle weighted and share resources weighted
  1472. //
  1473. // First, share idle weighted produces:
  1474. //
  1475. // namespace1: 42.6875
  1476. // initial cost 28.0000
  1477. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1478. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1479. //
  1480. // namespace2: 46.3125
  1481. // initial cost 36.0000
  1482. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1483. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1484. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1485. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1486. //
  1487. // namespace3: 23.0000
  1488. // initial cost 18.0000
  1489. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1490. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1491. //
  1492. // Then, sharing namespace1 means sharing 39.6875 according to coefficients
  1493. // computed before allocating idle (so that weighting idle differently
  1494. // doesn't adversely affect the sharing mechanism):
  1495. //
  1496. // namespace2: 74.7708
  1497. // initial cost 30.0000
  1498. // idle cost 10.3125
  1499. // shared cost 28.4583 = (42.6875)*(36.0/54.0)
  1500. //
  1501. // namespace3: 37.2292
  1502. // initial cost 18.0000
  1503. // idle cost 5.0000
  1504. // shared cost 14.2292 = (42.6875)*(18.0/54.0)
  1505. "6g": {
  1506. start: start,
  1507. aggBy: []string{AllocationNamespaceProp},
  1508. aggOpts: &AllocationAggregationOptions{
  1509. Share: namespaceEquals("namespace1"),
  1510. ShareSplit: ShareWeighted,
  1511. ShareIdle: ShareWeighted,
  1512. },
  1513. numResults: 2,
  1514. totalCost: activeTotalCost + idleTotalCost,
  1515. results: map[string]float64{
  1516. "namespace2": 74.77,
  1517. "namespace3": 37.23,
  1518. },
  1519. windowStart: startYesterday,
  1520. windowEnd: endYesterday,
  1521. expMinutes: 1440.0,
  1522. },
  1523. // 6h Share idle, share resources, and filter
  1524. //
  1525. // First, share idle weighted produces:
  1526. //
  1527. // namespace1: 42.6875
  1528. // initial cost 28.0000
  1529. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1530. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1531. //
  1532. // namespace2: 46.3125
  1533. // initial cost 36.0000
  1534. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1535. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1536. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1537. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1538. //
  1539. // namespace3: 23.0000
  1540. // initial cost 18.0000
  1541. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1542. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1543. //
  1544. // Then, sharing namespace1 means sharing 39.6875 according to coefficients
  1545. // computed before allocating idle (so that weighting idle differently
  1546. // doesn't adversely affect the sharing mechanism):
  1547. //
  1548. // namespace2: 74.7708
  1549. // initial cost 36.0000
  1550. // idle cost 10.3125
  1551. // shared cost 28.4583 = (42.6875)*(36.0/54.0)
  1552. //
  1553. // namespace3: 37.2292
  1554. // initial cost 18.0000
  1555. // idle cost 5.0000
  1556. // shared cost 14.2292 = (42.6875)*(18.0/54.0)
  1557. //
  1558. // Then, filter for namespace2: 74.7708
  1559. "6h": {
  1560. start: start,
  1561. aggBy: []string{AllocationNamespaceProp},
  1562. aggOpts: &AllocationAggregationOptions{
  1563. Filter: mustParseFilter(`namespace:"namespace2"`),
  1564. Share: namespaceEquals("namespace1"),
  1565. ShareSplit: ShareWeighted,
  1566. ShareIdle: ShareWeighted,
  1567. },
  1568. numResults: 1,
  1569. totalCost: 74.77,
  1570. results: map[string]float64{
  1571. "namespace2": 74.77,
  1572. },
  1573. windowStart: startYesterday,
  1574. windowEnd: endYesterday,
  1575. expMinutes: 1440.0,
  1576. },
  1577. // 6i Share idle, share resources, share overhead
  1578. //
  1579. // Share idle weighted:
  1580. //
  1581. // namespace1: 42.6875
  1582. // initial cost 28.0000
  1583. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1584. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1585. //
  1586. // namespace2: 46.3125
  1587. // initial cost 36.0000
  1588. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1589. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1590. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1591. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1592. //
  1593. // namespace3: 23.0000
  1594. // initial cost 18.0000
  1595. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1596. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1597. //
  1598. // Then share overhead:
  1599. //
  1600. // namespace1: 100.0533 = 42.6875 + (7.0*24.0)*(28.00/82.00)
  1601. // namespace2: 120.0686 = 46.3125 + (7.0*24.0)*(36.00/82.00)
  1602. // namespace3: 59.8780 = 23.0000 + (7.0*24.0)*(18.00/82.00)
  1603. //
  1604. // Then namespace 2 is filtered.
  1605. "6i": {
  1606. start: start,
  1607. aggBy: []string{AllocationNamespaceProp},
  1608. aggOpts: &AllocationAggregationOptions{
  1609. Filter: mustParseFilter(`namespace:"namespace2"`),
  1610. ShareSplit: ShareWeighted,
  1611. ShareIdle: ShareWeighted,
  1612. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1613. },
  1614. numResults: 1,
  1615. totalCost: 120.07,
  1616. results: map[string]float64{
  1617. "namespace2": 120.07,
  1618. },
  1619. windowStart: startYesterday,
  1620. windowEnd: endYesterday,
  1621. expMinutes: 1440.0,
  1622. },
  1623. // 6j Idle by Node
  1624. "6j": {
  1625. start: start,
  1626. aggBy: []string{AllocationNamespaceProp},
  1627. aggOpts: &AllocationAggregationOptions{
  1628. IdleByNode: true,
  1629. IncludeProportionalAssetResourceCosts: true,
  1630. },
  1631. numResults: numNamespaces + numIdle,
  1632. totalCost: activeTotalCost + idleTotalCost,
  1633. results: map[string]float64{
  1634. "namespace1": 28.00,
  1635. "namespace2": 36.00,
  1636. "namespace3": 18.00,
  1637. IdleSuffix: 30.00,
  1638. },
  1639. windowStart: startYesterday,
  1640. windowEnd: endYesterday,
  1641. expMinutes: 1440.0,
  1642. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  1643. "namespace1": {
  1644. "cluster1,c1nodes": ProportionalAssetResourceCost{
  1645. Cluster: "cluster1",
  1646. Name: "c1nodes",
  1647. Type: "Node",
  1648. ProviderID: "c1nodes",
  1649. GPUProportionalCost: 3,
  1650. CPUProportionalCost: 3,
  1651. RAMProportionalCost: 13,
  1652. },
  1653. "cluster2,node2": ProportionalAssetResourceCost{
  1654. Cluster: "cluster2",
  1655. Name: "node2",
  1656. Type: "Node",
  1657. ProviderID: "node2",
  1658. GPUProportionalCost: 3,
  1659. CPUProportionalCost: 3,
  1660. RAMProportionalCost: 3,
  1661. },
  1662. "cluster1,pv-a1111": {
  1663. Cluster: "cluster1",
  1664. Name: "pv-a1111",
  1665. Type: "PV",
  1666. PVProportionalCost: 1,
  1667. },
  1668. "cluster1,pv-a11abc2": {
  1669. Cluster: "cluster1",
  1670. Name: "pv-a11abc2",
  1671. Type: "PV",
  1672. PVProportionalCost: 1,
  1673. },
  1674. "cluster1,pv-a11def3": {
  1675. Cluster: "cluster1",
  1676. Name: "pv-a11def3",
  1677. Type: "PV",
  1678. PVProportionalCost: 1,
  1679. },
  1680. },
  1681. "namespace2": {
  1682. "cluster1,c1nodes": ProportionalAssetResourceCost{
  1683. Cluster: "cluster1",
  1684. Name: "c1nodes",
  1685. Type: "Node",
  1686. ProviderID: "c1nodes",
  1687. GPUProportionalCost: 3,
  1688. CPUProportionalCost: 3,
  1689. RAMProportionalCost: 3,
  1690. },
  1691. "cluster2,node1": ProportionalAssetResourceCost{
  1692. Cluster: "cluster2",
  1693. Name: "node1",
  1694. Type: "Node",
  1695. ProviderID: "node1",
  1696. GPUProportionalCost: 2,
  1697. CPUProportionalCost: 2,
  1698. RAMProportionalCost: 2,
  1699. },
  1700. "cluster2,node2": ProportionalAssetResourceCost{
  1701. Cluster: "cluster2",
  1702. Name: "node2",
  1703. Type: "Node",
  1704. ProviderID: "node2",
  1705. GPUProportionalCost: 1,
  1706. CPUProportionalCost: 1,
  1707. RAMProportionalCost: 1,
  1708. },
  1709. "cluster1,pv-a12ghi4": {
  1710. Cluster: "cluster1",
  1711. Name: "pv-a12ghi4",
  1712. Type: "PV",
  1713. PVProportionalCost: 1,
  1714. },
  1715. "cluster1,pv-a12ghi5": {
  1716. Cluster: "cluster1",
  1717. Name: "pv-a12ghi5",
  1718. Type: "PV",
  1719. PVProportionalCost: 1,
  1720. },
  1721. "cluster1,pv-a12jkl6": {
  1722. Cluster: "cluster1",
  1723. Name: "pv-a12jkl6",
  1724. Type: "PV",
  1725. PVProportionalCost: 1,
  1726. },
  1727. "cluster2,pv-a22mno4": {
  1728. Cluster: "cluster2",
  1729. Name: "pv-a22mno4",
  1730. Type: "PV",
  1731. PVProportionalCost: 1,
  1732. },
  1733. "cluster2,pv-a22mno5": {
  1734. Cluster: "cluster2",
  1735. Name: "pv-a22mno5",
  1736. Type: "PV",
  1737. PVProportionalCost: 1,
  1738. },
  1739. "cluster2,pv-a22pqr6": {
  1740. Cluster: "cluster2",
  1741. Name: "pv-a22pqr6",
  1742. Type: "PV",
  1743. PVProportionalCost: 1,
  1744. },
  1745. },
  1746. "namespace3": {
  1747. "cluster2,node3": ProportionalAssetResourceCost{
  1748. Cluster: "cluster2",
  1749. Name: "node3",
  1750. Type: "Node",
  1751. ProviderID: "node3",
  1752. GPUProportionalCost: 2,
  1753. CPUProportionalCost: 2,
  1754. RAMProportionalCost: 2,
  1755. },
  1756. "cluster2,node2": ProportionalAssetResourceCost{
  1757. Cluster: "cluster2",
  1758. Name: "node2",
  1759. Type: "Node",
  1760. ProviderID: "node2",
  1761. GPUProportionalCost: 1,
  1762. CPUProportionalCost: 1,
  1763. RAMProportionalCost: 1,
  1764. },
  1765. "cluster2,pv-a23stu7": {
  1766. Cluster: "cluster2",
  1767. Name: "pv-a23stu7",
  1768. Type: "PV",
  1769. PVProportionalCost: 1,
  1770. },
  1771. "cluster2,pv-a23vwx8": {
  1772. Cluster: "cluster2",
  1773. Name: "pv-a23vwx8",
  1774. Type: "PV",
  1775. PVProportionalCost: 1,
  1776. },
  1777. "cluster2,pv-a23vwx9": {
  1778. Cluster: "cluster2",
  1779. Name: "pv-a23vwx9",
  1780. Type: "PV",
  1781. PVProportionalCost: 1,
  1782. },
  1783. },
  1784. },
  1785. },
  1786. // 6k Split Idle, Idle by Node
  1787. "6k": {
  1788. start: start,
  1789. aggBy: []string{AllocationNamespaceProp},
  1790. aggOpts: &AllocationAggregationOptions{
  1791. SplitIdle: true,
  1792. IdleByNode: true,
  1793. },
  1794. numResults: numNamespaces + numSplitIdleNode,
  1795. totalCost: activeTotalCost + idleTotalCost,
  1796. results: map[string]float64{
  1797. "namespace1": 28.00,
  1798. "namespace2": 36.00,
  1799. "namespace3": 18.00,
  1800. fmt.Sprintf("c1nodes/%s", IdleSuffix): 20.00,
  1801. fmt.Sprintf("node1/%s", IdleSuffix): 3.333333,
  1802. fmt.Sprintf("node2/%s", IdleSuffix): 3.333333,
  1803. fmt.Sprintf("node3/%s", IdleSuffix): 3.333333,
  1804. },
  1805. windowStart: startYesterday,
  1806. windowEnd: endYesterday,
  1807. expMinutes: 1440.0,
  1808. },
  1809. // Old 6k Share idle Even Idle by Node (share idle even deprecated)
  1810. // 6l Share idle weighted with filters, Idle by Node
  1811. // Should match values from unfiltered aggregation (3a)
  1812. // 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)
  1813. "6l": {
  1814. start: start,
  1815. aggBy: []string{AllocationNamespaceProp},
  1816. aggOpts: &AllocationAggregationOptions{
  1817. Filter: mustParseFilter(`namespace:"namespace2"`),
  1818. ShareIdle: ShareWeighted,
  1819. IdleByNode: true,
  1820. },
  1821. numResults: 1,
  1822. totalCost: 46.31,
  1823. results: map[string]float64{
  1824. "namespace2": 46.31,
  1825. },
  1826. windowStart: startYesterday,
  1827. windowEnd: endYesterday,
  1828. expMinutes: 1440.0,
  1829. },
  1830. // 7 Edge cases and errors
  1831. // 7a Empty AggregationProperties
  1832. // 7b Filter all
  1833. // 7c Share all
  1834. // 7d Share and filter the same allocations
  1835. }
  1836. for name, testcase := range cases {
  1837. if name != "4a" {
  1838. continue
  1839. }
  1840. t.Run(name, func(t *testing.T) {
  1841. if testcase.aggOpts != nil && testcase.aggOpts.IdleByNode {
  1842. as = GenerateMockAllocationSetNodeIdle(testcase.start)
  1843. } else {
  1844. as = GenerateMockAllocationSetClusterIdle(testcase.start)
  1845. }
  1846. err = as.AggregateBy(testcase.aggBy, testcase.aggOpts)
  1847. log.Infof("RESULTS")
  1848. for name, alloc := range as.Allocations {
  1849. log.Infof(" %s = %f", name, alloc.TotalCost())
  1850. }
  1851. assertAllocationSetTotals(t, as, name, err, testcase.numResults, testcase.totalCost)
  1852. assertAllocationTotals(t, as, name, testcase.results)
  1853. assertParcResults(t, as, name, testcase.expectedParcResults)
  1854. assertAllocationWindow(t, as, name, testcase.windowStart, testcase.windowEnd, testcase.expMinutes)
  1855. })
  1856. }
  1857. }
  1858. func TestAllocationSet_AggregateBy_SharedCostBreakdown(t *testing.T) {
  1859. // Set generated by GenerateMockAllocationSet
  1860. // | Hierarchy | Cost | CPU | RAM | GPU | PV | Net | LB |
  1861. // +----------------------------------------+------+------+------+------+------+------+------+
  1862. // cluster1:
  1863. // idle: 20.00 5.00 15.00 0.00 0.00 0.00 0.00
  1864. // namespace1:
  1865. // pod1:
  1866. // container1: [app1, env1] 16.00 1.00 11.00 1.00 1.00 1.00 1.00
  1867. // pod-abc: (deployment1)
  1868. // container2: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1869. // pod-def: (deployment1)
  1870. // container3: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1871. // namespace2:
  1872. // pod-ghi: (deployment2)
  1873. // container4: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1874. // container5: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1875. // pod-jkl: (daemonset1)
  1876. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1877. // +-----------------------------------------+------+------+------+------+------+------+------+
  1878. // cluster1 subtotal 66.00 11.00 31.00 6.00 6.00 6.00 6.00
  1879. // +-----------------------------------------+------+------+------+------+------+------+------+
  1880. // cluster2:
  1881. // idle: 10.00 5.00 5.00 0.00 0.00 0.00 0.00
  1882. // namespace2:
  1883. // pod-mno: (deployment2)
  1884. // container4: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1885. // container5: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1886. // pod-pqr: (daemonset1)
  1887. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1888. // namespace3:
  1889. // pod-stu: (deployment3)
  1890. // container7: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1891. // pod-vwx: (statefulset1)
  1892. // container8: an[team2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1893. // container9: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1894. // +----------------------------------------+------+------+------+------+------+------+------+
  1895. // cluster2 subtotal 46.00 11.00 11.00 6.00 6.00 6.00 6.00
  1896. // +----------------------------------------+------+------+------+------+------+------+------+
  1897. // total 112.00 22.00 42.00 12.00 12.00 12.00 12.00
  1898. // +----------------------------------------+------+------+------+------+------+------+------+
  1899. end := time.Now().UTC().Truncate(day)
  1900. start := end.Add(-day)
  1901. // This is ugly, but required because cannot import filterutil due to import cycle
  1902. namespaceEquals := func(ns string) *ast.EqualOp {
  1903. return &ast.EqualOp{
  1904. Left: ast.Identifier{
  1905. Field: ast.NewField(allocation.FieldNamespace),
  1906. Key: "",
  1907. },
  1908. Right: ns,
  1909. }
  1910. }
  1911. cases := map[string]struct {
  1912. start time.Time
  1913. aggBy []string
  1914. aggOpts *AllocationAggregationOptions
  1915. }{
  1916. "agg cluster, flat shared cost": {
  1917. start: start,
  1918. aggBy: []string{"cluster"},
  1919. aggOpts: &AllocationAggregationOptions{
  1920. SharedHourlyCosts: map[string]float64{"share_hourly": 10.0 / timeutil.HoursPerDay},
  1921. IncludeSharedCostBreakdown: true,
  1922. },
  1923. },
  1924. "agg namespace, shared namespace: namespace1": {
  1925. start: start,
  1926. aggBy: []string{"namespace"},
  1927. aggOpts: &AllocationAggregationOptions{
  1928. Share: namespaceEquals("namespace1"),
  1929. IncludeSharedCostBreakdown: true,
  1930. },
  1931. },
  1932. "agg namespace, shared namespace: namespace3": {
  1933. start: start,
  1934. aggBy: []string{"namespace"},
  1935. aggOpts: &AllocationAggregationOptions{
  1936. Share: namespaceEquals("namespace3"),
  1937. IncludeSharedCostBreakdown: true,
  1938. },
  1939. },
  1940. }
  1941. for name, tc := range cases {
  1942. t.Run(name, func(t *testing.T) {
  1943. as := GenerateMockAllocationSetClusterIdle(tc.start)
  1944. err := as.AggregateBy(tc.aggBy, tc.aggOpts)
  1945. if err != nil {
  1946. t.Fatalf("error aggregating: %s", err)
  1947. }
  1948. for _, alloc := range as.Allocations {
  1949. var breakdownTotal float64
  1950. // ignore idle since it should never have shared costs
  1951. if strings.Contains(alloc.Name, IdleSuffix) {
  1952. continue
  1953. }
  1954. for _, sharedAlloc := range alloc.SharedCostBreakdown {
  1955. breakdownTotal += sharedAlloc.TotalCost
  1956. totalInternal := sharedAlloc.CPUCost + sharedAlloc.GPUCost + sharedAlloc.RAMCost + sharedAlloc.NetworkCost + sharedAlloc.LBCost + sharedAlloc.PVCost + sharedAlloc.ExternalCost
  1957. // check that the total cost of a single item in the breakdown equals the sum of its parts
  1958. // we can ignore the overheadCost breakdown since it only has a total
  1959. if totalInternal != sharedAlloc.TotalCost && sharedAlloc.Name != "overheadCost" {
  1960. t.Errorf("expected internal total: %f; got %f", sharedAlloc.TotalCost, totalInternal)
  1961. }
  1962. }
  1963. // check that the totals of all shared cost breakdowns equal the allocation's SharedCost
  1964. if breakdownTotal != alloc.SharedCost {
  1965. t.Errorf("expected breakdown total: %f; got %f", alloc.SharedCost, breakdownTotal)
  1966. }
  1967. }
  1968. })
  1969. }
  1970. }
  1971. // TODO niko
  1972. //func TestAllocationSet_Clone(t *testing.T) {}
  1973. // TODO niko
  1974. //func TestAllocationSet_Delete(t *testing.T) {}
  1975. // TODO niko
  1976. //func TestAllocationSet_End(t *testing.T) {}
  1977. // TODO niko
  1978. //func TestAllocationSet_IdleAllocations(t *testing.T) {}
  1979. // TODO niko
  1980. //func TestAllocationSet_Insert(t *testing.T) {}
  1981. // Asserts that all Allocations within an AllocationSet have a Window that
  1982. // matches that of the AllocationSet.
  1983. func TestAllocationSet_insertMatchingWindow(t *testing.T) {
  1984. setStart := time.Now().Round(time.Hour)
  1985. setEnd := setStart.Add(1 * time.Hour)
  1986. a1WindowStart := setStart.Add(5 * time.Minute)
  1987. a1WindowEnd := setStart.Add(50 * time.Minute)
  1988. a2WindowStart := setStart.Add(17 * time.Minute)
  1989. a2WindowEnd := setStart.Add(34 * time.Minute)
  1990. a1 := &Allocation{
  1991. Name: "allocation-1",
  1992. Window: Window(NewClosedWindow(a1WindowStart, a1WindowEnd)),
  1993. }
  1994. a2 := &Allocation{
  1995. Name: "allocation-2",
  1996. Window: Window(NewClosedWindow(a2WindowStart, a2WindowEnd)),
  1997. }
  1998. as := NewAllocationSet(setStart, setEnd)
  1999. as.Insert(a1)
  2000. as.Insert(a2)
  2001. if as.Length() != 2 {
  2002. t.Errorf("AS length got %d, expected %d", as.Length(), 2)
  2003. }
  2004. for _, a := range as.Allocations {
  2005. if !(*a.Window.Start()).Equal(setStart) {
  2006. t.Errorf("Allocation %s window start is %s, expected %s", a.Name, *a.Window.Start(), setStart)
  2007. }
  2008. if !(*a.Window.End()).Equal(setEnd) {
  2009. t.Errorf("Allocation %s window end is %s, expected %s", a.Name, *a.Window.End(), setEnd)
  2010. }
  2011. }
  2012. }
  2013. // This tests PARC accumulation. Assuming Node cost is $1 per core per hour
  2014. // From https://github.com/opencost/opencost/pull/1867#discussion_r1174109388:
  2015. // Over the span of hour 1:
  2016. // Pod 1 runs for 30 minutes, consuming 1 CPU while alive. PARC: 12.5% (0.5 core-hours / 4 available core-hours)
  2017. // Pod 2 runs for 1 hour, consuming 2 CPU while alive. PARC: 50% (2 core-hours)
  2018. // Pod 3 runs for 1 hour, consuming 1 CPU while alive. PARC: 25% (1 core-hour)
  2019. // Over the span of hour 2:
  2020. // Pod 1 does not run. PARC: 0% (0 core-hours / 4 available core-hours)
  2021. // Pod 2 runs for 30 minutes, consuming 2 CPU while active. PARC: 25% (1 core-hour)
  2022. // Pod 3 runs for 1 hour, consuming 1 CPU while active. PARC: 25% (1 core-hour)
  2023. // Over the span of hour 3:
  2024. // Pod 1 does not run. PARC: 0% (0 core-hours / 4 available)
  2025. // Pod 2 runs for 30 minutes, consuming 3 CPU while active. PARC: 37.5% (1.5 core-hours)
  2026. // Pod 3 runs for 1 hour, consuming 1 CPU while active. PARC: 25% (1 core-hour)
  2027. // We expect the following accumulated PARC:
  2028. // Pod 1: (0.5 + 0 + 0) core-hours used / (4 + 4 + 4) core-hours available = 0.5/12 = 4.16%
  2029. // Pod 2: (2 + 1 + 1.5) / (4 + 4 + 4) = 4.5/12 = 37.5%
  2030. // Pod 3: (1 + 1 + 1) / (4 + 4 + 4) = 3/12 = 25%
  2031. func TestParcInsert(t *testing.T) {
  2032. pod1_hour1 := ProportionalAssetResourceCost{
  2033. Cluster: "cluster1",
  2034. Name: "node1",
  2035. Type: "Node",
  2036. ProviderID: "i-1234",
  2037. CPUPercentage: 0.125,
  2038. GPUPercentage: 0,
  2039. RAMPercentage: 0,
  2040. NodeResourceCostPercentage: 0,
  2041. CPUTotalCost: 4,
  2042. CPUProportionalCost: 0.5,
  2043. }
  2044. pod1_hour2 := ProportionalAssetResourceCost{
  2045. Cluster: "cluster1",
  2046. Name: "node1",
  2047. Type: "Node",
  2048. ProviderID: "i-1234",
  2049. CPUPercentage: 0.0,
  2050. GPUPercentage: 0,
  2051. RAMPercentage: 0,
  2052. NodeResourceCostPercentage: 0,
  2053. CPUTotalCost: 4,
  2054. }
  2055. pod1_hour3 := ProportionalAssetResourceCost{
  2056. Cluster: "cluster1",
  2057. Name: "node1",
  2058. Type: "Node",
  2059. ProviderID: "i-1234",
  2060. CPUPercentage: 0.0,
  2061. GPUPercentage: 0,
  2062. RAMPercentage: 0,
  2063. NodeResourceCostPercentage: 0,
  2064. CPUTotalCost: 4,
  2065. }
  2066. pod2_hour1 := ProportionalAssetResourceCost{
  2067. Cluster: "cluster1",
  2068. Name: "node2",
  2069. Type: "Node",
  2070. ProviderID: "i-1234",
  2071. CPUPercentage: 0.0,
  2072. GPUPercentage: 0,
  2073. RAMPercentage: 0,
  2074. NodeResourceCostPercentage: 0,
  2075. CPUTotalCost: 4,
  2076. CPUProportionalCost: 2,
  2077. }
  2078. pod2_hour2 := ProportionalAssetResourceCost{
  2079. Cluster: "cluster1",
  2080. Name: "node2",
  2081. Type: "Node",
  2082. ProviderID: "i-1234",
  2083. CPUPercentage: 0.0,
  2084. GPUPercentage: 0,
  2085. RAMPercentage: 0,
  2086. NodeResourceCostPercentage: 0,
  2087. CPUTotalCost: 4,
  2088. CPUProportionalCost: 1,
  2089. }
  2090. pod2_hour3 := ProportionalAssetResourceCost{
  2091. Cluster: "cluster1",
  2092. Name: "node2",
  2093. Type: "Node",
  2094. ProviderID: "i-1234",
  2095. CPUPercentage: 0.0,
  2096. GPUPercentage: 0,
  2097. RAMPercentage: 0,
  2098. NodeResourceCostPercentage: 0,
  2099. CPUTotalCost: 4,
  2100. CPUProportionalCost: 1.5,
  2101. }
  2102. pod3_hour1 := ProportionalAssetResourceCost{
  2103. Cluster: "cluster1",
  2104. Name: "node3",
  2105. Type: "Node",
  2106. ProviderID: "i-1234",
  2107. CPUPercentage: 0.0,
  2108. GPUPercentage: 0,
  2109. RAMPercentage: 0,
  2110. NodeResourceCostPercentage: 0,
  2111. CPUTotalCost: 4,
  2112. CPUProportionalCost: 1,
  2113. }
  2114. pod3_hour2 := ProportionalAssetResourceCost{
  2115. Cluster: "cluster1",
  2116. Name: "node3",
  2117. Type: "Node",
  2118. ProviderID: "i-1234",
  2119. CPUPercentage: 0.0,
  2120. GPUPercentage: 0,
  2121. RAMPercentage: 0,
  2122. NodeResourceCostPercentage: 0,
  2123. CPUTotalCost: 4,
  2124. CPUProportionalCost: 1,
  2125. }
  2126. pod3_hour3 := ProportionalAssetResourceCost{
  2127. Cluster: "cluster1",
  2128. Name: "node3",
  2129. Type: "Node",
  2130. ProviderID: "i-1234",
  2131. CPUPercentage: 0.0,
  2132. GPUPercentage: 0,
  2133. RAMPercentage: 0,
  2134. NodeResourceCostPercentage: 0,
  2135. CPUTotalCost: 4,
  2136. CPUProportionalCost: 1,
  2137. }
  2138. parcs := ProportionalAssetResourceCosts{}
  2139. parcs.Insert(pod1_hour1, true)
  2140. parcs.Insert(pod1_hour2, true)
  2141. parcs.Insert(pod1_hour3, true)
  2142. parcs.Insert(pod2_hour1, true)
  2143. parcs.Insert(pod2_hour2, true)
  2144. parcs.Insert(pod2_hour3, true)
  2145. parcs.Insert(pod3_hour1, true)
  2146. parcs.Insert(pod3_hour2, true)
  2147. parcs.Insert(pod3_hour3, true)
  2148. log.Debug("added all parcs")
  2149. // set totals, compute percentaves
  2150. parc1, ok := parcs["cluster1,node1"]
  2151. if !ok {
  2152. t.Fatalf("parc1 not found")
  2153. }
  2154. parc1.CPUTotalCost = 12
  2155. parc2, ok := parcs["cluster1,node2"]
  2156. if !ok {
  2157. t.Fatalf("parc2 not found")
  2158. }
  2159. parc2.CPUTotalCost = 12
  2160. parc3, ok := parcs["cluster1,node3"]
  2161. if !ok {
  2162. t.Fatalf("parc1 not found")
  2163. }
  2164. parc3.CPUTotalCost = 12
  2165. ComputePercentages(&parc1)
  2166. ComputePercentages(&parc2)
  2167. ComputePercentages(&parc3)
  2168. parcs["cluster1,node1"] = parc1
  2169. parcs["cluster1,node2"] = parc2
  2170. parcs["cluster1,node3"] = parc3
  2171. expectedParcs := ProportionalAssetResourceCosts{
  2172. "cluster1,node1": ProportionalAssetResourceCost{
  2173. CPUPercentage: 0.041666666666666664,
  2174. NodeResourceCostPercentage: 0.041666666666666664,
  2175. },
  2176. "cluster1,node2": ProportionalAssetResourceCost{
  2177. CPUPercentage: 0.375,
  2178. NodeResourceCostPercentage: 0.375,
  2179. },
  2180. "cluster1,node3": ProportionalAssetResourceCost{
  2181. CPUPercentage: 0.25,
  2182. NodeResourceCostPercentage: 0.25,
  2183. },
  2184. }
  2185. for key, expectedParc := range expectedParcs {
  2186. actualParc, ok := parcs[key]
  2187. if !ok {
  2188. t.Fatalf("did not find expected PARC: %s", key)
  2189. }
  2190. if actualParc.CPUPercentage != expectedParc.CPUPercentage {
  2191. t.Fatalf("actual parc cpu percentage: %f did not match expected: %f", actualParc.CPUPercentage, expectedParc.CPUPercentage)
  2192. }
  2193. if actualParc.NodeResourceCostPercentage != expectedParc.NodeResourceCostPercentage {
  2194. t.Fatalf("actual parc node percentage: %f did not match expected: %f", actualParc.NodeResourceCostPercentage, expectedParc.NodeResourceCostPercentage)
  2195. }
  2196. }
  2197. }
  2198. // TODO niko
  2199. //func TestAllocationSet_IsEmpty(t *testing.T) {}
  2200. // TODO niko
  2201. //func TestAllocationSet_Length(t *testing.T) {}
  2202. // TODO niko
  2203. //func TestAllocationSet_Map(t *testing.T) {}
  2204. // TODO niko
  2205. //func TestAllocationSet_MarshalJSON(t *testing.T) {}
  2206. // TODO niko
  2207. //func TestAllocationSet_Resolution(t *testing.T) {}
  2208. // TODO niko
  2209. //func TestAllocationSet_Seconds(t *testing.T) {}
  2210. // TODO niko
  2211. //func TestAllocationSet_Set(t *testing.T) {}
  2212. // TODO niko
  2213. //func TestAllocationSet_Start(t *testing.T) {}
  2214. // TODO niko
  2215. //func TestAllocationSet_TotalCost(t *testing.T) {}
  2216. // TODO niko
  2217. //func TestNewAllocationSetRange(t *testing.T) {}
  2218. func TestAllocationSetRange_AccumulateRepeat(t *testing.T) {
  2219. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2220. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2221. today := time.Now().UTC().Truncate(day)
  2222. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2223. a := GenerateMockAllocationSet(ago2d)
  2224. b := GenerateMockAllocationSet(yesterday)
  2225. c := GenerateMockAllocationSet(today)
  2226. d := GenerateMockAllocationSet(tomorrow)
  2227. asr := NewAllocationSetRange(a, b, c, d)
  2228. // Take Total Cost
  2229. totalCost := asr.TotalCost()
  2230. // NewAccumulation does not mutate
  2231. result, err := asr.newAccumulation()
  2232. if err != nil {
  2233. t.Fatal(err)
  2234. }
  2235. asr2 := NewAllocationSetRange(result)
  2236. // Ensure Costs Match
  2237. if totalCost != asr2.TotalCost() {
  2238. t.Fatalf("Accumulated Total Cost does not match original Total Cost")
  2239. }
  2240. // Next NewAccumulation() call should prove that there is no mutation of inner data
  2241. result, err = asr.newAccumulation()
  2242. if err != nil {
  2243. t.Fatal(err)
  2244. }
  2245. asr3 := NewAllocationSetRange(result)
  2246. // Costs should be correct, as multiple calls to NewAccumulation() should not alter
  2247. // the internals of the AllocationSetRange
  2248. if totalCost != asr3.TotalCost() {
  2249. t.Fatalf("Accumulated Total Cost does not match original Total Cost. %f != %f", totalCost, asr3.TotalCost())
  2250. }
  2251. }
  2252. func TestAllocationSetRange_Accumulate(t *testing.T) {
  2253. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2254. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2255. today := time.Now().UTC().Truncate(day)
  2256. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2257. // Accumulating any combination of nil and/or empty set should result in empty set
  2258. result, err := NewAllocationSetRange(nil).accumulate()
  2259. if err != nil {
  2260. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2261. }
  2262. if !result.IsEmpty() {
  2263. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2264. }
  2265. result, err = NewAllocationSetRange(nil, nil).accumulate()
  2266. if err != nil {
  2267. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2268. }
  2269. if !result.IsEmpty() {
  2270. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2271. }
  2272. result, err = NewAllocationSetRange(NewAllocationSet(yesterday, today)).accumulate()
  2273. if err != nil {
  2274. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2275. }
  2276. if !result.IsEmpty() {
  2277. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2278. }
  2279. result, err = NewAllocationSetRange(nil, NewAllocationSet(ago2d, yesterday), nil, NewAllocationSet(today, tomorrow), nil).accumulate()
  2280. if err != nil {
  2281. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2282. }
  2283. if !result.IsEmpty() {
  2284. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2285. }
  2286. todayAS := NewAllocationSet(today, tomorrow)
  2287. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2288. yesterdayAS := NewAllocationSet(yesterday, today)
  2289. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2290. // Accumulate non-nil with nil should result in copy of non-nil, regardless of order
  2291. result, err = NewAllocationSetRange(nil, todayAS).accumulate()
  2292. if err != nil {
  2293. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2294. }
  2295. if result == nil {
  2296. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2297. }
  2298. if result.TotalCost() != 6.0 {
  2299. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  2300. }
  2301. result, err = NewAllocationSetRange(todayAS, nil).accumulate()
  2302. if err != nil {
  2303. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2304. }
  2305. if result == nil {
  2306. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2307. }
  2308. if result.TotalCost() != 6.0 {
  2309. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  2310. }
  2311. result, err = NewAllocationSetRange(nil, todayAS, nil).accumulate()
  2312. if err != nil {
  2313. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2314. }
  2315. if result == nil {
  2316. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2317. }
  2318. if result.TotalCost() != 6.0 {
  2319. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  2320. }
  2321. // Accumulate two non-nil should result in sum of both with appropriate start, end
  2322. result, err = NewAllocationSetRange(yesterdayAS, todayAS).accumulate()
  2323. if err != nil {
  2324. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2325. }
  2326. if result == nil {
  2327. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2328. }
  2329. if result.TotalCost() != 12.0 {
  2330. t.Fatalf("accumulating AllocationSetRange: expected total cost 12.0; actual %f", result.TotalCost())
  2331. }
  2332. allocMap := result.Allocations
  2333. if len(allocMap) != 1 {
  2334. t.Fatalf("accumulating AllocationSetRange: expected length 1; actual length %d", len(allocMap))
  2335. }
  2336. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  2337. if alloc == nil {
  2338. t.Fatalf("accumulating AllocationSetRange: expected allocation 'cluster1/namespace1/pod1/container1'")
  2339. }
  2340. if alloc.CPUCoreHours != 2.0 {
  2341. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", result.TotalCost())
  2342. }
  2343. if alloc.CPUCost != 2.0 {
  2344. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.CPUCost)
  2345. }
  2346. if alloc.CPUEfficiency() != 1.0 {
  2347. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.CPUEfficiency())
  2348. }
  2349. if alloc.GPUHours != 2.0 {
  2350. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.GPUHours)
  2351. }
  2352. if alloc.GPUCost != 2.0 {
  2353. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.GPUCost)
  2354. }
  2355. if alloc.NetworkCost != 2.0 {
  2356. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.NetworkCost)
  2357. }
  2358. if alloc.LoadBalancerCost != 2.0 {
  2359. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.LoadBalancerCost)
  2360. }
  2361. if alloc.PVByteHours() != 2.0 {
  2362. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.PVByteHours())
  2363. }
  2364. if alloc.PVCost() != 2.0 {
  2365. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.PVCost())
  2366. }
  2367. if alloc.RAMByteHours != 2.0 {
  2368. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.RAMByteHours)
  2369. }
  2370. if alloc.RAMCost != 2.0 {
  2371. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.RAMCost)
  2372. }
  2373. if alloc.RAMEfficiency() != 1.0 {
  2374. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.RAMEfficiency())
  2375. }
  2376. if alloc.TotalCost() != 12.0 {
  2377. t.Fatalf("accumulating AllocationSetRange: expected 12.0; actual %f", alloc.TotalCost())
  2378. }
  2379. if alloc.TotalEfficiency() != 1.0 {
  2380. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.TotalEfficiency())
  2381. }
  2382. if !alloc.Start.Equal(yesterday) {
  2383. t.Fatalf("accumulating AllocationSetRange: expected to start %s; actual %s", yesterday, alloc.Start)
  2384. }
  2385. if !alloc.End.Equal(tomorrow) {
  2386. t.Fatalf("accumulating AllocationSetRange: expected to end %s; actual %s", tomorrow, alloc.End)
  2387. }
  2388. if alloc.Minutes() != 2880.0 {
  2389. t.Fatalf("accumulating AllocationSetRange: expected %f minutes; actual %f", 2880.0, alloc.Minutes())
  2390. }
  2391. }
  2392. func TestAllocationSetRange_AccumulateBy_None(t *testing.T) {
  2393. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2394. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2395. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2396. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2397. today := time.Now().UTC().Truncate(day)
  2398. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2399. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2400. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2401. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2402. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2403. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2404. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2405. yesterdayAS := NewAllocationSet(yesterday, today)
  2406. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2407. todayAS := NewAllocationSet(today, tomorrow)
  2408. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2409. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2410. asr, err := asr.Accumulate(AccumulateOptionNone)
  2411. if err != nil {
  2412. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2413. }
  2414. if len(asr.Allocations) != 5 {
  2415. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  2416. }
  2417. }
  2418. func TestAllocationSetRange_AccumulateBy_All(t *testing.T) {
  2419. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2420. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2421. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2422. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2423. today := time.Now().UTC().Truncate(day)
  2424. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2425. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2426. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2427. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2428. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2429. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2430. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2431. yesterdayAS := NewAllocationSet(yesterday, today)
  2432. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2433. todayAS := NewAllocationSet(today, tomorrow)
  2434. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2435. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2436. asr, err := asr.Accumulate(AccumulateOptionAll)
  2437. if err != nil {
  2438. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2439. }
  2440. if len(asr.Allocations) != 1 {
  2441. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  2442. }
  2443. allocMap := asr.Allocations[0].Allocations
  2444. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  2445. if alloc.Minutes() != 4320.0 {
  2446. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 4320.0, alloc.Minutes())
  2447. }
  2448. }
  2449. func TestAllocationSetRange_AccumulateBy_Hour(t *testing.T) {
  2450. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  2451. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  2452. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  2453. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  2454. currentHour := time.Now().UTC().Truncate(time.Hour)
  2455. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  2456. ago4hAS := NewAllocationSet(ago4h, ago3h)
  2457. ago4hAS.Set(NewMockUnitAllocation("4", ago4h, time.Hour, nil))
  2458. ago3hAS := NewAllocationSet(ago3h, ago2h)
  2459. ago3hAS.Set(NewMockUnitAllocation("a", ago3h, time.Hour, nil))
  2460. ago2hAS := NewAllocationSet(ago2h, ago1h)
  2461. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  2462. ago1hAS := NewAllocationSet(ago1h, currentHour)
  2463. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  2464. currentHourAS := NewAllocationSet(currentHour, nextHour)
  2465. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  2466. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  2467. asr, err := asr.Accumulate(AccumulateOptionHour)
  2468. if err != nil {
  2469. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2470. }
  2471. if len(asr.Allocations) != 5 {
  2472. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  2473. }
  2474. allocMap := asr.Allocations[0].Allocations
  2475. alloc := allocMap["4"]
  2476. if alloc.Minutes() != 60.0 {
  2477. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 60.0, alloc.Minutes())
  2478. }
  2479. }
  2480. func TestAllocationSetRange_AccumulateBy_Day_From_Day(t *testing.T) {
  2481. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2482. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2483. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2484. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2485. today := time.Now().UTC().Truncate(day)
  2486. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2487. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2488. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2489. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2490. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2491. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2492. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2493. yesterdayAS := NewAllocationSet(yesterday, today)
  2494. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2495. todayAS := NewAllocationSet(today, tomorrow)
  2496. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2497. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2498. asr, err := asr.Accumulate(AccumulateOptionDay)
  2499. if err != nil {
  2500. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2501. }
  2502. if len(asr.Allocations) != 5 {
  2503. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  2504. }
  2505. allocMap := asr.Allocations[0].Allocations
  2506. alloc := allocMap["4"]
  2507. if alloc.Minutes() != 1440.0 {
  2508. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 1440.0, alloc.Minutes())
  2509. }
  2510. }
  2511. func TestAllocationSetRange_AccumulateBy_Day_From_Hours(t *testing.T) {
  2512. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  2513. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  2514. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  2515. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  2516. currentHour := time.Now().UTC().Truncate(time.Hour)
  2517. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  2518. ago4hAS := NewAllocationSet(ago4h, ago3h)
  2519. ago4hAS.Set(NewMockUnitAllocation("", ago4h, time.Hour, nil))
  2520. ago3hAS := NewAllocationSet(ago3h, ago2h)
  2521. ago3hAS.Set(NewMockUnitAllocation("", ago3h, time.Hour, nil))
  2522. ago2hAS := NewAllocationSet(ago2h, ago1h)
  2523. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  2524. ago1hAS := NewAllocationSet(ago1h, currentHour)
  2525. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  2526. currentHourAS := NewAllocationSet(currentHour, nextHour)
  2527. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  2528. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  2529. asr, err := asr.Accumulate(AccumulateOptionDay)
  2530. if err != nil {
  2531. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2532. }
  2533. if len(asr.Allocations) != 1 && len(asr.Allocations) != 2 {
  2534. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  2535. }
  2536. allocMap := asr.Allocations[0].Allocations
  2537. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  2538. if alloc.Minutes() > 300.0 {
  2539. t.Errorf("accumulating AllocationSetRange: expected %f or less minutes; actual %f", 300.0, alloc.Minutes())
  2540. }
  2541. }
  2542. func TestAllocationSetRange_AccumulateBy_Week(t *testing.T) {
  2543. ago9d := time.Now().UTC().Truncate(day).Add(-9 * day)
  2544. ago8d := time.Now().UTC().Truncate(day).Add(-8 * day)
  2545. ago7d := time.Now().UTC().Truncate(day).Add(-7 * day)
  2546. ago6d := time.Now().UTC().Truncate(day).Add(-6 * day)
  2547. ago5d := time.Now().UTC().Truncate(day).Add(-5 * day)
  2548. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2549. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2550. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2551. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2552. today := time.Now().UTC().Truncate(day)
  2553. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2554. ago9dAS := NewAllocationSet(ago9d, ago8d)
  2555. ago9dAS.Set(NewMockUnitAllocation("4", ago9d, day, nil))
  2556. ago8dAS := NewAllocationSet(ago8d, ago7d)
  2557. ago8dAS.Set(NewMockUnitAllocation("4", ago8d, day, nil))
  2558. ago7dAS := NewAllocationSet(ago7d, ago6d)
  2559. ago7dAS.Set(NewMockUnitAllocation("4", ago7d, day, nil))
  2560. ago6dAS := NewAllocationSet(ago6d, ago5d)
  2561. ago6dAS.Set(NewMockUnitAllocation("4", ago6d, day, nil))
  2562. ago5dAS := NewAllocationSet(ago5d, ago4d)
  2563. ago5dAS.Set(NewMockUnitAllocation("4", ago5d, day, nil))
  2564. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2565. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2566. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2567. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2568. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2569. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2570. yesterdayAS := NewAllocationSet(yesterday, today)
  2571. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2572. todayAS := NewAllocationSet(today, tomorrow)
  2573. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2574. asr := NewAllocationSetRange(ago9dAS, ago8dAS, ago7dAS, ago6dAS, ago5dAS, ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2575. asr, err := asr.Accumulate(AccumulateOptionWeek)
  2576. if err != nil {
  2577. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2578. }
  2579. if len(asr.Allocations) != 2 && len(asr.Allocations) != 3 {
  2580. t.Fatalf("expected 2 or 3 allocation sets, got:%d", len(asr.Allocations))
  2581. }
  2582. for _, as := range asr.Allocations {
  2583. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*7 {
  2584. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  2585. }
  2586. }
  2587. }
  2588. func TestAllocationSetRange_AccumulateBy_Month(t *testing.T) {
  2589. prevMonth1stDay := time.Date(2020, 01, 29, 0, 0, 0, 0, time.UTC)
  2590. prevMonth2ndDay := time.Date(2020, 01, 30, 0, 0, 0, 0, time.UTC)
  2591. prevMonth3ndDay := time.Date(2020, 01, 31, 0, 0, 0, 0, time.UTC)
  2592. nextMonth1stDay := time.Date(2020, 02, 01, 0, 0, 0, 0, time.UTC)
  2593. nextMonth2ndDay := time.Date(2020, 02, 02, 0, 0, 0, 0, time.UTC)
  2594. prev1AS := NewAllocationSet(prevMonth1stDay, prevMonth2ndDay)
  2595. prev1AS.Set(NewMockUnitAllocation("", prevMonth1stDay, day, nil))
  2596. prev2AS := NewAllocationSet(prevMonth2ndDay, prevMonth3ndDay)
  2597. prev2AS.Set(NewMockUnitAllocation("", prevMonth2ndDay, day, nil))
  2598. prev3AS := NewAllocationSet(prevMonth3ndDay, nextMonth1stDay)
  2599. prev3AS.Set(NewMockUnitAllocation("", prevMonth3ndDay, day, nil))
  2600. nextAS := NewAllocationSet(nextMonth1stDay, nextMonth2ndDay)
  2601. nextAS.Set(NewMockUnitAllocation("", nextMonth1stDay, day, nil))
  2602. asr := NewAllocationSetRange(prev1AS, prev2AS, prev3AS, nextAS)
  2603. asr, err := asr.Accumulate(AccumulateOptionMonth)
  2604. if err != nil {
  2605. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2606. }
  2607. if len(asr.Allocations) != 2 {
  2608. t.Fatalf("expected 2 allocation sets, got:%d", len(asr.Allocations))
  2609. }
  2610. for _, as := range asr.Allocations {
  2611. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*31 {
  2612. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  2613. }
  2614. }
  2615. }
  2616. func TestAllocationSetRange_AccumulateBy_Quarter(t *testing.T) {
  2617. q1Day1 := time.Date(2020, 3, 30, 0, 0, 0, 0, time.UTC)
  2618. q1Day2 := time.Date(2020, 3, 31, 0, 0, 0, 0, time.UTC)
  2619. q2Day1 := time.Date(2020, 4, 1, 0, 0, 0, 0, time.UTC)
  2620. q2Day2 := time.Date(2020, 4, 2, 0, 0, 0, 0, time.UTC)
  2621. q1AS1 := NewAllocationSet(q1Day1, q1Day2)
  2622. q1AS1.Set(NewMockUnitAllocation("", q1Day1, day, nil))
  2623. q1AS2 := NewAllocationSet(q1Day2, q2Day1)
  2624. q1AS2.Set(NewMockUnitAllocation("", q1Day2, day, nil))
  2625. q2AS1 := NewAllocationSet(q2Day1, q2Day2)
  2626. q2AS1.Set(NewMockUnitAllocation("", q2Day1, day, nil))
  2627. asr := NewAllocationSetRange(q1AS1, q1AS2, q2AS1)
  2628. asr, err := asr.Accumulate(AccumulateOptionQuarter)
  2629. if err != nil {
  2630. t.Fatalf("unexpected error calling accumulateBy quarter: %s", err)
  2631. }
  2632. if len(asr.Allocations) != 2 {
  2633. t.Fatalf("expected 2 allocation sets, got:%d", len(asr.Allocations))
  2634. }
  2635. for _, as := range asr.Allocations {
  2636. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*92 {
  2637. t.Fatalf("expected window duration to be between 1 and 92 days, got:%s", as.Window.Duration().String())
  2638. }
  2639. }
  2640. }
  2641. // TODO niko
  2642. // func TestAllocationSetRange_AggregateBy(t *testing.T) {}
  2643. // TODO niko
  2644. // func TestAllocationSetRange_Append(t *testing.T) {}
  2645. // TODO niko
  2646. // func TestAllocationSetRange_Each(t *testing.T) {}
  2647. // TODO niko
  2648. // func TestAllocationSetRange_Get(t *testing.T) {}
  2649. func TestAllocationSetRange_InsertRange(t *testing.T) {
  2650. // Set up
  2651. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2652. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2653. today := time.Now().UTC().Truncate(day)
  2654. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2655. unit := NewMockUnitAllocation("", today, day, nil)
  2656. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2657. ago2dAS.Set(NewMockUnitAllocation("a", ago2d, day, nil))
  2658. ago2dAS.Set(NewMockUnitAllocation("b", ago2d, day, nil))
  2659. ago2dAS.Set(NewMockUnitAllocation("c", ago2d, day, nil))
  2660. yesterdayAS := NewAllocationSet(yesterday, today)
  2661. yesterdayAS.Set(NewMockUnitAllocation("a", yesterday, day, nil))
  2662. yesterdayAS.Set(NewMockUnitAllocation("b", yesterday, day, nil))
  2663. yesterdayAS.Set(NewMockUnitAllocation("c", yesterday, day, nil))
  2664. todayAS := NewAllocationSet(today, tomorrow)
  2665. todayAS.Set(NewMockUnitAllocation("a", today, day, nil))
  2666. todayAS.Set(NewMockUnitAllocation("b", today, day, nil))
  2667. todayAS.Set(NewMockUnitAllocation("c", today, day, nil))
  2668. var nilASR *AllocationSetRange
  2669. thisASR := NewAllocationSetRange(yesterdayAS.Clone(), todayAS.Clone())
  2670. thatASR := NewAllocationSetRange(yesterdayAS.Clone())
  2671. longASR := NewAllocationSetRange(ago2dAS.Clone(), yesterdayAS.Clone(), todayAS.Clone())
  2672. var err error
  2673. // Expect an error calling InsertRange on nil
  2674. err = nilASR.InsertRange(thatASR)
  2675. if err == nil {
  2676. t.Fatalf("expected error, got nil")
  2677. }
  2678. // Expect nothing to happen calling InsertRange(nil) on non-nil ASR
  2679. err = thisASR.InsertRange(nil)
  2680. if err != nil {
  2681. t.Fatalf("unexpected error: %s", err)
  2682. }
  2683. for _, as := range thisASR.Allocations {
  2684. for k, a := range as.Allocations {
  2685. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2686. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2687. }
  2688. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2689. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2690. }
  2691. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2692. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2693. }
  2694. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2695. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2696. }
  2697. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2698. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2699. }
  2700. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2701. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2702. }
  2703. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2704. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2705. }
  2706. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2707. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2708. }
  2709. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2710. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2711. }
  2712. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2713. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2714. }
  2715. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2716. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2717. }
  2718. }
  2719. }
  2720. // Expect an error calling InsertRange with a range exceeding the receiver
  2721. err = thisASR.InsertRange(longASR)
  2722. if err == nil {
  2723. t.Fatalf("expected error calling InsertRange with a range exceeding the receiver")
  2724. }
  2725. // Expect each Allocation in "today" to stay the same, but "yesterday" to
  2726. // precisely double when inserting a range that only has a duplicate of
  2727. // "yesterday", but no entry for "today"
  2728. err = thisASR.InsertRange(thatASR)
  2729. if err != nil {
  2730. t.Fatalf("unexpected error: %s", err)
  2731. }
  2732. yAS, err := thisASR.Get(0)
  2733. for k, a := range yAS.Allocations {
  2734. if !util.IsApproximately(a.CPUCoreHours, 2*unit.CPUCoreHours) {
  2735. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2736. }
  2737. if !util.IsApproximately(a.CPUCost, 2*unit.CPUCost) {
  2738. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2739. }
  2740. if !util.IsApproximately(a.RAMByteHours, 2*unit.RAMByteHours) {
  2741. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2742. }
  2743. if !util.IsApproximately(a.RAMCost, 2*unit.RAMCost) {
  2744. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2745. }
  2746. if !util.IsApproximately(a.GPUHours, 2*unit.GPUHours) {
  2747. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2748. }
  2749. if !util.IsApproximately(a.GPUCost, 2*unit.GPUCost) {
  2750. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2751. }
  2752. if !util.IsApproximately(a.PVByteHours(), 2*unit.PVByteHours()) {
  2753. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2754. }
  2755. if !util.IsApproximately(a.PVCost(), 2*unit.PVCost()) {
  2756. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2757. }
  2758. if !util.IsApproximately(a.NetworkCost, 2*unit.NetworkCost) {
  2759. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2760. }
  2761. if !util.IsApproximately(a.LoadBalancerCost, 2*unit.LoadBalancerCost) {
  2762. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2763. }
  2764. if !util.IsApproximately(a.TotalCost(), 2*unit.TotalCost()) {
  2765. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2766. }
  2767. }
  2768. tAS, err := thisASR.Get(1)
  2769. for k, a := range tAS.Allocations {
  2770. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2771. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2772. }
  2773. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2774. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2775. }
  2776. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2777. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2778. }
  2779. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2780. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2781. }
  2782. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2783. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2784. }
  2785. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2786. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2787. }
  2788. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2789. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2790. }
  2791. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2792. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2793. }
  2794. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2795. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2796. }
  2797. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2798. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2799. }
  2800. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2801. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2802. }
  2803. }
  2804. }
  2805. // TODO niko
  2806. // func TestAllocationSetRange_Length(t *testing.T) {}
  2807. func TestAllocationSetRange_MarshalJSON(t *testing.T) {
  2808. tests := []struct {
  2809. name string
  2810. arg *AllocationSetRange
  2811. expected *AllocationSetRange
  2812. }{
  2813. {
  2814. name: "Nil ASR",
  2815. arg: nil,
  2816. },
  2817. {
  2818. name: "Nil AS in ASR",
  2819. arg: NewAllocationSetRange(nil),
  2820. },
  2821. {
  2822. name: "Normal ASR",
  2823. arg: &AllocationSetRange{
  2824. Allocations: []*AllocationSet{
  2825. {
  2826. Allocations: map[string]*Allocation{
  2827. "a": {
  2828. Start: time.Now().UTC().Truncate(day),
  2829. },
  2830. },
  2831. },
  2832. },
  2833. },
  2834. },
  2835. }
  2836. for _, test := range tests {
  2837. bytes, err := json.Marshal(test.arg)
  2838. if err != nil {
  2839. t.Fatalf("ASR Marshal: test %s, unexpected error: %s", test.name, err)
  2840. }
  2841. var testASR []*AllocationSet
  2842. marshaled := &testASR
  2843. err = json.Unmarshal(bytes, marshaled)
  2844. if err != nil {
  2845. t.Fatalf("ASR Unmarshal: test %s: unexpected error: %s", test.name, err)
  2846. }
  2847. if test.arg.Length() != len(testASR) {
  2848. t.Fatalf("ASR Unmarshal: test %s: length mutated in encoding: expected %d but got %d", test.name, test.arg.Length(), len(testASR))
  2849. }
  2850. // Allocations don't unmarshal back from json
  2851. }
  2852. }
  2853. // TODO niko
  2854. // func TestAllocationSetRange_Slice(t *testing.T) {}
  2855. // TODO niko
  2856. // func TestAllocationSetRange_Window(t *testing.T) {}
  2857. func TestAllocationSetRange_Start(t *testing.T) {
  2858. tests := []struct {
  2859. name string
  2860. arg *AllocationSetRange
  2861. expectError bool
  2862. expected time.Time
  2863. }{
  2864. {
  2865. name: "Empty ASR",
  2866. arg: nil,
  2867. expectError: true,
  2868. },
  2869. {
  2870. name: "Single allocation",
  2871. arg: &AllocationSetRange{
  2872. Allocations: []*AllocationSet{
  2873. {
  2874. Allocations: map[string]*Allocation{
  2875. "a": {
  2876. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2877. },
  2878. },
  2879. },
  2880. },
  2881. },
  2882. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2883. },
  2884. {
  2885. name: "Two allocations",
  2886. arg: &AllocationSetRange{
  2887. Allocations: []*AllocationSet{
  2888. {
  2889. Allocations: map[string]*Allocation{
  2890. "a": {
  2891. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2892. },
  2893. "b": {
  2894. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2895. },
  2896. },
  2897. },
  2898. },
  2899. },
  2900. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2901. },
  2902. {
  2903. name: "Two AllocationSets",
  2904. arg: &AllocationSetRange{
  2905. Allocations: []*AllocationSet{
  2906. {
  2907. Allocations: map[string]*Allocation{
  2908. "a": {
  2909. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2910. },
  2911. },
  2912. },
  2913. {
  2914. Allocations: map[string]*Allocation{
  2915. "b": {
  2916. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2917. },
  2918. },
  2919. },
  2920. },
  2921. },
  2922. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2923. },
  2924. }
  2925. for _, test := range tests {
  2926. result, err := test.arg.Start()
  2927. if test.expectError && err != nil {
  2928. continue
  2929. }
  2930. if test.expectError && err == nil {
  2931. t.Errorf("%s: expected error and got none", test.name)
  2932. } else if result != test.expected {
  2933. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2934. }
  2935. }
  2936. }
  2937. func TestAllocationSetRange_End(t *testing.T) {
  2938. tests := []struct {
  2939. name string
  2940. arg *AllocationSetRange
  2941. expectError bool
  2942. expected time.Time
  2943. }{
  2944. {
  2945. name: "Empty ASR",
  2946. arg: nil,
  2947. expectError: true,
  2948. },
  2949. {
  2950. name: "Single allocation",
  2951. arg: &AllocationSetRange{
  2952. Allocations: []*AllocationSet{
  2953. {
  2954. Allocations: map[string]*Allocation{
  2955. "a": {
  2956. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2957. },
  2958. },
  2959. },
  2960. },
  2961. },
  2962. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2963. },
  2964. {
  2965. name: "Two allocations",
  2966. arg: &AllocationSetRange{
  2967. Allocations: []*AllocationSet{
  2968. {
  2969. Allocations: map[string]*Allocation{
  2970. "a": {
  2971. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2972. },
  2973. "b": {
  2974. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2975. },
  2976. },
  2977. },
  2978. },
  2979. },
  2980. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2981. },
  2982. {
  2983. name: "Two AllocationSets",
  2984. arg: &AllocationSetRange{
  2985. Allocations: []*AllocationSet{
  2986. {
  2987. Allocations: map[string]*Allocation{
  2988. "a": {
  2989. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2990. },
  2991. },
  2992. },
  2993. {
  2994. Allocations: map[string]*Allocation{
  2995. "b": {
  2996. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2997. },
  2998. },
  2999. },
  3000. },
  3001. },
  3002. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  3003. },
  3004. }
  3005. for _, test := range tests {
  3006. result, err := test.arg.End()
  3007. if test.expectError && err != nil {
  3008. continue
  3009. }
  3010. if test.expectError && err == nil {
  3011. t.Errorf("%s: expected error and got none", test.name)
  3012. } else if result != test.expected {
  3013. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  3014. }
  3015. }
  3016. }
  3017. func TestAllocationSetRange_Minutes(t *testing.T) {
  3018. tests := []struct {
  3019. name string
  3020. arg *AllocationSetRange
  3021. expected float64
  3022. }{
  3023. {
  3024. name: "Empty ASR",
  3025. arg: nil,
  3026. expected: 0,
  3027. },
  3028. {
  3029. name: "Single allocation",
  3030. arg: &AllocationSetRange{
  3031. Allocations: []*AllocationSet{
  3032. {
  3033. Allocations: map[string]*Allocation{
  3034. "a": {
  3035. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  3036. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  3037. },
  3038. },
  3039. },
  3040. },
  3041. },
  3042. expected: 24 * 60,
  3043. },
  3044. {
  3045. name: "Two allocations",
  3046. arg: &AllocationSetRange{
  3047. Allocations: []*AllocationSet{
  3048. {
  3049. Allocations: map[string]*Allocation{
  3050. "a": {
  3051. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  3052. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  3053. },
  3054. "b": {
  3055. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  3056. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  3057. },
  3058. },
  3059. },
  3060. },
  3061. },
  3062. expected: 2 * 24 * 60,
  3063. },
  3064. {
  3065. name: "Two AllocationSets",
  3066. arg: &AllocationSetRange{
  3067. Allocations: []*AllocationSet{
  3068. {
  3069. Allocations: map[string]*Allocation{
  3070. "a": {
  3071. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  3072. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  3073. },
  3074. },
  3075. },
  3076. {
  3077. Allocations: map[string]*Allocation{
  3078. "b": {
  3079. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  3080. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  3081. },
  3082. },
  3083. },
  3084. },
  3085. },
  3086. expected: 2 * 24 * 60,
  3087. },
  3088. }
  3089. for _, test := range tests {
  3090. result := test.arg.Minutes()
  3091. if result != test.expected {
  3092. t.Errorf("%s: expected %f but got %f", test.name, test.expected, result)
  3093. }
  3094. }
  3095. }
  3096. func TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate(t *testing.T) {
  3097. today := time.Now().Round(day)
  3098. start := today.AddDate(0, 0, -4)
  3099. var allocationSets []*AllocationSet
  3100. for i := 0; i < 4; i++ {
  3101. allocationSets = append(allocationSets, GenerateMockAllocationSet(start))
  3102. start = start.AddDate(0, 0, 1)
  3103. }
  3104. var originalAllocationSets []*AllocationSet
  3105. for _, as := range allocationSets {
  3106. originalAllocationSets = append(originalAllocationSets, as.Clone())
  3107. }
  3108. asr := NewAllocationSetRange()
  3109. for _, as := range allocationSets {
  3110. asr.Append(as.Clone())
  3111. }
  3112. expected, err := asr.accumulate()
  3113. if err != nil {
  3114. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: AllocationSetRange.Accumulate() returned an error\n")
  3115. }
  3116. var got *AllocationSet
  3117. for i := 0; i < len(allocationSets); i++ {
  3118. got, err = got.Accumulate(allocationSets[i])
  3119. if err != nil {
  3120. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Accumulate(allocationSets[%d]) returned an error\n", i)
  3121. }
  3122. }
  3123. // compare the got and expected Allocation sets, ensure that they match
  3124. if len(got.Allocations) != len(expected.Allocations) {
  3125. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.Allocations does not match length of expected.Allocations\n")
  3126. }
  3127. for key, a := range got.Allocations {
  3128. if _, ok := expected.Allocations[key]; !ok {
  3129. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] not found in expected.Allocations\n", key)
  3130. }
  3131. if !a.Equal(expected.Allocations[key]) {
  3132. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] did not match expected.Allocations[%[1]s]", key)
  3133. }
  3134. }
  3135. if len(got.ExternalKeys) != len(expected.ExternalKeys) {
  3136. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.ExternalKeys does not match length of expected.ExternalKeys\n")
  3137. }
  3138. if len(got.IdleKeys) != len(expected.IdleKeys) {
  3139. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.IdleKeys does not match length of expected.IdleKeys\n")
  3140. }
  3141. if !got.Window.Start().UTC().Equal(expected.Window.Start().UTC()) {
  3142. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.start: got:%s, expected:%s\n", got.Window.Start(), expected.Window.Start())
  3143. }
  3144. if !got.Window.End().UTC().Equal(expected.Window.End().UTC()) {
  3145. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.end: got:%s, expected:%s\n", got.Window.End(), expected.Window.End())
  3146. }
  3147. for i := range allocationSets {
  3148. for key, allocation := range allocationSets[i].Allocations {
  3149. if !allocation.Equal(originalAllocationSets[i].Allocations[key]) {
  3150. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: allocationSet has been mutated in Accumulate; allocationSet: %d, allocation: %s\n", i, key)
  3151. }
  3152. }
  3153. }
  3154. }
  3155. func Test_AggregateByService_UnmountedLBs(t *testing.T) {
  3156. end := time.Now().UTC().Truncate(day)
  3157. start := end.Add(-day)
  3158. normalProps := &AllocationProperties{
  3159. Cluster: "cluster-one",
  3160. Container: "nginx-plus-nginx-ingress",
  3161. Controller: "nginx-plus-nginx-ingress",
  3162. ControllerKind: "deployment",
  3163. Namespace: "nginx-plus",
  3164. Pod: "nginx-plus-nginx-ingress-123a4b5678-ab12c",
  3165. ProviderID: "test",
  3166. Node: "testnode",
  3167. Services: []string{
  3168. "nginx-plus-nginx-ingress",
  3169. },
  3170. }
  3171. problematicProps := &AllocationProperties{
  3172. Cluster: "cluster-one",
  3173. Container: UnmountedSuffix,
  3174. Namespace: UnmountedSuffix,
  3175. Pod: UnmountedSuffix,
  3176. ProviderID: "test",
  3177. Node: "testnode",
  3178. Services: []string{
  3179. "nginx-plus-nginx-ingress",
  3180. "ingress-nginx-controller",
  3181. "pacman",
  3182. },
  3183. }
  3184. idle := NewMockUnitAllocation(fmt.Sprintf("cluster-one/%s", IdleSuffix), start, day, &AllocationProperties{
  3185. Cluster: "cluster-one",
  3186. })
  3187. // this allocation is the main point of the test; an unmounted LB that has services
  3188. problematicAllocation := NewMockUnitAllocation("cluster-one//__unmounted__/__unmounted__/__unmounted__", start, day, problematicProps)
  3189. two := NewMockUnitAllocation("cluster-one//nginx-plus/nginx-plus-nginx-ingress-123a4b5678-ab12c/nginx-plus-nginx-ingress", start, day, normalProps)
  3190. three := NewMockUnitAllocation("cluster-one//nginx-plus/nginx-plus-nginx-ingress-123a4b5678-ab12c/nginx-plus-nginx-ingress", start, day, normalProps)
  3191. four := NewMockUnitAllocation("cluster-one//nginx-plus/nginx-plus-nginx-ingress-123a4b5678-ab12c/nginx-plus-nginx-ingress", start, day, normalProps)
  3192. problematicAllocation.ExternalCost = 2.35
  3193. two.ExternalCost = 1.35
  3194. three.ExternalCost = 2.60
  3195. four.ExternalCost = 4.30
  3196. set := NewAllocationSet(start, start.Add(day), problematicAllocation, two, three, four)
  3197. set.Insert(idle)
  3198. set.AggregateBy([]string{AllocationServiceProp}, &AllocationAggregationOptions{
  3199. Filter: ops.Contains(allocation.FieldServices, "nginx-plus-nginx-ingress"),
  3200. })
  3201. for _, alloc := range set.Allocations {
  3202. if !strings.Contains(UnmountedSuffix, alloc.Name) {
  3203. props := alloc.Properties
  3204. if props.Cluster == UnmountedSuffix {
  3205. t.Error("cluster unmounted")
  3206. }
  3207. if props.Container == UnmountedSuffix {
  3208. t.Error("container unmounted")
  3209. }
  3210. if props.Namespace == UnmountedSuffix {
  3211. t.Error("namespace unmounted")
  3212. }
  3213. if props.Pod == UnmountedSuffix {
  3214. t.Error("pod unmounted")
  3215. }
  3216. if props.Controller == UnmountedSuffix {
  3217. t.Error("controller unmounted")
  3218. }
  3219. }
  3220. }
  3221. spew.Config.DisableMethods = true
  3222. t.Logf("%s", spew.Sdump(set.Allocations))
  3223. }
  3224. func Test_DetermineSharingName(t *testing.T) {
  3225. var alloc *Allocation
  3226. var name string
  3227. var err error
  3228. // test nil allocation with nil options
  3229. name, err = alloc.determineSharingName(nil)
  3230. if err == nil {
  3231. t.Fatalf("determineSharingName: expected error; actual nil")
  3232. }
  3233. // test nil with non-nil options
  3234. name, err = alloc.determineSharingName(&AllocationAggregationOptions{})
  3235. if err == nil {
  3236. t.Fatalf("determineSharingName: expected error; actual nil")
  3237. }
  3238. alloc = &Allocation{}
  3239. alloc.Properties = &AllocationProperties{
  3240. Cluster: "cluster1",
  3241. Labels: map[string]string{
  3242. "app": "app1",
  3243. "env": "env1",
  3244. },
  3245. Namespace: "namespace1",
  3246. }
  3247. // test non-nil allocation with nil options
  3248. name, err = alloc.determineSharingName(nil)
  3249. if err != nil {
  3250. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3251. } else if name != "unknown" {
  3252. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3253. }
  3254. // test non-nil allocation with empty options
  3255. options := &AllocationAggregationOptions{}
  3256. name, err = alloc.determineSharingName(options)
  3257. if err != nil {
  3258. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3259. } else if name != "unknown" {
  3260. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3261. }
  3262. // test non-nil allocation with matching namespace options
  3263. options.SharedNamespaces = []string{"namespace1"}
  3264. name, err = alloc.determineSharingName(options)
  3265. if err != nil {
  3266. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3267. } else if name != "namespace1" {
  3268. t.Fatalf("determineSharingName: expected \"namespace1\"; actual \"%s\"", name)
  3269. }
  3270. // test non-nil allocation with non-matching namespace options
  3271. options.SharedNamespaces = []string{"namespace2"}
  3272. name, err = alloc.determineSharingName(options)
  3273. if err != nil {
  3274. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3275. } else if name != "unknown" {
  3276. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3277. }
  3278. // test non-nil allocation with matching label options
  3279. options.SharedNamespaces = nil
  3280. options.SharedLabels = map[string][]string{
  3281. "app": {"app1"},
  3282. }
  3283. name, err = alloc.determineSharingName(options)
  3284. if err != nil {
  3285. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3286. } else if name != "app1" {
  3287. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3288. }
  3289. // test non-nil allocation with partial-matching label options
  3290. options.SharedLabels = map[string][]string{
  3291. "app": {"app1", "app2"},
  3292. }
  3293. name, err = alloc.determineSharingName(options)
  3294. if err != nil {
  3295. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3296. } else if name != "app1" {
  3297. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3298. }
  3299. // test non-nil allocation with non-matching label options
  3300. options.SharedLabels = map[string][]string{
  3301. "app": {"app2"},
  3302. }
  3303. name, err = alloc.determineSharingName(options)
  3304. if err != nil {
  3305. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3306. } else if name != "unknown" {
  3307. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3308. }
  3309. // test non-nil allocation with matching namespace and label options
  3310. options.SharedNamespaces = []string{"namespace1"}
  3311. options.SharedLabels = map[string][]string{
  3312. "app": {"app1"},
  3313. }
  3314. name, err = alloc.determineSharingName(options)
  3315. if err != nil {
  3316. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3317. } else if name != "app1" {
  3318. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3319. }
  3320. // test non-nil allocation with non-matching namespace and matching label options
  3321. options.SharedNamespaces = []string{"namespace2"}
  3322. options.SharedLabels = map[string][]string{
  3323. "app": {"app1"},
  3324. }
  3325. name, err = alloc.determineSharingName(options)
  3326. if err != nil {
  3327. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3328. } else if name != "app1" {
  3329. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3330. }
  3331. // test non-nil allocation with non-matching namespace and non-matching label options
  3332. options.SharedNamespaces = []string{"namespace2"}
  3333. options.SharedLabels = map[string][]string{
  3334. "app": {"app2"},
  3335. }
  3336. name, err = alloc.determineSharingName(options)
  3337. if err != nil {
  3338. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3339. } else if name != "unknown" {
  3340. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3341. }
  3342. // test non-nil allocation with multiple matching label options
  3343. alloc.Properties.Labels = map[string]string{
  3344. "app": "app1",
  3345. "env": "env1",
  3346. }
  3347. options.SharedNamespaces = nil
  3348. options.SharedLabels = map[string][]string{
  3349. "app": {"app1"},
  3350. "env": {"env1"},
  3351. }
  3352. name, err = alloc.determineSharingName(options)
  3353. if err != nil {
  3354. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3355. } else if name != "app1" {
  3356. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3357. }
  3358. // test non-nil allocation with one matching label option
  3359. alloc.Properties.Labels = map[string]string{
  3360. "app": "app2",
  3361. "env": "env1",
  3362. }
  3363. options.SharedNamespaces = nil
  3364. options.SharedLabels = map[string][]string{
  3365. "app": {"app1"},
  3366. "env": {"env1"},
  3367. }
  3368. name, err = alloc.determineSharingName(options)
  3369. if err != nil {
  3370. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3371. } else if name != "env1" {
  3372. t.Fatalf("determineSharingName: expected \"env1\"; actual \"%s\"", name)
  3373. }
  3374. // test non-nil allocation with one matching namespace option
  3375. alloc.Properties.Namespace = "namespace1"
  3376. options.SharedNamespaces = []string{"namespace1", "namespace2"}
  3377. options.SharedLabels = nil
  3378. name, err = alloc.determineSharingName(options)
  3379. if err != nil {
  3380. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3381. } else if name != "namespace1" {
  3382. t.Fatalf("determineSharingName: expected \"namespace1\"; actual \"%s\"", name)
  3383. }
  3384. // test non-nil allocation with another one matching namespace option
  3385. alloc.Properties.Namespace = "namespace2"
  3386. options.SharedNamespaces = []string{"namespace1", "namespace2"}
  3387. options.SharedLabels = nil
  3388. name, err = alloc.determineSharingName(options)
  3389. if err != nil {
  3390. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3391. } else if name != "namespace2" {
  3392. t.Fatalf("determineSharingName: expected \"namespace2\"; actual \"%s\"", name)
  3393. }
  3394. // test non-nil allocation with non-matching namespace options
  3395. alloc.Properties.Namespace = "namespace3"
  3396. options.SharedNamespaces = []string{"namespace1", "namespace2"}
  3397. name, err = alloc.determineSharingName(options)
  3398. if err != nil {
  3399. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3400. } else if name != "unknown" {
  3401. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3402. }
  3403. }
  3404. func TestIsFilterEmptyTrue(t *testing.T) {
  3405. compiler := NewAllocationMatchCompiler(nil)
  3406. matcher, err := compiler.Compile(nil)
  3407. if err != nil {
  3408. t.Fatalf("compiling nil filter: %s", err)
  3409. }
  3410. result := isFilterEmpty(matcher)
  3411. if !result {
  3412. t.Errorf("matcher '%+v' should be reported empty but wasn't", matcher)
  3413. }
  3414. }
  3415. func TestIsFilterEmptyFalse(t *testing.T) {
  3416. compiler := NewAllocationMatchCompiler(nil)
  3417. matcher, err := compiler.Compile(ops.Eq(allocation.FieldClusterID, "test"))
  3418. if err != nil {
  3419. t.Fatalf("compiling nil filter: %s", err)
  3420. }
  3421. result := isFilterEmpty(matcher)
  3422. if result {
  3423. t.Errorf("matcher '%+v' should be not be reported empty but was", matcher)
  3424. }
  3425. }
  3426. func TestAllocation_SanitizeNaN(t *testing.T) {
  3427. tcName := "TestAllocation_SanitizeNaN"
  3428. alloc := getMockAllocation(math.NaN())
  3429. alloc.SanitizeNaN()
  3430. checkAllocation(t, tcName, alloc)
  3431. }
  3432. func checkAllocation(t *testing.T, tcName string, alloc Allocation) {
  3433. v := reflect.ValueOf(alloc)
  3434. checkAllFloat64sForNaN(t, v, tcName)
  3435. vRaw := reflect.ValueOf(*alloc.RawAllocationOnly)
  3436. checkAllFloat64sForNaN(t, vRaw, tcName)
  3437. for _, pv := range alloc.PVs {
  3438. vPV := reflect.ValueOf(*pv)
  3439. checkAllFloat64sForNaN(t, vPV, tcName)
  3440. }
  3441. for _, parc := range alloc.ProportionalAssetResourceCosts {
  3442. vParc := reflect.ValueOf(parc)
  3443. checkAllFloat64sForNaN(t, vParc, tcName)
  3444. }
  3445. for _, scb := range alloc.SharedCostBreakdown {
  3446. vScb := reflect.ValueOf(scb)
  3447. checkAllFloat64sForNaN(t, vScb, tcName)
  3448. }
  3449. for _, lb := range alloc.LoadBalancers {
  3450. vLb := reflect.ValueOf(*lb)
  3451. checkAllFloat64sForNaN(t, vLb, tcName)
  3452. }
  3453. }
  3454. func TestAllocationSet_SanitizeNaN(t *testing.T) {
  3455. allocNaN := getMockAllocation(math.NaN())
  3456. allocNotNaN := getMockAllocation(1.2)
  3457. allocSet := AllocationSet{
  3458. Allocations: map[string]*Allocation{"NaN": &allocNaN, "notNaN": &allocNotNaN},
  3459. }
  3460. allocSet.SanitizeNaN()
  3461. for _, a := range allocSet.Allocations {
  3462. checkAllocation(t, "TestAllocationSet_SanitizeNaN", *a)
  3463. }
  3464. }
  3465. func getMockAllocation(f float64) Allocation {
  3466. alloc := Allocation{
  3467. Name: "mockAllocation",
  3468. Properties: nil,
  3469. Window: Window{},
  3470. Start: time.Time{},
  3471. End: time.Time{},
  3472. CPUCoreHours: f,
  3473. CPUCoreRequestAverage: f,
  3474. CPUCoreUsageAverage: f,
  3475. CPUCost: f,
  3476. CPUCostAdjustment: f,
  3477. GPUHours: f,
  3478. GPUCost: f,
  3479. GPUCostAdjustment: f,
  3480. NetworkTransferBytes: f,
  3481. NetworkReceiveBytes: f,
  3482. NetworkCost: f,
  3483. NetworkCrossZoneCost: f,
  3484. NetworkCrossRegionCost: f,
  3485. NetworkInternetCost: f,
  3486. NetworkCostAdjustment: f,
  3487. NetworkNatGatewayEgressCost: f,
  3488. NetworkNatGatewayIngressCost: f,
  3489. LoadBalancerCost: f,
  3490. LoadBalancerCostAdjustment: f,
  3491. PVs: PVAllocations{{Cluster: "testPV", Name: "PVName"}: getMockPVAllocation(math.NaN())},
  3492. PVCostAdjustment: f,
  3493. RAMByteHours: f,
  3494. RAMBytesRequestAverage: f,
  3495. RAMBytesUsageAverage: f,
  3496. RAMCost: f,
  3497. RAMCostAdjustment: f,
  3498. SharedCost: f,
  3499. ExternalCost: f,
  3500. RawAllocationOnly: getMockRawAllocationOnlyData(f),
  3501. ProportionalAssetResourceCosts: ProportionalAssetResourceCosts{"NaN": *getMockPARC(f)},
  3502. SharedCostBreakdown: SharedCostBreakdowns{"NaN": *getMockSharedCostBreakdown(f)},
  3503. LoadBalancers: LbAllocations{"NaN": getMockLbAllocation(f)},
  3504. }
  3505. return alloc
  3506. }
  3507. func TestPVAllocation_SanitizeNaN(t *testing.T) {
  3508. pva := getMockPVAllocation(math.NaN())
  3509. pva.SanitizeNaN()
  3510. v := reflect.ValueOf(*pva)
  3511. checkAllFloat64sForNaN(t, v, "TestPVAllocation_SanitizeNaN")
  3512. }
  3513. func TestPVAllocations_SanitizeNaN(t *testing.T) {
  3514. pvaNaN := getMockPVAllocation(math.NaN())
  3515. pvaNotNaN := getMockPVAllocation(1.2)
  3516. pvs := PVAllocations{{Cluster: "testPV", Name: "PVName1"}: pvaNaN, {Cluster: "testPV", Name: "PVName2"}: pvaNotNaN}
  3517. pvs.SanitizeNaN()
  3518. for _, pv := range pvs {
  3519. v := reflect.ValueOf(*pv)
  3520. checkAllFloat64sForNaN(t, v, "TestPVAllocations_SanitizeNaN")
  3521. }
  3522. }
  3523. func getMockPVAllocation(f float64) *PVAllocation {
  3524. return &PVAllocation{
  3525. ByteHours: f,
  3526. Cost: f,
  3527. }
  3528. }
  3529. func TestRawAllocationOnlyData_SanitizeNaN(t *testing.T) {
  3530. raw := getMockRawAllocationOnlyData(math.NaN())
  3531. raw.SanitizeNaN()
  3532. v := reflect.ValueOf(*raw)
  3533. checkAllFloat64sForNaN(t, v, "TestRawAllocationOnlyData_SanitizeNaN")
  3534. nan := math.NaN()
  3535. nilRawAllocation := &RawAllocationOnlyData{
  3536. CPUCoreUsageMax: nan,
  3537. RAMBytesUsageMax: nan,
  3538. GPUUsageMax: &nan,
  3539. }
  3540. nilRawAllocation.SanitizeNaN()
  3541. // SanitizeNaN allocates nil if NaN is passed
  3542. if nilRawAllocation.GPUUsageMax != nil {
  3543. t.Fatalf("want: nil, got: %v", nilRawAllocation.GPUUsageMax)
  3544. }
  3545. // SanitizeNaN allocates 0.0 if NaN is passed
  3546. if nilRawAllocation.CPUCoreUsageMax != 0.0 {
  3547. t.Fatalf("want: 0.0, got: %v", nilRawAllocation.CPUCoreUsageMax)
  3548. }
  3549. // SanitizeNaN allocates 0.0 if NaN is passed
  3550. if nilRawAllocation.RAMBytesUsageMax != 0.0 {
  3551. t.Fatalf("want: 0.0, got: %v", nilRawAllocation.RAMBytesUsageMax)
  3552. }
  3553. }
  3554. func getMockRawAllocationOnlyData(f float64) *RawAllocationOnlyData {
  3555. return &RawAllocationOnlyData{
  3556. CPUCoreUsageMax: f,
  3557. RAMBytesUsageMax: f,
  3558. GPUUsageMax: &f,
  3559. }
  3560. }
  3561. func TestLbAllocation_SanitizeNaN(t *testing.T) {
  3562. lbaNaN := getMockLbAllocation(math.NaN())
  3563. lbaNaN.SanitizeNaN()
  3564. v := reflect.ValueOf(*lbaNaN)
  3565. checkAllFloat64sForNaN(t, v, "TestLbAllocation_SanitizeNaN")
  3566. }
  3567. func TestLbAllocations_SanitizeNaN(t *testing.T) {
  3568. lbaNaN := getMockLbAllocation(math.NaN())
  3569. lbaValid := getMockLbAllocation(1.2)
  3570. lbas := LbAllocations{"NaN": lbaNaN, "notNaN": lbaValid}
  3571. lbas.SanitizeNaN()
  3572. for _, lba := range lbas {
  3573. v := reflect.ValueOf(*lba)
  3574. checkAllFloat64sForNaN(t, v, "TestLbAllocations_SanitizeNaN")
  3575. }
  3576. }
  3577. func getMockLbAllocation(f float64) *LbAllocation {
  3578. return &LbAllocation{
  3579. Service: "testLoadBalancer",
  3580. Cost: f,
  3581. Private: false,
  3582. }
  3583. }
  3584. func TestProportionalAssetResourceCosts_SanitizeNaN(t *testing.T) {
  3585. parcAllNaN := getMockPARC(math.NaN())
  3586. parcNotNaN := getMockPARC(1.2)
  3587. parcs := ProportionalAssetResourceCosts{"NaN": *parcAllNaN, "notNaN": *parcNotNaN}
  3588. parcs.SanitizeNaN()
  3589. for _, parc := range parcs {
  3590. v := reflect.ValueOf(parc)
  3591. checkAllFloat64sForNaN(t, v, "TestProportionalAssetResourceCosts_SanitizeNaN")
  3592. }
  3593. }
  3594. func getMockPARC(f float64) *ProportionalAssetResourceCost {
  3595. return &ProportionalAssetResourceCost{
  3596. Cluster: "testCluster",
  3597. Name: "testName",
  3598. Type: "testType",
  3599. ProviderID: "testProvider",
  3600. CPUPercentage: f,
  3601. GPUPercentage: f,
  3602. RAMPercentage: f,
  3603. LoadBalancerPercentage: f,
  3604. PVPercentage: f,
  3605. NodeResourceCostPercentage: f,
  3606. GPUTotalCost: f,
  3607. GPUProportionalCost: f,
  3608. CPUTotalCost: f,
  3609. CPUProportionalCost: f,
  3610. RAMTotalCost: f,
  3611. RAMProportionalCost: f,
  3612. LoadBalancerProportionalCost: f,
  3613. LoadBalancerTotalCost: f,
  3614. PVProportionalCost: f,
  3615. PVTotalCost: f,
  3616. }
  3617. }
  3618. func TestSharedCostBreakdowns_SanitizeNaN(t *testing.T) {
  3619. scbNaN := getMockSharedCostBreakdown(math.NaN())
  3620. scbNotNaN := getMockSharedCostBreakdown(1.2)
  3621. scbs := SharedCostBreakdowns{"NaN": *scbNaN, "notNaN": *scbNotNaN}
  3622. scbs.SanitizeNaN()
  3623. for _, scb := range scbs {
  3624. v := reflect.ValueOf(scb)
  3625. checkAllFloat64sForNaN(t, v, "TestSharedCostBreakdowns_SanitizeNaN")
  3626. }
  3627. }
  3628. func getMockSharedCostBreakdown(f float64) *SharedCostBreakdown {
  3629. return &SharedCostBreakdown{
  3630. Name: "testBreakdown",
  3631. TotalCost: f,
  3632. CPUCost: f,
  3633. GPUCost: f,
  3634. RAMCost: f,
  3635. PVCost: f,
  3636. NetworkCost: f,
  3637. LBCost: f,
  3638. ExternalCost: f,
  3639. }
  3640. }
  3641. func checkAllFloat64sForNaN(t *testing.T, v reflect.Value, testCaseName string) {
  3642. vType := v.Type()
  3643. // go through each field on the struct
  3644. for i := 0; i < v.NumField(); i++ {
  3645. // Check if field is public and can be converted to a float
  3646. if v.Field(i).CanInterface() && v.Field(i).CanFloat() {
  3647. f := v.Field(i).Float()
  3648. if math.IsNaN(f) {
  3649. t.Fatalf("%s: expected not NaN for field: %s, got:NaN", testCaseName, vType.Field(i).Name)
  3650. }
  3651. }
  3652. }
  3653. }
  3654. // TestGPUAllocation_Equal verifies value semantics for the pointer fields:
  3655. // two independently constructed GPUAllocations with equal contents must be
  3656. // equal, regardless of pointer identity. Regression test for #3846.
  3657. func TestGPUAllocation_Equal(t *testing.T) {
  3658. makeGPUAllocation := func() *GPUAllocation {
  3659. shared := true
  3660. usage := 0.5
  3661. request := 1.0
  3662. return &GPUAllocation{
  3663. GPUDevice: "nvidia0",
  3664. GPUModel: "Tesla T4",
  3665. GPUUUID: "GPU-1",
  3666. IsGPUShared: &shared,
  3667. GPUUsageAverage: &usage,
  3668. GPURequestAverage: &request,
  3669. }
  3670. }
  3671. cases := map[string]struct {
  3672. a, b *GPUAllocation
  3673. want bool
  3674. }{
  3675. "both nil": {nil, nil, true},
  3676. "one nil": {makeGPUAllocation(), nil, false},
  3677. "identical values, distinct pointers": {
  3678. makeGPUAllocation(), makeGPUAllocation(), true,
  3679. },
  3680. "different usage value": {
  3681. makeGPUAllocation(),
  3682. func() *GPUAllocation { g := makeGPUAllocation(); v := 0.9; g.GPUUsageAverage = &v; return g }(),
  3683. false,
  3684. },
  3685. "different shared value": {
  3686. makeGPUAllocation(),
  3687. func() *GPUAllocation { g := makeGPUAllocation(); v := false; g.IsGPUShared = &v; return g }(),
  3688. false,
  3689. },
  3690. "nil vs set pointer field": {
  3691. makeGPUAllocation(),
  3692. func() *GPUAllocation { g := makeGPUAllocation(); g.GPURequestAverage = nil; return g }(),
  3693. false,
  3694. },
  3695. "different device identity": {
  3696. makeGPUAllocation(),
  3697. func() *GPUAllocation { g := makeGPUAllocation(); g.GPUUUID = "GPU-2"; return g }(),
  3698. false,
  3699. },
  3700. }
  3701. for name, tc := range cases {
  3702. t.Run(name, func(t *testing.T) {
  3703. if got := tc.a.Equal(tc.b); got != tc.want {
  3704. t.Errorf("Equal() = %v, want %v", got, tc.want)
  3705. }
  3706. if got := tc.b.Equal(tc.a); got != tc.want {
  3707. t.Errorf("Equal() reversed = %v, want %v", got, tc.want)
  3708. }
  3709. })
  3710. }
  3711. t.Run("binary roundtrip equals original", func(t *testing.T) {
  3712. orig := makeGPUAllocation()
  3713. bs, err := orig.MarshalBinary()
  3714. if err != nil {
  3715. t.Fatalf("MarshalBinary: %s", err)
  3716. }
  3717. decoded := new(GPUAllocation)
  3718. if err := decoded.UnmarshalBinary(bs); err != nil {
  3719. t.Fatalf("UnmarshalBinary: %s", err)
  3720. }
  3721. if !orig.Equal(decoded) {
  3722. t.Errorf("roundtrip-decoded GPUAllocation not Equal to original: %+v vs %+v", orig, decoded)
  3723. }
  3724. })
  3725. }