allocation_test.go 127 KB

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