allocation_test.go 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438
  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. if !reflect.DeepEqual(expectedParcs[key], actualParc) {
  501. t.Fatalf("actual PARC %v did not match expected PARC %v", actualParc, expectedParcs[key])
  502. }
  503. }
  504. }
  505. }
  506. func roundFloat(val float64) float64 {
  507. ratio := math.Pow(10, float64(5))
  508. return math.Round(val*ratio) / ratio
  509. }
  510. func assertAllocationTotals(t *testing.T, as *AllocationSet, msg string, exps map[string]float64) {
  511. for _, a := range as.Allocations {
  512. if exp, ok := exps[a.Name]; ok {
  513. if math.Round(a.TotalCost()*100) != math.Round(exp*100) {
  514. t.Fatalf("AllocationSet.AggregateBy[%s]: expected total cost %f, actual %f", msg, exp, a.TotalCost())
  515. }
  516. } else {
  517. t.Fatalf("AllocationSet.AggregateBy[%s]: unexpected allocation: %s", msg, a.Name)
  518. }
  519. }
  520. }
  521. func assertAllocationWindow(t *testing.T, as *AllocationSet, msg string, expStart, expEnd time.Time, expMinutes float64) {
  522. for _, a := range as.Allocations {
  523. if !a.Start.Equal(expStart) {
  524. t.Fatalf("AllocationSet.AggregateBy[%s]: expected start %s, actual %s", msg, expStart, a.Start)
  525. }
  526. if !a.End.Equal(expEnd) {
  527. t.Fatalf("AllocationSet.AggregateBy[%s]: expected end %s, actual %s", msg, expEnd, a.End)
  528. }
  529. if a.Minutes() != expMinutes {
  530. t.Fatalf("AllocationSet.AggregateBy[%s]: expected minutes %f, actual %f", msg, expMinutes, a.Minutes())
  531. }
  532. }
  533. }
  534. func printAllocationSet(msg string, as *AllocationSet) {
  535. fmt.Printf("--- %s ---\n", msg)
  536. for _, a := range as.Allocations {
  537. fmt.Printf(" > %s\n", a)
  538. }
  539. }
  540. func TestAllocationSet_AggregateBy(t *testing.T) {
  541. // Test AggregateBy against the following workload topology, which is
  542. // generated by GenerateMockAllocationSet:
  543. // | Hierarchy | Cost | CPU | RAM | GPU | PV | Net | LB |
  544. // +----------------------------------------+------+------+------+------+------+------+------+
  545. // cluster1:
  546. // idle: 20.00 5.00 15.00 0.00 0.00 0.00 0.00
  547. // namespace1:
  548. // pod1:
  549. // container1: [app1, env1] 16.00 1.00 11.00 1.00 1.00 1.00 1.00
  550. // pod-abc: (deployment1)
  551. // container2: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  552. // pod-def: (deployment1)
  553. // container3: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  554. // namespace2:
  555. // pod-ghi: (deployment2)
  556. // container4: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  557. // container5: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  558. // pod-jkl: (daemonset1)
  559. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  560. // +-----------------------------------------+------+------+------+------+------+------+------+
  561. // cluster1 subtotal 66.00 11.00 31.00 6.00 6.00 6.00 6.00
  562. // +-----------------------------------------+------+------+------+------+------+------+------+
  563. // cluster2:
  564. // idle: 10.00 5.00 5.00 0.00 0.00 0.00 0.00
  565. // namespace2:
  566. // pod-mno: (deployment2)
  567. // container4: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  568. // container5: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  569. // pod-pqr: (daemonset1)
  570. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  571. // namespace3:
  572. // pod-stu: (deployment3)
  573. // container7: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  574. // pod-vwx: (statefulset1)
  575. // container8: an[team2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  576. // container9: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  577. // +----------------------------------------+------+------+------+------+------+------+------+
  578. // cluster2 subtotal 46.00 11.00 11.00 6.00 6.00 6.00 6.00
  579. // +----------------------------------------+------+------+------+------+------+------+------+
  580. // total 112.00 22.00 42.00 12.00 12.00 12.00 12.00
  581. // +----------------------------------------+------+------+------+------+------+------+------+
  582. // Scenarios to test:
  583. // 1 Single-aggregation
  584. // 1a AggregationProperties=(Cluster)
  585. // 1b AggregationProperties=(Namespace)
  586. // 1c AggregationProperties=(Pod)
  587. // 1d AggregationProperties=(Container)
  588. // 1e AggregationProperties=(ControllerKind)
  589. // 1f AggregationProperties=(Controller)
  590. // 1g AggregationProperties=(Service)
  591. // 1h AggregationProperties=(Label:app)
  592. // 2 Multi-aggregation
  593. // 2a AggregationProperties=(Cluster, Namespace)
  594. // 2b AggregationProperties=(Namespace, Label:app)
  595. // 2c AggregationProperties=(Cluster, Namespace, Pod, Container)
  596. // 2d AggregationProperties=(Label:app, Label:environment)
  597. // 3 Share idle
  598. // 3a AggregationProperties=(Namespace) ShareIdle=ShareWeighted
  599. // 3b AggregationProperties=(Namespace) ShareIdle=ShareEven (TODO niko/etl)
  600. // 4 Share resources
  601. // 4a Share namespace ShareEven
  602. // 4b Share cluster ShareWeighted
  603. // 4c Share label ShareEven
  604. // 4d Share overhead ShareWeighted
  605. // 5 Filters
  606. // 5a Filter by cluster with separate idle
  607. // 5b Filter by cluster with shared idle
  608. // TODO niko/idle more filter tests
  609. // 6 Combinations and options
  610. // 6a SplitIdle
  611. // 6b Share idle with filters
  612. // 6c Share resources with filters
  613. // 6d Share idle and share resources
  614. // 6e IdleByNode
  615. // 7 Edge cases and errors
  616. // 7a Empty AggregationProperties
  617. // 7b Filter all
  618. // 7c Share all
  619. // 7d Share and filter the same allocations
  620. // Definitions and set-up:
  621. var as *AllocationSet
  622. var err error
  623. endYesterday := time.Now().UTC().Truncate(day)
  624. startYesterday := endYesterday.Add(-day)
  625. numClusters := 2
  626. numNamespaces := 3
  627. numPods := 9
  628. numContainers := 9
  629. numControllerKinds := 3
  630. numControllers := 5
  631. numServices := 1
  632. numLabelApps := 2
  633. // By default, idle is reported as a single, merged allocation
  634. numIdle := 1
  635. // There will only ever be one __unallocated__
  636. numUnallocated := 1
  637. // There are two clusters, so each gets an idle entry when they are split
  638. numSplitIdleCluster := 2
  639. // There are two clusters, so each gets an idle entry when they are split
  640. numSplitIdleNode := 4
  641. activeTotalCost := 82.0
  642. idleTotalCost := 30.0
  643. sharedOverheadHourlyCost := 7.0
  644. // Match Functions
  645. isNamespace3 := func(a *Allocation) bool {
  646. ns := a.Properties.Namespace
  647. return ns == "namespace3"
  648. }
  649. isApp1 := func(a *Allocation) bool {
  650. ls := a.Properties.Labels
  651. if app, ok := ls["app"]; ok && app == "app1" {
  652. return true
  653. }
  654. return false
  655. }
  656. // Filters
  657. isNamespace := func(matchNamespace string) func(*Allocation) bool {
  658. return func(a *Allocation) bool {
  659. namespace := a.Properties.Namespace
  660. return namespace == matchNamespace
  661. }
  662. }
  663. end := time.Now().UTC().Truncate(day)
  664. start := end.Add(-day)
  665. // Tests:
  666. cases := map[string]struct {
  667. start time.Time
  668. aggBy []string
  669. aggOpts *AllocationAggregationOptions
  670. numResults int
  671. totalCost float64
  672. results map[string]float64
  673. windowStart time.Time
  674. windowEnd time.Time
  675. expMinutes float64
  676. expectedParcResults map[string]ProportionalAssetResourceCosts
  677. }{
  678. // 1 Single-aggregation
  679. // 1a AggregationProperties=(Cluster)
  680. "1a": {
  681. start: start,
  682. aggBy: []string{AllocationClusterProp},
  683. aggOpts: nil,
  684. numResults: numClusters + numIdle,
  685. totalCost: activeTotalCost + idleTotalCost,
  686. results: map[string]float64{
  687. "cluster1": 46.00,
  688. "cluster2": 36.00,
  689. IdleSuffix: 30.00,
  690. },
  691. windowStart: startYesterday,
  692. windowEnd: endYesterday,
  693. expMinutes: 1440.0,
  694. },
  695. // 1b AggregationProperties=(Namespace)
  696. "1b": {
  697. start: start,
  698. aggBy: []string{AllocationNamespaceProp},
  699. aggOpts: nil,
  700. numResults: numNamespaces + numIdle,
  701. totalCost: activeTotalCost + idleTotalCost,
  702. results: map[string]float64{
  703. "namespace1": 28.00,
  704. "namespace2": 36.00,
  705. "namespace3": 18.00,
  706. IdleSuffix: 30.00,
  707. },
  708. windowStart: startYesterday,
  709. windowEnd: endYesterday,
  710. expMinutes: 1440.0,
  711. },
  712. // 1c AggregationProperties=(Pod)
  713. "1c": {
  714. start: start,
  715. aggBy: []string{AllocationPodProp},
  716. aggOpts: nil,
  717. numResults: numPods + numIdle,
  718. totalCost: activeTotalCost + idleTotalCost,
  719. results: map[string]float64{
  720. "pod-jkl": 6.00,
  721. "pod-stu": 6.00,
  722. "pod-abc": 6.00,
  723. "pod-pqr": 6.00,
  724. "pod-def": 6.00,
  725. "pod-vwx": 12.00,
  726. "pod1": 16.00,
  727. "pod-mno": 12.00,
  728. "pod-ghi": 12.00,
  729. IdleSuffix: 30.00,
  730. },
  731. windowStart: startYesterday,
  732. windowEnd: endYesterday,
  733. expMinutes: 1440.0,
  734. },
  735. // 1d AggregationProperties=(Container)
  736. "1d": {
  737. start: start,
  738. aggBy: []string{AllocationContainerProp},
  739. aggOpts: nil,
  740. numResults: numContainers + numIdle,
  741. totalCost: activeTotalCost + idleTotalCost,
  742. results: map[string]float64{
  743. "container2": 6.00,
  744. "container9": 6.00,
  745. "container6": 12.00,
  746. "container3": 6.00,
  747. "container4": 12.00,
  748. "container7": 6.00,
  749. "container8": 6.00,
  750. "container5": 12.00,
  751. "container1": 16.00,
  752. IdleSuffix: 30.00,
  753. },
  754. windowStart: startYesterday,
  755. windowEnd: endYesterday,
  756. expMinutes: 1440.0,
  757. },
  758. // 1e AggregationProperties=(ControllerKind)
  759. "1e": {
  760. start: start,
  761. aggBy: []string{AllocationControllerKindProp},
  762. aggOpts: nil,
  763. numResults: numControllerKinds + numIdle + numUnallocated,
  764. totalCost: activeTotalCost + idleTotalCost,
  765. results: map[string]float64{
  766. "daemonset": 12.00,
  767. "deployment": 42.00,
  768. "statefulset": 12.00,
  769. IdleSuffix: 30.00,
  770. UnallocatedSuffix: 16.00,
  771. },
  772. windowStart: startYesterday,
  773. windowEnd: endYesterday,
  774. expMinutes: 1440.0,
  775. },
  776. // 1f AggregationProperties=(Controller)
  777. "1f": {
  778. start: start,
  779. aggBy: []string{AllocationControllerProp},
  780. aggOpts: nil,
  781. numResults: numControllers + numIdle + numUnallocated,
  782. totalCost: activeTotalCost + idleTotalCost,
  783. results: map[string]float64{
  784. "deployment:deployment2": 24.00,
  785. "daemonset:daemonset1": 12.00,
  786. "deployment:deployment3": 6.00,
  787. "statefulset:statefulset1": 12.00,
  788. "deployment:deployment1": 12.00,
  789. IdleSuffix: 30.00,
  790. UnallocatedSuffix: 16.00,
  791. },
  792. windowStart: startYesterday,
  793. windowEnd: endYesterday,
  794. expMinutes: 1440.0,
  795. },
  796. // 1g AggregationProperties=(Service)
  797. "1g": {
  798. start: start,
  799. aggBy: []string{AllocationServiceProp},
  800. aggOpts: nil,
  801. numResults: numServices + numIdle + numUnallocated,
  802. totalCost: activeTotalCost + idleTotalCost,
  803. results: map[string]float64{
  804. "service1": 12.00,
  805. IdleSuffix: 30.00,
  806. UnallocatedSuffix: 70.00,
  807. },
  808. windowStart: startYesterday,
  809. windowEnd: endYesterday,
  810. expMinutes: 1440.0,
  811. },
  812. // 1h AggregationProperties=(Label:app)
  813. "1h": {
  814. start: start,
  815. aggBy: []string{"label:app"},
  816. aggOpts: nil,
  817. numResults: numLabelApps + numIdle + numUnallocated,
  818. totalCost: activeTotalCost + idleTotalCost,
  819. results: map[string]float64{
  820. "app1": 16.00,
  821. "app2": 24.00,
  822. IdleSuffix: 30.00,
  823. UnallocatedSuffix: 42.00,
  824. },
  825. windowStart: startYesterday,
  826. windowEnd: endYesterday,
  827. expMinutes: 1440.0,
  828. },
  829. // 1i AggregationProperties=(deployment)
  830. "1i": {
  831. start: start,
  832. aggBy: []string{AllocationDeploymentProp},
  833. aggOpts: nil,
  834. numResults: 3 + numIdle + numUnallocated,
  835. totalCost: activeTotalCost + idleTotalCost,
  836. results: map[string]float64{
  837. "deployment1": 12.00,
  838. "deployment2": 24.00,
  839. "deployment3": 6.00,
  840. IdleSuffix: 30.00,
  841. UnallocatedSuffix: 40.00,
  842. },
  843. windowStart: startYesterday,
  844. windowEnd: endYesterday,
  845. expMinutes: 1440.0,
  846. },
  847. // 1j AggregationProperties=(Annotation:team)
  848. "1j": {
  849. start: start,
  850. aggBy: []string{"annotation:team"},
  851. aggOpts: nil,
  852. numResults: 2 + numIdle + numUnallocated,
  853. totalCost: activeTotalCost + idleTotalCost,
  854. results: map[string]float64{
  855. "team1": 12.00,
  856. "team2": 6.00,
  857. IdleSuffix: 30.00,
  858. UnallocatedSuffix: 64.00,
  859. },
  860. windowStart: startYesterday,
  861. windowEnd: endYesterday,
  862. expMinutes: 1440.0,
  863. },
  864. // 1k AggregationProperties=(daemonSet)
  865. "1k": {
  866. start: start,
  867. aggBy: []string{AllocationDaemonSetProp},
  868. aggOpts: nil,
  869. numResults: 1 + numIdle + numUnallocated,
  870. totalCost: activeTotalCost + idleTotalCost,
  871. results: map[string]float64{
  872. "daemonset1": 12.00,
  873. IdleSuffix: 30.00,
  874. UnallocatedSuffix: 70.00,
  875. },
  876. windowStart: startYesterday,
  877. windowEnd: endYesterday,
  878. expMinutes: 1440.0,
  879. },
  880. // 1l AggregationProperties=(statefulSet)
  881. "1l": {
  882. start: start,
  883. aggBy: []string{AllocationStatefulSetProp},
  884. aggOpts: nil,
  885. numResults: 1 + numIdle + numUnallocated,
  886. totalCost: activeTotalCost + idleTotalCost,
  887. results: map[string]float64{
  888. "statefulset1": 12.00,
  889. IdleSuffix: 30.00,
  890. UnallocatedSuffix: 70.00,
  891. },
  892. windowStart: startYesterday,
  893. windowEnd: endYesterday,
  894. expMinutes: 1440.0,
  895. },
  896. // 2 Multi-aggregation
  897. // 2a AggregationProperties=(Cluster, Namespace)
  898. // 2b AggregationProperties=(Namespace, Label:app)
  899. // 2c AggregationProperties=(Cluster, Namespace, Pod, Container)
  900. // 2d AggregationProperties=(Label:app, Label:environment)
  901. "2d": {
  902. start: start,
  903. aggBy: []string{"label:app", "label:env"},
  904. aggOpts: nil,
  905. numResults: 3 + numIdle + numUnallocated,
  906. totalCost: activeTotalCost + idleTotalCost,
  907. // sets should be {idle, unallocated, app1/env1, app2/env2, app2/unallocated}
  908. results: map[string]float64{
  909. "app1/env1": 16.00,
  910. "app2/env2": 12.00,
  911. "app2/" + UnallocatedSuffix: 12.00,
  912. IdleSuffix: 30.00,
  913. UnallocatedSuffix + "/" + UnallocatedSuffix: 42.00,
  914. },
  915. windowStart: startYesterday,
  916. windowEnd: endYesterday,
  917. expMinutes: 1440.0,
  918. },
  919. // 2e AggregationProperties=(Cluster, Label:app, Label:environment)
  920. "2e": {
  921. start: start,
  922. aggBy: []string{AllocationClusterProp, "label:app", "label:env"},
  923. aggOpts: nil,
  924. numResults: 6,
  925. totalCost: activeTotalCost + idleTotalCost,
  926. results: map[string]float64{
  927. "cluster1/app2/env2": 12.00,
  928. "__idle__": 30.00,
  929. "cluster1/app1/env1": 16.00,
  930. "cluster1/" + UnallocatedSuffix + "/" + UnallocatedSuffix: 18.00,
  931. "cluster2/app2/" + UnallocatedSuffix: 12.00,
  932. "cluster2/" + UnallocatedSuffix + "/" + UnallocatedSuffix: 24.00,
  933. },
  934. windowStart: startYesterday,
  935. windowEnd: endYesterday,
  936. expMinutes: 1440.0,
  937. },
  938. // 2f AggregationProperties=(annotation:team, pod)
  939. "2f": {
  940. start: start,
  941. aggBy: []string{AllocationPodProp, "annotation:team"},
  942. aggOpts: nil,
  943. numResults: 11,
  944. totalCost: activeTotalCost + idleTotalCost,
  945. results: map[string]float64{
  946. "pod-jkl/" + UnallocatedSuffix: 6.00,
  947. "pod-stu/team1": 6.00,
  948. "pod-abc/" + UnallocatedSuffix: 6.00,
  949. "pod-pqr/" + UnallocatedSuffix: 6.00,
  950. "pod-def/" + UnallocatedSuffix: 6.00,
  951. "pod-vwx/team1": 6.00,
  952. "pod-vwx/team2": 6.00,
  953. "pod1/" + UnallocatedSuffix: 16.00,
  954. "pod-mno/" + UnallocatedSuffix: 12.00,
  955. "pod-ghi/" + UnallocatedSuffix: 12.00,
  956. IdleSuffix: 30.00,
  957. },
  958. windowStart: startYesterday,
  959. windowEnd: endYesterday,
  960. expMinutes: 1440.0,
  961. },
  962. // 3 Share idle
  963. // 3a AggregationProperties=(Namespace) ShareIdle=ShareWeighted
  964. // namespace1: 42.6875 = 28.00 + 5.00*(3.00/6.00) + 15.0*(13.0/16.0)
  965. // 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)
  966. // namespace3: 23.0000 = 18.00 + 5.0*(3.0/6.0) + 5.0*(3.0/6.0)
  967. "3a": {
  968. start: start,
  969. aggBy: []string{AllocationNamespaceProp},
  970. aggOpts: &AllocationAggregationOptions{ShareIdle: ShareWeighted},
  971. numResults: numNamespaces,
  972. totalCost: activeTotalCost + idleTotalCost,
  973. results: map[string]float64{
  974. "namespace1": 42.69,
  975. "namespace2": 46.31,
  976. "namespace3": 23.00,
  977. },
  978. windowStart: startYesterday,
  979. windowEnd: endYesterday,
  980. expMinutes: 1440.0,
  981. },
  982. // 3b: sharing idle evenly is deprecated
  983. // 4 Share resources
  984. // 4a Share namespace ShareEven
  985. // namespace1: 37.5000 = 28.00 + 18.00*(1.0/2.0)
  986. // namespace2: 45.5000 = 36.00 + 18.00*(1.0/2.0)
  987. // idle: 30.0000
  988. "4a": {
  989. start: start,
  990. aggBy: []string{AllocationNamespaceProp},
  991. aggOpts: &AllocationAggregationOptions{
  992. ShareFuncs: []AllocationMatchFunc{isNamespace3},
  993. ShareSplit: ShareEven,
  994. },
  995. numResults: numNamespaces,
  996. totalCost: activeTotalCost + idleTotalCost,
  997. results: map[string]float64{
  998. "namespace1": 37.00,
  999. "namespace2": 45.00,
  1000. IdleSuffix: 30.00,
  1001. },
  1002. windowStart: startYesterday,
  1003. windowEnd: endYesterday,
  1004. expMinutes: 1440.0,
  1005. },
  1006. // 4b Share namespace ShareWeighted
  1007. // namespace1: 32.5000 =
  1008. // namespace2: 37.5000 =
  1009. // idle: 30.0000
  1010. "4b": {
  1011. start: start,
  1012. aggBy: []string{AllocationNamespaceProp},
  1013. aggOpts: &AllocationAggregationOptions{
  1014. ShareFuncs: []AllocationMatchFunc{isNamespace3},
  1015. ShareSplit: ShareWeighted,
  1016. IncludeProportionalAssetResourceCosts: true,
  1017. },
  1018. numResults: numNamespaces,
  1019. totalCost: activeTotalCost + idleTotalCost,
  1020. results: map[string]float64{
  1021. "namespace1": 35.88,
  1022. "namespace2": 46.125,
  1023. IdleSuffix: 30.00,
  1024. },
  1025. windowStart: startYesterday,
  1026. windowEnd: endYesterday,
  1027. expMinutes: 1440.0,
  1028. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  1029. "namespace1": {
  1030. "cluster1": ProportionalAssetResourceCost{
  1031. Cluster: "cluster1",
  1032. Name: "",
  1033. Type: "",
  1034. ProviderID: "",
  1035. GPUProportionalCost: 3,
  1036. CPUProportionalCost: 3,
  1037. RAMProportionalCost: 13,
  1038. },
  1039. },
  1040. "namespace2": {
  1041. "cluster1": ProportionalAssetResourceCost{
  1042. Cluster: "cluster1",
  1043. Name: "",
  1044. Type: "",
  1045. ProviderID: "",
  1046. GPUProportionalCost: 3,
  1047. CPUProportionalCost: 3,
  1048. RAMProportionalCost: 3,
  1049. },
  1050. "cluster2": ProportionalAssetResourceCost{
  1051. Cluster: "cluster2",
  1052. Name: "",
  1053. Type: "",
  1054. ProviderID: "",
  1055. GPUProportionalCost: 3,
  1056. CPUProportionalCost: 3,
  1057. RAMProportionalCost: 3,
  1058. },
  1059. },
  1060. },
  1061. },
  1062. // 4c Share label ShareEven
  1063. // namespace1: 17.3333 = 28.00 - 16.00 + 16.00*(1.0/3.0)
  1064. // namespace2: 41.3333 = 36.00 + 16.00*(1.0/3.0)
  1065. // namespace3: 23.3333 = 18.00 + 16.00*(1.0/3.0)
  1066. // idle: 30.0000
  1067. "4c": {
  1068. start: start,
  1069. aggBy: []string{AllocationNamespaceProp},
  1070. aggOpts: &AllocationAggregationOptions{
  1071. ShareFuncs: []AllocationMatchFunc{isApp1},
  1072. ShareSplit: ShareEven,
  1073. },
  1074. numResults: numNamespaces + numIdle,
  1075. totalCost: activeTotalCost + idleTotalCost,
  1076. results: map[string]float64{
  1077. "namespace1": 17.33,
  1078. "namespace2": 41.33,
  1079. "namespace3": 23.33,
  1080. IdleSuffix: 30.00,
  1081. },
  1082. windowStart: startYesterday,
  1083. windowEnd: endYesterday,
  1084. expMinutes: 1440.0,
  1085. },
  1086. // 4d Share overhead ShareWeighted
  1087. // namespace1: 85.366 = 28.00 + (7.0*24.0)*(28.00/82.00)
  1088. // namespace2: 109.756 = 36.00 + (7.0*24.0)*(36.00/82.00)
  1089. // namespace3: 54.878 = 18.00 + (7.0*24.0)*(18.00/82.00)
  1090. // idle: 30.0000
  1091. "4d": {
  1092. start: start,
  1093. aggBy: []string{AllocationNamespaceProp},
  1094. aggOpts: &AllocationAggregationOptions{
  1095. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1096. ShareSplit: ShareWeighted,
  1097. },
  1098. numResults: numNamespaces + numIdle,
  1099. totalCost: activeTotalCost + idleTotalCost + (sharedOverheadHourlyCost * 24.0),
  1100. results: map[string]float64{
  1101. "namespace1": 85.366,
  1102. "namespace2": 109.756,
  1103. "namespace3": 54.878,
  1104. IdleSuffix: 30.00,
  1105. },
  1106. windowStart: startYesterday,
  1107. windowEnd: endYesterday,
  1108. expMinutes: 1440.0,
  1109. },
  1110. // 5 Filters
  1111. // 5a Filter by cluster with separate idle
  1112. "5a": {
  1113. start: start,
  1114. aggBy: []string{AllocationClusterProp},
  1115. aggOpts: &AllocationAggregationOptions{
  1116. Filter: mustParseFilter(`cluster:"cluster1"`),
  1117. ShareIdle: ShareNone,
  1118. },
  1119. numResults: 1 + numIdle,
  1120. totalCost: 66.0,
  1121. results: map[string]float64{
  1122. "cluster1": 46.00,
  1123. IdleSuffix: 20.00,
  1124. },
  1125. windowStart: startYesterday,
  1126. windowEnd: endYesterday,
  1127. expMinutes: 1440.0,
  1128. },
  1129. // 5b Filter by cluster with shared idle
  1130. "5b": {
  1131. start: start,
  1132. aggBy: []string{AllocationClusterProp},
  1133. aggOpts: &AllocationAggregationOptions{
  1134. Filter: mustParseFilter(`cluster:"cluster1"`),
  1135. ShareIdle: ShareWeighted,
  1136. },
  1137. numResults: 1,
  1138. totalCost: 66.0,
  1139. results: map[string]float64{
  1140. "cluster1": 66.00,
  1141. },
  1142. windowStart: startYesterday,
  1143. windowEnd: endYesterday,
  1144. expMinutes: 1440.0,
  1145. },
  1146. // 5c Filter by cluster, agg by namespace, with separate idle
  1147. "5c": {
  1148. start: start,
  1149. aggBy: []string{AllocationNamespaceProp},
  1150. aggOpts: &AllocationAggregationOptions{
  1151. Filter: mustParseFilter(`cluster:"cluster1"`),
  1152. ShareIdle: ShareNone,
  1153. },
  1154. numResults: 2 + numIdle,
  1155. totalCost: 66.0,
  1156. results: map[string]float64{
  1157. "namespace1": 28.00,
  1158. "namespace2": 18.00,
  1159. IdleSuffix: 20.00,
  1160. },
  1161. windowStart: startYesterday,
  1162. windowEnd: endYesterday,
  1163. expMinutes: 1440.0,
  1164. },
  1165. // 5d Filter by namespace, agg by cluster, with separate idle
  1166. "5d": {
  1167. start: start,
  1168. aggBy: []string{AllocationClusterProp},
  1169. aggOpts: &AllocationAggregationOptions{
  1170. Filter: mustParseFilter(`namespace:"namespace2"`),
  1171. ShareIdle: ShareNone,
  1172. },
  1173. numResults: numClusters + numIdle,
  1174. totalCost: 46.31,
  1175. results: map[string]float64{
  1176. "cluster1": 18.00,
  1177. "cluster2": 18.00,
  1178. IdleSuffix: 10.31,
  1179. },
  1180. windowStart: startYesterday,
  1181. windowEnd: endYesterday,
  1182. expMinutes: 1440.0,
  1183. },
  1184. // 6 Combinations and options
  1185. // 6a SplitIdle
  1186. "6a": {
  1187. start: start,
  1188. aggBy: []string{AllocationNamespaceProp},
  1189. aggOpts: &AllocationAggregationOptions{
  1190. SplitIdle: true,
  1191. },
  1192. numResults: numNamespaces + numSplitIdleCluster,
  1193. totalCost: activeTotalCost + idleTotalCost,
  1194. results: map[string]float64{
  1195. "namespace1": 28.00,
  1196. "namespace2": 36.00,
  1197. "namespace3": 18.00,
  1198. fmt.Sprintf("cluster1/%s", IdleSuffix): 20.00,
  1199. fmt.Sprintf("cluster2/%s", IdleSuffix): 10.00,
  1200. },
  1201. windowStart: startYesterday,
  1202. windowEnd: endYesterday,
  1203. expMinutes: 1440.0,
  1204. },
  1205. // 6b Share idle weighted with filters
  1206. // Should match values from unfiltered aggregation (3a)
  1207. // 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)
  1208. "6b": {
  1209. start: start,
  1210. aggBy: []string{AllocationNamespaceProp},
  1211. aggOpts: &AllocationAggregationOptions{
  1212. Filter: mustParseFilter(`namespace:"namespace2"`),
  1213. ShareIdle: ShareWeighted,
  1214. },
  1215. numResults: 1,
  1216. totalCost: 46.31,
  1217. results: map[string]float64{
  1218. "namespace2": 46.31,
  1219. },
  1220. windowStart: startYesterday,
  1221. windowEnd: endYesterday,
  1222. expMinutes: 1440.0,
  1223. },
  1224. // 6c Share idle even with filters (share idle even is deprecated)
  1225. // 6d Share overhead with filters
  1226. // namespace1: 85.366 = 28.00 + (7.0*24.0)*(28.00/82.00)
  1227. // namespace2: 109.756 = 36.00 + (7.0*24.0)*(36.00/82.00)
  1228. // namespace3: 54.878 = 18.00 + (7.0*24.0)*(18.00/82.00)
  1229. // idle: 10.3125 = % of idle paired with namespace2
  1230. // Then namespace 2 is filtered.
  1231. "6d": {
  1232. start: start,
  1233. aggBy: []string{AllocationNamespaceProp},
  1234. aggOpts: &AllocationAggregationOptions{
  1235. Filter: mustParseFilter(`namespace:"namespace2"`),
  1236. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1237. ShareSplit: ShareWeighted,
  1238. },
  1239. numResults: 1 + numIdle,
  1240. totalCost: 120.0686,
  1241. results: map[string]float64{
  1242. "namespace2": 109.7561,
  1243. IdleSuffix: 10.3125,
  1244. },
  1245. windowStart: startYesterday,
  1246. windowEnd: endYesterday,
  1247. expMinutes: 1440.0,
  1248. },
  1249. // 6e Share resources with filters
  1250. "6e": {
  1251. start: start,
  1252. aggBy: []string{AllocationNamespaceProp},
  1253. aggOpts: &AllocationAggregationOptions{
  1254. Filter: mustParseFilter(`namespace:"namespace2"`),
  1255. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1256. ShareSplit: ShareWeighted,
  1257. },
  1258. numResults: 1 + numIdle,
  1259. totalCost: 79.6667, // should be 74.7708, but I'm punting -- too difficult (NK)
  1260. results: map[string]float64{
  1261. "namespace2": 54.6667,
  1262. IdleSuffix: 25.000, // should be 20.1042, but I'm punting -- too difficult (NK)
  1263. },
  1264. windowStart: startYesterday,
  1265. windowEnd: endYesterday,
  1266. expMinutes: 1440.0,
  1267. },
  1268. // 6f Share resources with filters and share idle
  1269. "6f": {
  1270. start: start,
  1271. aggBy: []string{AllocationNamespaceProp},
  1272. aggOpts: &AllocationAggregationOptions{
  1273. Filter: mustParseFilter(`namespace:"namespace2"`),
  1274. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1275. ShareSplit: ShareWeighted,
  1276. ShareIdle: ShareWeighted,
  1277. },
  1278. numResults: 1,
  1279. totalCost: 74.77083,
  1280. results: map[string]float64{
  1281. "namespace2": 74.77083,
  1282. },
  1283. windowStart: startYesterday,
  1284. windowEnd: endYesterday,
  1285. expMinutes: 1440.0,
  1286. },
  1287. // 6g Share idle weighted and share resources weighted
  1288. //
  1289. // First, share idle weighted produces:
  1290. //
  1291. // namespace1: 42.6875
  1292. // initial cost 28.0000
  1293. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1294. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1295. //
  1296. // namespace2: 46.3125
  1297. // initial cost 36.0000
  1298. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1299. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1300. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1301. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1302. //
  1303. // namespace3: 23.0000
  1304. // initial cost 18.0000
  1305. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1306. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1307. //
  1308. // Then, sharing namespace1 means sharing 39.6875 according to coefficients
  1309. // computed before allocating idle (so that weighting idle differently
  1310. // doesn't adversely affect the sharing mechanism):
  1311. //
  1312. // namespace2: 74.7708
  1313. // initial cost 30.0000
  1314. // idle cost 10.3125
  1315. // shared cost 28.4583 = (42.6875)*(36.0/54.0)
  1316. //
  1317. // namespace3: 37.2292
  1318. // initial cost 18.0000
  1319. // idle cost 5.0000
  1320. // shared cost 14.2292 = (42.6875)*(18.0/54.0)
  1321. "6g": {
  1322. start: start,
  1323. aggBy: []string{AllocationNamespaceProp},
  1324. aggOpts: &AllocationAggregationOptions{
  1325. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1326. ShareSplit: ShareWeighted,
  1327. ShareIdle: ShareWeighted,
  1328. },
  1329. numResults: 2,
  1330. totalCost: activeTotalCost + idleTotalCost,
  1331. results: map[string]float64{
  1332. "namespace2": 74.77,
  1333. "namespace3": 37.23,
  1334. },
  1335. windowStart: startYesterday,
  1336. windowEnd: endYesterday,
  1337. expMinutes: 1440.0,
  1338. },
  1339. // 6h Share idle, share resources, and filter
  1340. //
  1341. // First, share idle weighted produces:
  1342. //
  1343. // namespace1: 42.6875
  1344. // initial cost 28.0000
  1345. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1346. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1347. //
  1348. // namespace2: 46.3125
  1349. // initial cost 36.0000
  1350. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1351. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1352. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1353. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1354. //
  1355. // namespace3: 23.0000
  1356. // initial cost 18.0000
  1357. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1358. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1359. //
  1360. // Then, sharing namespace1 means sharing 39.6875 according to coefficients
  1361. // computed before allocating idle (so that weighting idle differently
  1362. // doesn't adversely affect the sharing mechanism):
  1363. //
  1364. // namespace2: 74.7708
  1365. // initial cost 36.0000
  1366. // idle cost 10.3125
  1367. // shared cost 28.4583 = (42.6875)*(36.0/54.0)
  1368. //
  1369. // namespace3: 37.2292
  1370. // initial cost 18.0000
  1371. // idle cost 5.0000
  1372. // shared cost 14.2292 = (42.6875)*(18.0/54.0)
  1373. //
  1374. // Then, filter for namespace2: 74.7708
  1375. "6h": {
  1376. start: start,
  1377. aggBy: []string{AllocationNamespaceProp},
  1378. aggOpts: &AllocationAggregationOptions{
  1379. Filter: mustParseFilter(`namespace:"namespace2"`),
  1380. ShareFuncs: []AllocationMatchFunc{isNamespace("namespace1")},
  1381. ShareSplit: ShareWeighted,
  1382. ShareIdle: ShareWeighted,
  1383. },
  1384. numResults: 1,
  1385. totalCost: 74.77,
  1386. results: map[string]float64{
  1387. "namespace2": 74.77,
  1388. },
  1389. windowStart: startYesterday,
  1390. windowEnd: endYesterday,
  1391. expMinutes: 1440.0,
  1392. },
  1393. // 6i Share idle, share resources, share overhead
  1394. //
  1395. // Share idle weighted:
  1396. //
  1397. // namespace1: 42.6875
  1398. // initial cost 28.0000
  1399. // cluster1.cpu 2.5000 = 5.00*(3.00/6.00)
  1400. // cluster1.ram 12.1875 = 15.00*(13.0/16.0)
  1401. //
  1402. // namespace2: 46.3125
  1403. // initial cost 36.0000
  1404. // cluster1.cpu 2.5000 = 5.00*(3.0/6.0)
  1405. // cluster1.ram 2.8125 = 15.00*(3.0/16.0)
  1406. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1407. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1408. //
  1409. // namespace3: 23.0000
  1410. // initial cost 18.0000
  1411. // cluster2.cpu 2.5000 = 5.00*(3.0/6.0)
  1412. // cluster2.ram 2.5000 = 5.00*(3.0/6.0)
  1413. //
  1414. // Then share overhead:
  1415. //
  1416. // namespace1: 100.0533 = 42.6875 + (7.0*24.0)*(28.00/82.00)
  1417. // namespace2: 120.0686 = 46.3125 + (7.0*24.0)*(36.00/82.00)
  1418. // namespace3: 59.8780 = 23.0000 + (7.0*24.0)*(18.00/82.00)
  1419. //
  1420. // Then namespace 2 is filtered.
  1421. "6i": {
  1422. start: start,
  1423. aggBy: []string{AllocationNamespaceProp},
  1424. aggOpts: &AllocationAggregationOptions{
  1425. Filter: mustParseFilter(`namespace:"namespace2"`),
  1426. ShareSplit: ShareWeighted,
  1427. ShareIdle: ShareWeighted,
  1428. SharedHourlyCosts: map[string]float64{"total": sharedOverheadHourlyCost},
  1429. },
  1430. numResults: 1,
  1431. totalCost: 120.07,
  1432. results: map[string]float64{
  1433. "namespace2": 120.07,
  1434. },
  1435. windowStart: startYesterday,
  1436. windowEnd: endYesterday,
  1437. expMinutes: 1440.0,
  1438. },
  1439. // 6j Idle by Node
  1440. "6j": {
  1441. start: start,
  1442. aggBy: []string{AllocationNamespaceProp},
  1443. aggOpts: &AllocationAggregationOptions{
  1444. IdleByNode: true,
  1445. IncludeProportionalAssetResourceCosts: true,
  1446. },
  1447. numResults: numNamespaces + numIdle,
  1448. totalCost: activeTotalCost + idleTotalCost,
  1449. results: map[string]float64{
  1450. "namespace1": 28.00,
  1451. "namespace2": 36.00,
  1452. "namespace3": 18.00,
  1453. IdleSuffix: 30.00,
  1454. },
  1455. windowStart: startYesterday,
  1456. windowEnd: endYesterday,
  1457. expMinutes: 1440.0,
  1458. expectedParcResults: map[string]ProportionalAssetResourceCosts{
  1459. "namespace1": {
  1460. "cluster1,c1nodes": ProportionalAssetResourceCost{
  1461. Cluster: "cluster1",
  1462. Name: "c1nodes",
  1463. Type: "Node",
  1464. ProviderID: "c1nodes",
  1465. GPUProportionalCost: 3,
  1466. CPUProportionalCost: 3,
  1467. RAMProportionalCost: 13,
  1468. },
  1469. "cluster2,node2": ProportionalAssetResourceCost{
  1470. Cluster: "cluster2",
  1471. Name: "node2",
  1472. Type: "Node",
  1473. ProviderID: "node2",
  1474. GPUProportionalCost: 3,
  1475. CPUProportionalCost: 3,
  1476. RAMProportionalCost: 3,
  1477. },
  1478. },
  1479. "namespace2": {
  1480. "cluster1,c1nodes": ProportionalAssetResourceCost{
  1481. Cluster: "cluster1",
  1482. Name: "c1nodes",
  1483. Type: "Node",
  1484. ProviderID: "c1nodes",
  1485. GPUProportionalCost: 3,
  1486. CPUProportionalCost: 3,
  1487. RAMProportionalCost: 3,
  1488. },
  1489. "cluster2,node1": ProportionalAssetResourceCost{
  1490. Cluster: "cluster2",
  1491. Name: "node1",
  1492. Type: "Node",
  1493. ProviderID: "node1",
  1494. GPUProportionalCost: 2,
  1495. CPUProportionalCost: 2,
  1496. RAMProportionalCost: 2,
  1497. },
  1498. "cluster2,node2": ProportionalAssetResourceCost{
  1499. Cluster: "cluster2",
  1500. Name: "node2",
  1501. Type: "Node",
  1502. ProviderID: "node2",
  1503. GPUProportionalCost: 1,
  1504. CPUProportionalCost: 1,
  1505. RAMProportionalCost: 1,
  1506. },
  1507. },
  1508. "namespace3": {
  1509. "cluster2,node3": ProportionalAssetResourceCost{
  1510. Cluster: "cluster2",
  1511. Name: "node3",
  1512. Type: "Node",
  1513. ProviderID: "node3",
  1514. GPUProportionalCost: 2,
  1515. CPUProportionalCost: 2,
  1516. RAMProportionalCost: 2,
  1517. },
  1518. "cluster2,node2": ProportionalAssetResourceCost{
  1519. Cluster: "cluster2",
  1520. Name: "node2",
  1521. Type: "Node",
  1522. ProviderID: "node2",
  1523. GPUProportionalCost: 1,
  1524. CPUProportionalCost: 1,
  1525. RAMProportionalCost: 1,
  1526. },
  1527. },
  1528. },
  1529. },
  1530. // 6k Split Idle, Idle by Node
  1531. "6k": {
  1532. start: start,
  1533. aggBy: []string{AllocationNamespaceProp},
  1534. aggOpts: &AllocationAggregationOptions{
  1535. SplitIdle: true,
  1536. IdleByNode: true,
  1537. },
  1538. numResults: numNamespaces + numSplitIdleNode,
  1539. totalCost: activeTotalCost + idleTotalCost,
  1540. results: map[string]float64{
  1541. "namespace1": 28.00,
  1542. "namespace2": 36.00,
  1543. "namespace3": 18.00,
  1544. fmt.Sprintf("c1nodes/%s", IdleSuffix): 20.00,
  1545. fmt.Sprintf("node1/%s", IdleSuffix): 3.333333,
  1546. fmt.Sprintf("node2/%s", IdleSuffix): 3.333333,
  1547. fmt.Sprintf("node3/%s", IdleSuffix): 3.333333,
  1548. },
  1549. windowStart: startYesterday,
  1550. windowEnd: endYesterday,
  1551. expMinutes: 1440.0,
  1552. },
  1553. // Old 6k Share idle Even Idle by Node (share idle even deprecated)
  1554. // 6l Share idle weighted with filters, Idle by Node
  1555. // Should match values from unfiltered aggregation (3a)
  1556. // 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)
  1557. "6l": {
  1558. start: start,
  1559. aggBy: []string{AllocationNamespaceProp},
  1560. aggOpts: &AllocationAggregationOptions{
  1561. Filter: mustParseFilter(`namespace:"namespace2"`),
  1562. ShareIdle: ShareWeighted,
  1563. IdleByNode: true,
  1564. },
  1565. numResults: 1,
  1566. totalCost: 46.31,
  1567. results: map[string]float64{
  1568. "namespace2": 46.31,
  1569. },
  1570. windowStart: startYesterday,
  1571. windowEnd: endYesterday,
  1572. expMinutes: 1440.0,
  1573. },
  1574. // 7 Edge cases and errors
  1575. // 7a Empty AggregationProperties
  1576. // 7b Filter all
  1577. // 7c Share all
  1578. // 7d Share and filter the same allocations
  1579. }
  1580. for name, testcase := range cases {
  1581. t.Run(name, func(t *testing.T) {
  1582. if testcase.aggOpts != nil && testcase.aggOpts.IdleByNode {
  1583. as = GenerateMockAllocationSetNodeIdle(testcase.start)
  1584. } else {
  1585. as = GenerateMockAllocationSetClusterIdle(testcase.start)
  1586. }
  1587. err = as.AggregateBy(testcase.aggBy, testcase.aggOpts)
  1588. assertAllocationSetTotals(t, as, name, err, testcase.numResults, testcase.totalCost)
  1589. assertAllocationTotals(t, as, name, testcase.results)
  1590. assertParcResults(t, as, name, testcase.expectedParcResults)
  1591. assertAllocationWindow(t, as, name, testcase.windowStart, testcase.windowEnd, testcase.expMinutes)
  1592. })
  1593. }
  1594. }
  1595. func TestAllocationSet_AggregateBy_SharedCostBreakdown(t *testing.T) {
  1596. // Set generated by GenerateMockAllocationSet
  1597. // | Hierarchy | Cost | CPU | RAM | GPU | PV | Net | LB |
  1598. // +----------------------------------------+------+------+------+------+------+------+------+
  1599. // cluster1:
  1600. // idle: 20.00 5.00 15.00 0.00 0.00 0.00 0.00
  1601. // namespace1:
  1602. // pod1:
  1603. // container1: [app1, env1] 16.00 1.00 11.00 1.00 1.00 1.00 1.00
  1604. // pod-abc: (deployment1)
  1605. // container2: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1606. // pod-def: (deployment1)
  1607. // container3: 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1608. // namespace2:
  1609. // pod-ghi: (deployment2)
  1610. // container4: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1611. // container5: [app2, env2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1612. // pod-jkl: (daemonset1)
  1613. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1614. // +-----------------------------------------+------+------+------+------+------+------+------+
  1615. // cluster1 subtotal 66.00 11.00 31.00 6.00 6.00 6.00 6.00
  1616. // +-----------------------------------------+------+------+------+------+------+------+------+
  1617. // cluster2:
  1618. // idle: 10.00 5.00 5.00 0.00 0.00 0.00 0.00
  1619. // namespace2:
  1620. // pod-mno: (deployment2)
  1621. // container4: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1622. // container5: [app2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1623. // pod-pqr: (daemonset1)
  1624. // container6: {service1} 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1625. // namespace3:
  1626. // pod-stu: (deployment3)
  1627. // container7: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1628. // pod-vwx: (statefulset1)
  1629. // container8: an[team2] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1630. // container9: an[team1] 6.00 1.00 1.00 1.00 1.00 1.00 1.00
  1631. // +----------------------------------------+------+------+------+------+------+------+------+
  1632. // cluster2 subtotal 46.00 11.00 11.00 6.00 6.00 6.00 6.00
  1633. // +----------------------------------------+------+------+------+------+------+------+------+
  1634. // total 112.00 22.00 42.00 12.00 12.00 12.00 12.00
  1635. // +----------------------------------------+------+------+------+------+------+------+------+
  1636. end := time.Now().UTC().Truncate(day)
  1637. start := end.Add(-day)
  1638. isNamespace1 := func(a *Allocation) bool {
  1639. ns := a.Properties.Namespace
  1640. return ns == "namespace1"
  1641. }
  1642. isNamespace3 := func(a *Allocation) bool {
  1643. ns := a.Properties.Namespace
  1644. return ns == "namespace3"
  1645. }
  1646. cases := map[string]struct {
  1647. start time.Time
  1648. aggBy []string
  1649. aggOpts *AllocationAggregationOptions
  1650. }{
  1651. "agg cluster, flat shared cost": {
  1652. start: start,
  1653. aggBy: []string{"cluster"},
  1654. aggOpts: &AllocationAggregationOptions{
  1655. SharedHourlyCosts: map[string]float64{"share_hourly": 10.0 / timeutil.HoursPerDay},
  1656. IncludeSharedCostBreakdown: true,
  1657. },
  1658. },
  1659. "agg namespace, shared namespace: namespace1": {
  1660. start: start,
  1661. aggBy: []string{"namespace"},
  1662. aggOpts: &AllocationAggregationOptions{
  1663. ShareFuncs: []AllocationMatchFunc{
  1664. isNamespace1,
  1665. },
  1666. IncludeSharedCostBreakdown: true,
  1667. },
  1668. },
  1669. "agg namespace, shared namespace: namespace3": {
  1670. start: start,
  1671. aggBy: []string{"namespace"},
  1672. aggOpts: &AllocationAggregationOptions{
  1673. ShareFuncs: []AllocationMatchFunc{
  1674. isNamespace3,
  1675. },
  1676. IncludeSharedCostBreakdown: true,
  1677. },
  1678. },
  1679. }
  1680. for name, tc := range cases {
  1681. t.Run(name, func(t *testing.T) {
  1682. as := GenerateMockAllocationSetClusterIdle(tc.start)
  1683. err := as.AggregateBy(tc.aggBy, tc.aggOpts)
  1684. if err != nil {
  1685. t.Fatalf("error aggregating: %s", err)
  1686. }
  1687. for _, alloc := range as.Allocations {
  1688. var breakdownTotal float64
  1689. // ignore idle since it should never have shared costs
  1690. if strings.Contains(alloc.Name, IdleSuffix) {
  1691. continue
  1692. }
  1693. for _, sharedAlloc := range alloc.SharedCostBreakdown {
  1694. breakdownTotal += sharedAlloc.TotalCost
  1695. totalInternal := sharedAlloc.CPUCost + sharedAlloc.GPUCost + sharedAlloc.RAMCost + sharedAlloc.NetworkCost + sharedAlloc.LBCost + sharedAlloc.PVCost + sharedAlloc.ExternalCost
  1696. // check that the total cost of a single item in the breakdown equals the sum of its parts
  1697. // we can ignore the overheadCost breakdown since it only has a total
  1698. if totalInternal != sharedAlloc.TotalCost && sharedAlloc.Name != "overheadCost" {
  1699. t.Errorf("expected internal total: %f; got %f", sharedAlloc.TotalCost, totalInternal)
  1700. }
  1701. }
  1702. // check that the totals of all shared cost breakdowns equal the allocation's SharedCost
  1703. if breakdownTotal != alloc.SharedCost {
  1704. t.Errorf("expected breakdown total: %f; got %f", alloc.SharedCost, breakdownTotal)
  1705. }
  1706. }
  1707. })
  1708. }
  1709. }
  1710. // TODO niko/etl
  1711. //func TestAllocationSet_Clone(t *testing.T) {}
  1712. // TODO niko/etl
  1713. //func TestAllocationSet_Delete(t *testing.T) {}
  1714. // TODO niko/etl
  1715. //func TestAllocationSet_End(t *testing.T) {}
  1716. // TODO niko/etl
  1717. //func TestAllocationSet_IdleAllocations(t *testing.T) {}
  1718. // TODO niko/etl
  1719. //func TestAllocationSet_Insert(t *testing.T) {}
  1720. // Asserts that all Allocations within an AllocationSet have a Window that
  1721. // matches that of the AllocationSet.
  1722. func TestAllocationSet_insertMatchingWindow(t *testing.T) {
  1723. setStart := time.Now().Round(time.Hour)
  1724. setEnd := setStart.Add(1 * time.Hour)
  1725. a1WindowStart := setStart.Add(5 * time.Minute)
  1726. a1WindowEnd := setStart.Add(50 * time.Minute)
  1727. a2WindowStart := setStart.Add(17 * time.Minute)
  1728. a2WindowEnd := setStart.Add(34 * time.Minute)
  1729. a1 := &Allocation{
  1730. Name: "allocation-1",
  1731. Window: Window(NewClosedWindow(a1WindowStart, a1WindowEnd)),
  1732. }
  1733. a2 := &Allocation{
  1734. Name: "allocation-2",
  1735. Window: Window(NewClosedWindow(a2WindowStart, a2WindowEnd)),
  1736. }
  1737. as := NewAllocationSet(setStart, setEnd)
  1738. as.Insert(a1)
  1739. as.Insert(a2)
  1740. if as.Length() != 2 {
  1741. t.Errorf("AS length got %d, expected %d", as.Length(), 2)
  1742. }
  1743. for _, a := range as.Allocations {
  1744. if !(*a.Window.Start()).Equal(setStart) {
  1745. t.Errorf("Allocation %s window start is %s, expected %s", a.Name, *a.Window.Start(), setStart)
  1746. }
  1747. if !(*a.Window.End()).Equal(setEnd) {
  1748. t.Errorf("Allocation %s window end is %s, expected %s", a.Name, *a.Window.End(), setEnd)
  1749. }
  1750. }
  1751. }
  1752. // This tests PARC accumulation. Assuming Node cost is $1 per core per hour
  1753. // From https://github.com/opencost/opencost/pull/1867#discussion_r1174109388:
  1754. // Over the span of hour 1:
  1755. // Pod 1 runs for 30 minutes, consuming 1 CPU while alive. PARC: 12.5% (0.5 core-hours / 4 available core-hours)
  1756. // Pod 2 runs for 1 hour, consuming 2 CPU while alive. PARC: 50% (2 core-hours)
  1757. // Pod 3 runs for 1 hour, consuming 1 CPU while alive. PARC: 25% (1 core-hour)
  1758. // Over the span of hour 2:
  1759. // Pod 1 does not run. PARC: 0% (0 core-hours / 4 available core-hours)
  1760. // Pod 2 runs for 30 minutes, consuming 2 CPU while active. PARC: 25% (1 core-hour)
  1761. // Pod 3 runs for 1 hour, consuming 1 CPU while active. PARC: 25% (1 core-hour)
  1762. // Over the span of hour 3:
  1763. // Pod 1 does not run. PARC: 0% (0 core-hours / 4 available)
  1764. // Pod 2 runs for 30 minutes, consuming 3 CPU while active. PARC: 37.5% (1.5 core-hours)
  1765. // Pod 3 runs for 1 hour, consuming 1 CPU while active. PARC: 25% (1 core-hour)
  1766. // We expect the following accumulated PARC:
  1767. // Pod 1: (0.5 + 0 + 0) core-hours used / (4 + 4 + 4) core-hours available = 0.5/12 = 4.16%
  1768. // Pod 2: (2 + 1 + 1.5) / (4 + 4 + 4) = 4.5/12 = 37.5%
  1769. // Pod 3: (1 + 1 + 1) / (4 + 4 + 4) = 3/12 = 25%
  1770. func TestParcInsert(t *testing.T) {
  1771. pod1_hour1 := ProportionalAssetResourceCost{
  1772. Cluster: "cluster1",
  1773. Name: "node1",
  1774. Type: "Node",
  1775. ProviderID: "i-1234",
  1776. CPUPercentage: 0.125,
  1777. GPUPercentage: 0,
  1778. RAMPercentage: 0,
  1779. NodeResourceCostPercentage: 0,
  1780. CPUTotalCost: 4,
  1781. CPUProportionalCost: 0.5,
  1782. }
  1783. pod1_hour2 := ProportionalAssetResourceCost{
  1784. Cluster: "cluster1",
  1785. Name: "node1",
  1786. Type: "Node",
  1787. ProviderID: "i-1234",
  1788. CPUPercentage: 0.0,
  1789. GPUPercentage: 0,
  1790. RAMPercentage: 0,
  1791. NodeResourceCostPercentage: 0,
  1792. CPUTotalCost: 4,
  1793. }
  1794. pod1_hour3 := ProportionalAssetResourceCost{
  1795. Cluster: "cluster1",
  1796. Name: "node1",
  1797. Type: "Node",
  1798. ProviderID: "i-1234",
  1799. CPUPercentage: 0.0,
  1800. GPUPercentage: 0,
  1801. RAMPercentage: 0,
  1802. NodeResourceCostPercentage: 0,
  1803. CPUTotalCost: 4,
  1804. }
  1805. pod2_hour1 := ProportionalAssetResourceCost{
  1806. Cluster: "cluster1",
  1807. Name: "node2",
  1808. Type: "Node",
  1809. ProviderID: "i-1234",
  1810. CPUPercentage: 0.0,
  1811. GPUPercentage: 0,
  1812. RAMPercentage: 0,
  1813. NodeResourceCostPercentage: 0,
  1814. CPUTotalCost: 4,
  1815. CPUProportionalCost: 2,
  1816. }
  1817. pod2_hour2 := ProportionalAssetResourceCost{
  1818. Cluster: "cluster1",
  1819. Name: "node2",
  1820. Type: "Node",
  1821. ProviderID: "i-1234",
  1822. CPUPercentage: 0.0,
  1823. GPUPercentage: 0,
  1824. RAMPercentage: 0,
  1825. NodeResourceCostPercentage: 0,
  1826. CPUTotalCost: 4,
  1827. CPUProportionalCost: 1,
  1828. }
  1829. pod2_hour3 := ProportionalAssetResourceCost{
  1830. Cluster: "cluster1",
  1831. Name: "node2",
  1832. Type: "Node",
  1833. ProviderID: "i-1234",
  1834. CPUPercentage: 0.0,
  1835. GPUPercentage: 0,
  1836. RAMPercentage: 0,
  1837. NodeResourceCostPercentage: 0,
  1838. CPUTotalCost: 4,
  1839. CPUProportionalCost: 1.5,
  1840. }
  1841. pod3_hour1 := ProportionalAssetResourceCost{
  1842. Cluster: "cluster1",
  1843. Name: "node3",
  1844. Type: "Node",
  1845. ProviderID: "i-1234",
  1846. CPUPercentage: 0.0,
  1847. GPUPercentage: 0,
  1848. RAMPercentage: 0,
  1849. NodeResourceCostPercentage: 0,
  1850. CPUTotalCost: 4,
  1851. CPUProportionalCost: 1,
  1852. }
  1853. pod3_hour2 := ProportionalAssetResourceCost{
  1854. Cluster: "cluster1",
  1855. Name: "node3",
  1856. Type: "Node",
  1857. ProviderID: "i-1234",
  1858. CPUPercentage: 0.0,
  1859. GPUPercentage: 0,
  1860. RAMPercentage: 0,
  1861. NodeResourceCostPercentage: 0,
  1862. CPUTotalCost: 4,
  1863. CPUProportionalCost: 1,
  1864. }
  1865. pod3_hour3 := ProportionalAssetResourceCost{
  1866. Cluster: "cluster1",
  1867. Name: "node3",
  1868. Type: "Node",
  1869. ProviderID: "i-1234",
  1870. CPUPercentage: 0.0,
  1871. GPUPercentage: 0,
  1872. RAMPercentage: 0,
  1873. NodeResourceCostPercentage: 0,
  1874. CPUTotalCost: 4,
  1875. CPUProportionalCost: 1,
  1876. }
  1877. parcs := ProportionalAssetResourceCosts{}
  1878. parcs.Insert(pod1_hour1, true)
  1879. parcs.Insert(pod1_hour2, true)
  1880. parcs.Insert(pod1_hour3, true)
  1881. parcs.Insert(pod2_hour1, true)
  1882. parcs.Insert(pod2_hour2, true)
  1883. parcs.Insert(pod2_hour3, true)
  1884. parcs.Insert(pod3_hour1, true)
  1885. parcs.Insert(pod3_hour2, true)
  1886. parcs.Insert(pod3_hour3, true)
  1887. log.Debug("added all parcs")
  1888. // set totals, compute percentaves
  1889. parc1, ok := parcs["cluster1,node1"]
  1890. if !ok {
  1891. t.Fatalf("parc1 not found")
  1892. }
  1893. parc1.CPUTotalCost = 12
  1894. parc2, ok := parcs["cluster1,node2"]
  1895. if !ok {
  1896. t.Fatalf("parc2 not found")
  1897. }
  1898. parc2.CPUTotalCost = 12
  1899. parc3, ok := parcs["cluster1,node3"]
  1900. if !ok {
  1901. t.Fatalf("parc1 not found")
  1902. }
  1903. parc3.CPUTotalCost = 12
  1904. ComputePercentages(&parc1)
  1905. ComputePercentages(&parc2)
  1906. ComputePercentages(&parc3)
  1907. parcs["cluster1,node1"] = parc1
  1908. parcs["cluster1,node2"] = parc2
  1909. parcs["cluster1,node3"] = parc3
  1910. expectedParcs := ProportionalAssetResourceCosts{
  1911. "cluster1,node1": ProportionalAssetResourceCost{
  1912. CPUPercentage: 0.041666666666666664,
  1913. NodeResourceCostPercentage: 0.041666666666666664,
  1914. },
  1915. "cluster1,node2": ProportionalAssetResourceCost{
  1916. CPUPercentage: 0.375,
  1917. NodeResourceCostPercentage: 0.375,
  1918. },
  1919. "cluster1,node3": ProportionalAssetResourceCost{
  1920. CPUPercentage: 0.25,
  1921. NodeResourceCostPercentage: 0.25,
  1922. },
  1923. }
  1924. for key, expectedParc := range expectedParcs {
  1925. actualParc, ok := parcs[key]
  1926. if !ok {
  1927. t.Fatalf("did not find expected PARC: %s", key)
  1928. }
  1929. if actualParc.CPUPercentage != expectedParc.CPUPercentage {
  1930. t.Fatalf("actual parc cpu percentage: %f did not match expected: %f", actualParc.CPUPercentage, expectedParc.CPUPercentage)
  1931. }
  1932. if actualParc.NodeResourceCostPercentage != expectedParc.NodeResourceCostPercentage {
  1933. t.Fatalf("actual parc node percentage: %f did not match expected: %f", actualParc.NodeResourceCostPercentage, expectedParc.NodeResourceCostPercentage)
  1934. }
  1935. }
  1936. }
  1937. // TODO niko/etl
  1938. //func TestAllocationSet_IsEmpty(t *testing.T) {}
  1939. // TODO niko/etl
  1940. //func TestAllocationSet_Length(t *testing.T) {}
  1941. // TODO niko/etl
  1942. //func TestAllocationSet_Map(t *testing.T) {}
  1943. // TODO niko/etl
  1944. //func TestAllocationSet_MarshalJSON(t *testing.T) {}
  1945. // TODO niko/etl
  1946. //func TestAllocationSet_Resolution(t *testing.T) {}
  1947. // TODO niko/etl
  1948. //func TestAllocationSet_Seconds(t *testing.T) {}
  1949. // TODO niko/etl
  1950. //func TestAllocationSet_Set(t *testing.T) {}
  1951. // TODO niko/etl
  1952. //func TestAllocationSet_Start(t *testing.T) {}
  1953. // TODO niko/etl
  1954. //func TestAllocationSet_TotalCost(t *testing.T) {}
  1955. // TODO niko/etl
  1956. //func TestNewAllocationSetRange(t *testing.T) {}
  1957. func TestAllocationSetRange_AccumulateRepeat(t *testing.T) {
  1958. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1959. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1960. today := time.Now().UTC().Truncate(day)
  1961. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1962. a := GenerateMockAllocationSet(ago2d)
  1963. b := GenerateMockAllocationSet(yesterday)
  1964. c := GenerateMockAllocationSet(today)
  1965. d := GenerateMockAllocationSet(tomorrow)
  1966. asr := NewAllocationSetRange(a, b, c, d)
  1967. // Take Total Cost
  1968. totalCost := asr.TotalCost()
  1969. // NewAccumulation does not mutate
  1970. result, err := asr.newAccumulation()
  1971. if err != nil {
  1972. t.Fatal(err)
  1973. }
  1974. asr2 := NewAllocationSetRange(result)
  1975. // Ensure Costs Match
  1976. if totalCost != asr2.TotalCost() {
  1977. t.Fatalf("Accumulated Total Cost does not match original Total Cost")
  1978. }
  1979. // Next NewAccumulation() call should prove that there is no mutation of inner data
  1980. result, err = asr.newAccumulation()
  1981. if err != nil {
  1982. t.Fatal(err)
  1983. }
  1984. asr3 := NewAllocationSetRange(result)
  1985. // Costs should be correct, as multiple calls to NewAccumulation() should not alter
  1986. // the internals of the AllocationSetRange
  1987. if totalCost != asr3.TotalCost() {
  1988. t.Fatalf("Accumulated Total Cost does not match original Total Cost. %f != %f", totalCost, asr3.TotalCost())
  1989. }
  1990. }
  1991. func TestAllocationSetRange_Accumulate(t *testing.T) {
  1992. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  1993. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  1994. today := time.Now().UTC().Truncate(day)
  1995. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  1996. // Accumulating any combination of nil and/or empty set should result in empty set
  1997. result, err := NewAllocationSetRange(nil).accumulate()
  1998. if err != nil {
  1999. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2000. }
  2001. if !result.IsEmpty() {
  2002. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2003. }
  2004. result, err = NewAllocationSetRange(nil, nil).accumulate()
  2005. if err != nil {
  2006. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2007. }
  2008. if !result.IsEmpty() {
  2009. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2010. }
  2011. result, err = NewAllocationSetRange(NewAllocationSet(yesterday, today)).accumulate()
  2012. if err != nil {
  2013. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2014. }
  2015. if !result.IsEmpty() {
  2016. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2017. }
  2018. result, err = NewAllocationSetRange(nil, NewAllocationSet(ago2d, yesterday), nil, NewAllocationSet(today, tomorrow), nil).accumulate()
  2019. if err != nil {
  2020. t.Fatalf("unexpected error accumulating nil AllocationSetRange: %s", err)
  2021. }
  2022. if !result.IsEmpty() {
  2023. t.Fatalf("accumulating nil AllocationSetRange: expected empty; actual %s", result)
  2024. }
  2025. todayAS := NewAllocationSet(today, tomorrow)
  2026. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2027. yesterdayAS := NewAllocationSet(yesterday, today)
  2028. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2029. // Accumulate non-nil with nil should result in copy of non-nil, regardless of order
  2030. result, err = NewAllocationSetRange(nil, todayAS).accumulate()
  2031. if err != nil {
  2032. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2033. }
  2034. if result == nil {
  2035. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2036. }
  2037. if result.TotalCost() != 6.0 {
  2038. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  2039. }
  2040. result, err = NewAllocationSetRange(todayAS, nil).accumulate()
  2041. if err != nil {
  2042. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2043. }
  2044. if result == nil {
  2045. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2046. }
  2047. if result.TotalCost() != 6.0 {
  2048. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  2049. }
  2050. result, err = NewAllocationSetRange(nil, todayAS, nil).accumulate()
  2051. if err != nil {
  2052. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2053. }
  2054. if result == nil {
  2055. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2056. }
  2057. if result.TotalCost() != 6.0 {
  2058. t.Fatalf("accumulating AllocationSetRange: expected total cost 6.0; actual %f", result.TotalCost())
  2059. }
  2060. // Accumulate two non-nil should result in sum of both with appropriate start, end
  2061. result, err = NewAllocationSetRange(yesterdayAS, todayAS).accumulate()
  2062. if err != nil {
  2063. t.Fatalf("unexpected error accumulating AllocationSetRange of length 1: %s", err)
  2064. }
  2065. if result == nil {
  2066. t.Fatalf("accumulating AllocationSetRange: expected AllocationSet; actual %s", result)
  2067. }
  2068. if result.TotalCost() != 12.0 {
  2069. t.Fatalf("accumulating AllocationSetRange: expected total cost 12.0; actual %f", result.TotalCost())
  2070. }
  2071. allocMap := result.Allocations
  2072. if len(allocMap) != 1 {
  2073. t.Fatalf("accumulating AllocationSetRange: expected length 1; actual length %d", len(allocMap))
  2074. }
  2075. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  2076. if alloc == nil {
  2077. t.Fatalf("accumulating AllocationSetRange: expected allocation 'cluster1/namespace1/pod1/container1'")
  2078. }
  2079. if alloc.CPUCoreHours != 2.0 {
  2080. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", result.TotalCost())
  2081. }
  2082. if alloc.CPUCost != 2.0 {
  2083. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.CPUCost)
  2084. }
  2085. if alloc.CPUEfficiency() != 1.0 {
  2086. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.CPUEfficiency())
  2087. }
  2088. if alloc.GPUHours != 2.0 {
  2089. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.GPUHours)
  2090. }
  2091. if alloc.GPUCost != 2.0 {
  2092. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.GPUCost)
  2093. }
  2094. if alloc.NetworkCost != 2.0 {
  2095. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.NetworkCost)
  2096. }
  2097. if alloc.LoadBalancerCost != 2.0 {
  2098. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.LoadBalancerCost)
  2099. }
  2100. if alloc.PVByteHours() != 2.0 {
  2101. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.PVByteHours())
  2102. }
  2103. if alloc.PVCost() != 2.0 {
  2104. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.PVCost())
  2105. }
  2106. if alloc.RAMByteHours != 2.0 {
  2107. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.RAMByteHours)
  2108. }
  2109. if alloc.RAMCost != 2.0 {
  2110. t.Fatalf("accumulating AllocationSetRange: expected 2.0; actual %f", alloc.RAMCost)
  2111. }
  2112. if alloc.RAMEfficiency() != 1.0 {
  2113. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.RAMEfficiency())
  2114. }
  2115. if alloc.TotalCost() != 12.0 {
  2116. t.Fatalf("accumulating AllocationSetRange: expected 12.0; actual %f", alloc.TotalCost())
  2117. }
  2118. if alloc.TotalEfficiency() != 1.0 {
  2119. t.Fatalf("accumulating AllocationSetRange: expected 1.0; actual %f", alloc.TotalEfficiency())
  2120. }
  2121. if !alloc.Start.Equal(yesterday) {
  2122. t.Fatalf("accumulating AllocationSetRange: expected to start %s; actual %s", yesterday, alloc.Start)
  2123. }
  2124. if !alloc.End.Equal(tomorrow) {
  2125. t.Fatalf("accumulating AllocationSetRange: expected to end %s; actual %s", tomorrow, alloc.End)
  2126. }
  2127. if alloc.Minutes() != 2880.0 {
  2128. t.Fatalf("accumulating AllocationSetRange: expected %f minutes; actual %f", 2880.0, alloc.Minutes())
  2129. }
  2130. }
  2131. func TestAllocationSetRange_AccumulateBy_None(t *testing.T) {
  2132. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2133. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2134. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2135. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2136. today := time.Now().UTC().Truncate(day)
  2137. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2138. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2139. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2140. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2141. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2142. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2143. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2144. yesterdayAS := NewAllocationSet(yesterday, today)
  2145. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2146. todayAS := NewAllocationSet(today, tomorrow)
  2147. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2148. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2149. asr, err := asr.Accumulate(AccumulateOptionNone)
  2150. if err != nil {
  2151. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2152. }
  2153. if len(asr.Allocations) != 5 {
  2154. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  2155. }
  2156. }
  2157. func TestAllocationSetRange_AccumulateBy_All(t *testing.T) {
  2158. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2159. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2160. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2161. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2162. today := time.Now().UTC().Truncate(day)
  2163. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2164. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2165. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2166. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2167. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2168. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2169. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2170. yesterdayAS := NewAllocationSet(yesterday, today)
  2171. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2172. todayAS := NewAllocationSet(today, tomorrow)
  2173. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2174. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2175. asr, err := asr.Accumulate(AccumulateOptionAll)
  2176. if err != nil {
  2177. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2178. }
  2179. if len(asr.Allocations) != 1 {
  2180. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  2181. }
  2182. allocMap := asr.Allocations[0].Allocations
  2183. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  2184. if alloc.Minutes() != 4320.0 {
  2185. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 4320.0, alloc.Minutes())
  2186. }
  2187. }
  2188. func TestAllocationSetRange_AccumulateBy_Hour(t *testing.T) {
  2189. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  2190. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  2191. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  2192. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  2193. currentHour := time.Now().UTC().Truncate(time.Hour)
  2194. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  2195. ago4hAS := NewAllocationSet(ago4h, ago3h)
  2196. ago4hAS.Set(NewMockUnitAllocation("4", ago4h, time.Hour, nil))
  2197. ago3hAS := NewAllocationSet(ago3h, ago2h)
  2198. ago3hAS.Set(NewMockUnitAllocation("a", ago3h, time.Hour, nil))
  2199. ago2hAS := NewAllocationSet(ago2h, ago1h)
  2200. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  2201. ago1hAS := NewAllocationSet(ago1h, currentHour)
  2202. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  2203. currentHourAS := NewAllocationSet(currentHour, nextHour)
  2204. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  2205. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  2206. asr, err := asr.Accumulate(AccumulateOptionHour)
  2207. if err != nil {
  2208. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2209. }
  2210. if len(asr.Allocations) != 5 {
  2211. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  2212. }
  2213. allocMap := asr.Allocations[0].Allocations
  2214. alloc := allocMap["4"]
  2215. if alloc.Minutes() != 60.0 {
  2216. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 60.0, alloc.Minutes())
  2217. }
  2218. }
  2219. func TestAllocationSetRange_AccumulateBy_Day_From_Day(t *testing.T) {
  2220. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2221. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2222. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2223. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2224. today := time.Now().UTC().Truncate(day)
  2225. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2226. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2227. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2228. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2229. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2230. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2231. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2232. yesterdayAS := NewAllocationSet(yesterday, today)
  2233. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2234. todayAS := NewAllocationSet(today, tomorrow)
  2235. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2236. asr := NewAllocationSetRange(ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2237. asr, err := asr.Accumulate(AccumulateOptionDay)
  2238. if err != nil {
  2239. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2240. }
  2241. if len(asr.Allocations) != 5 {
  2242. t.Fatalf("expected 5 allocation sets, got:%d", len(asr.Allocations))
  2243. }
  2244. allocMap := asr.Allocations[0].Allocations
  2245. alloc := allocMap["4"]
  2246. if alloc.Minutes() != 1440.0 {
  2247. t.Errorf("accumulating AllocationSetRange: expected %f minutes; actual %f", 1440.0, alloc.Minutes())
  2248. }
  2249. }
  2250. func TestAllocationSetRange_AccumulateBy_Day_From_Hours(t *testing.T) {
  2251. ago4h := time.Now().UTC().Truncate(time.Hour).Add(-4 * time.Hour)
  2252. ago3h := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
  2253. ago2h := time.Now().UTC().Truncate(time.Hour).Add(-2 * time.Hour)
  2254. ago1h := time.Now().UTC().Truncate(time.Hour).Add(-time.Hour)
  2255. currentHour := time.Now().UTC().Truncate(time.Hour)
  2256. nextHour := time.Now().UTC().Truncate(time.Hour).Add(time.Hour)
  2257. ago4hAS := NewAllocationSet(ago4h, ago3h)
  2258. ago4hAS.Set(NewMockUnitAllocation("", ago4h, time.Hour, nil))
  2259. ago3hAS := NewAllocationSet(ago3h, ago2h)
  2260. ago3hAS.Set(NewMockUnitAllocation("", ago3h, time.Hour, nil))
  2261. ago2hAS := NewAllocationSet(ago2h, ago1h)
  2262. ago2hAS.Set(NewMockUnitAllocation("", ago2h, time.Hour, nil))
  2263. ago1hAS := NewAllocationSet(ago1h, currentHour)
  2264. ago1hAS.Set(NewMockUnitAllocation("", ago1h, time.Hour, nil))
  2265. currentHourAS := NewAllocationSet(currentHour, nextHour)
  2266. currentHourAS.Set(NewMockUnitAllocation("", currentHour, time.Hour, nil))
  2267. asr := NewAllocationSetRange(ago4hAS, ago3hAS, ago2hAS, ago1hAS, currentHourAS)
  2268. asr, err := asr.Accumulate(AccumulateOptionDay)
  2269. if err != nil {
  2270. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2271. }
  2272. if len(asr.Allocations) != 1 && len(asr.Allocations) != 2 {
  2273. t.Fatalf("expected 1 allocation set, got:%d", len(asr.Allocations))
  2274. }
  2275. allocMap := asr.Allocations[0].Allocations
  2276. alloc := allocMap["cluster1/namespace1/pod1/container1"]
  2277. if alloc.Minutes() > 300.0 {
  2278. t.Errorf("accumulating AllocationSetRange: expected %f or less minutes; actual %f", 300.0, alloc.Minutes())
  2279. }
  2280. }
  2281. func TestAllocationSetRange_AccumulateBy_Week(t *testing.T) {
  2282. ago9d := time.Now().UTC().Truncate(day).Add(-9 * day)
  2283. ago8d := time.Now().UTC().Truncate(day).Add(-8 * day)
  2284. ago7d := time.Now().UTC().Truncate(day).Add(-7 * day)
  2285. ago6d := time.Now().UTC().Truncate(day).Add(-6 * day)
  2286. ago5d := time.Now().UTC().Truncate(day).Add(-5 * day)
  2287. ago4d := time.Now().UTC().Truncate(day).Add(-4 * day)
  2288. ago3d := time.Now().UTC().Truncate(day).Add(-3 * day)
  2289. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2290. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2291. today := time.Now().UTC().Truncate(day)
  2292. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2293. ago9dAS := NewAllocationSet(ago9d, ago8d)
  2294. ago9dAS.Set(NewMockUnitAllocation("4", ago9d, day, nil))
  2295. ago8dAS := NewAllocationSet(ago8d, ago7d)
  2296. ago8dAS.Set(NewMockUnitAllocation("4", ago8d, day, nil))
  2297. ago7dAS := NewAllocationSet(ago7d, ago6d)
  2298. ago7dAS.Set(NewMockUnitAllocation("4", ago7d, day, nil))
  2299. ago6dAS := NewAllocationSet(ago6d, ago5d)
  2300. ago6dAS.Set(NewMockUnitAllocation("4", ago6d, day, nil))
  2301. ago5dAS := NewAllocationSet(ago5d, ago4d)
  2302. ago5dAS.Set(NewMockUnitAllocation("4", ago5d, day, nil))
  2303. ago4dAS := NewAllocationSet(ago4d, ago3d)
  2304. ago4dAS.Set(NewMockUnitAllocation("4", ago4d, day, nil))
  2305. ago3dAS := NewAllocationSet(ago3d, ago2d)
  2306. ago3dAS.Set(NewMockUnitAllocation("a", ago3d, day, nil))
  2307. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2308. ago2dAS.Set(NewMockUnitAllocation("", ago2d, day, nil))
  2309. yesterdayAS := NewAllocationSet(yesterday, today)
  2310. yesterdayAS.Set(NewMockUnitAllocation("", yesterday, day, nil))
  2311. todayAS := NewAllocationSet(today, tomorrow)
  2312. todayAS.Set(NewMockUnitAllocation("", today, day, nil))
  2313. asr := NewAllocationSetRange(ago9dAS, ago8dAS, ago7dAS, ago6dAS, ago5dAS, ago4dAS, ago3dAS, ago2dAS, yesterdayAS, todayAS)
  2314. asr, err := asr.Accumulate(AccumulateOptionWeek)
  2315. if err != nil {
  2316. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2317. }
  2318. if len(asr.Allocations) != 2 && len(asr.Allocations) != 3 {
  2319. t.Fatalf("expected 2 or 3 allocation sets, got:%d", len(asr.Allocations))
  2320. }
  2321. for _, as := range asr.Allocations {
  2322. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*7 {
  2323. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  2324. }
  2325. }
  2326. }
  2327. func TestAllocationSetRange_AccumulateBy_Month(t *testing.T) {
  2328. prevMonth1stDay := time.Date(2020, 01, 29, 0, 0, 0, 0, time.UTC)
  2329. prevMonth2ndDay := time.Date(2020, 01, 30, 0, 0, 0, 0, time.UTC)
  2330. prevMonth3ndDay := time.Date(2020, 01, 31, 0, 0, 0, 0, time.UTC)
  2331. nextMonth1stDay := time.Date(2020, 02, 01, 0, 0, 0, 0, time.UTC)
  2332. nextMonth2ndDay := time.Date(2020, 02, 02, 0, 0, 0, 0, time.UTC)
  2333. prev1AS := NewAllocationSet(prevMonth1stDay, prevMonth2ndDay)
  2334. prev1AS.Set(NewMockUnitAllocation("", prevMonth1stDay, day, nil))
  2335. prev2AS := NewAllocationSet(prevMonth2ndDay, prevMonth3ndDay)
  2336. prev2AS.Set(NewMockUnitAllocation("", prevMonth2ndDay, day, nil))
  2337. prev3AS := NewAllocationSet(prevMonth3ndDay, nextMonth1stDay)
  2338. prev3AS.Set(NewMockUnitAllocation("", prevMonth3ndDay, day, nil))
  2339. nextAS := NewAllocationSet(nextMonth1stDay, nextMonth2ndDay)
  2340. nextAS.Set(NewMockUnitAllocation("", nextMonth1stDay, day, nil))
  2341. asr := NewAllocationSetRange(prev1AS, prev2AS, prev3AS, nextAS)
  2342. asr, err := asr.Accumulate(AccumulateOptionMonth)
  2343. if err != nil {
  2344. t.Fatalf("unexpected error calling accumulateBy: %s", err)
  2345. }
  2346. if len(asr.Allocations) != 2 {
  2347. t.Fatalf("expected 2 allocation sets, got:%d", len(asr.Allocations))
  2348. }
  2349. for _, as := range asr.Allocations {
  2350. if as.Window.Duration() < time.Hour*24 || as.Window.Duration() > time.Hour*24*31 {
  2351. t.Fatalf("expected window duration to be between 1 and 7 days, got:%s", as.Window.Duration().String())
  2352. }
  2353. }
  2354. }
  2355. // TODO niko/etl
  2356. // func TestAllocationSetRange_AggregateBy(t *testing.T) {}
  2357. // TODO niko/etl
  2358. // func TestAllocationSetRange_Append(t *testing.T) {}
  2359. // TODO niko/etl
  2360. // func TestAllocationSetRange_Each(t *testing.T) {}
  2361. // TODO niko/etl
  2362. // func TestAllocationSetRange_Get(t *testing.T) {}
  2363. func TestAllocationSetRange_InsertRange(t *testing.T) {
  2364. // Set up
  2365. ago2d := time.Now().UTC().Truncate(day).Add(-2 * day)
  2366. yesterday := time.Now().UTC().Truncate(day).Add(-day)
  2367. today := time.Now().UTC().Truncate(day)
  2368. tomorrow := time.Now().UTC().Truncate(day).Add(day)
  2369. unit := NewMockUnitAllocation("", today, day, nil)
  2370. ago2dAS := NewAllocationSet(ago2d, yesterday)
  2371. ago2dAS.Set(NewMockUnitAllocation("a", ago2d, day, nil))
  2372. ago2dAS.Set(NewMockUnitAllocation("b", ago2d, day, nil))
  2373. ago2dAS.Set(NewMockUnitAllocation("c", ago2d, day, nil))
  2374. yesterdayAS := NewAllocationSet(yesterday, today)
  2375. yesterdayAS.Set(NewMockUnitAllocation("a", yesterday, day, nil))
  2376. yesterdayAS.Set(NewMockUnitAllocation("b", yesterday, day, nil))
  2377. yesterdayAS.Set(NewMockUnitAllocation("c", yesterday, day, nil))
  2378. todayAS := NewAllocationSet(today, tomorrow)
  2379. todayAS.Set(NewMockUnitAllocation("a", today, day, nil))
  2380. todayAS.Set(NewMockUnitAllocation("b", today, day, nil))
  2381. todayAS.Set(NewMockUnitAllocation("c", today, day, nil))
  2382. var nilASR *AllocationSetRange
  2383. thisASR := NewAllocationSetRange(yesterdayAS.Clone(), todayAS.Clone())
  2384. thatASR := NewAllocationSetRange(yesterdayAS.Clone())
  2385. longASR := NewAllocationSetRange(ago2dAS.Clone(), yesterdayAS.Clone(), todayAS.Clone())
  2386. var err error
  2387. // Expect an error calling InsertRange on nil
  2388. err = nilASR.InsertRange(thatASR)
  2389. if err == nil {
  2390. t.Fatalf("expected error, got nil")
  2391. }
  2392. // Expect nothing to happen calling InsertRange(nil) on non-nil ASR
  2393. err = thisASR.InsertRange(nil)
  2394. if err != nil {
  2395. t.Fatalf("unexpected error: %s", err)
  2396. }
  2397. for _, as := range thisASR.Allocations {
  2398. for k, a := range as.Allocations {
  2399. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2400. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2401. }
  2402. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2403. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2404. }
  2405. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2406. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2407. }
  2408. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2409. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2410. }
  2411. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2412. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2413. }
  2414. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2415. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2416. }
  2417. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2418. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2419. }
  2420. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2421. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2422. }
  2423. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2424. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2425. }
  2426. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2427. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2428. }
  2429. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2430. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2431. }
  2432. }
  2433. }
  2434. // Expect an error calling InsertRange with a range exceeding the receiver
  2435. err = thisASR.InsertRange(longASR)
  2436. if err == nil {
  2437. t.Fatalf("expected error calling InsertRange with a range exceeding the receiver")
  2438. }
  2439. // Expect each Allocation in "today" to stay the same, but "yesterday" to
  2440. // precisely double when inserting a range that only has a duplicate of
  2441. // "yesterday", but no entry for "today"
  2442. err = thisASR.InsertRange(thatASR)
  2443. if err != nil {
  2444. t.Fatalf("unexpected error: %s", err)
  2445. }
  2446. yAS, err := thisASR.Get(0)
  2447. for k, a := range yAS.Allocations {
  2448. if !util.IsApproximately(a.CPUCoreHours, 2*unit.CPUCoreHours) {
  2449. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2450. }
  2451. if !util.IsApproximately(a.CPUCost, 2*unit.CPUCost) {
  2452. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2453. }
  2454. if !util.IsApproximately(a.RAMByteHours, 2*unit.RAMByteHours) {
  2455. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2456. }
  2457. if !util.IsApproximately(a.RAMCost, 2*unit.RAMCost) {
  2458. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2459. }
  2460. if !util.IsApproximately(a.GPUHours, 2*unit.GPUHours) {
  2461. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2462. }
  2463. if !util.IsApproximately(a.GPUCost, 2*unit.GPUCost) {
  2464. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2465. }
  2466. if !util.IsApproximately(a.PVByteHours(), 2*unit.PVByteHours()) {
  2467. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2468. }
  2469. if !util.IsApproximately(a.PVCost(), 2*unit.PVCost()) {
  2470. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2471. }
  2472. if !util.IsApproximately(a.NetworkCost, 2*unit.NetworkCost) {
  2473. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2474. }
  2475. if !util.IsApproximately(a.LoadBalancerCost, 2*unit.LoadBalancerCost) {
  2476. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2477. }
  2478. if !util.IsApproximately(a.TotalCost(), 2*unit.TotalCost()) {
  2479. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2480. }
  2481. }
  2482. tAS, err := thisASR.Get(1)
  2483. for k, a := range tAS.Allocations {
  2484. if !util.IsApproximately(a.CPUCoreHours, unit.CPUCoreHours) {
  2485. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCoreHours, a.CPUCoreHours)
  2486. }
  2487. if !util.IsApproximately(a.CPUCost, unit.CPUCost) {
  2488. t.Fatalf("allocation %s: expected %f; got %f", k, unit.CPUCost, a.CPUCost)
  2489. }
  2490. if !util.IsApproximately(a.RAMByteHours, unit.RAMByteHours) {
  2491. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMByteHours, a.RAMByteHours)
  2492. }
  2493. if !util.IsApproximately(a.RAMCost, unit.RAMCost) {
  2494. t.Fatalf("allocation %s: expected %f; got %f", k, unit.RAMCost, a.RAMCost)
  2495. }
  2496. if !util.IsApproximately(a.GPUHours, unit.GPUHours) {
  2497. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUHours, a.GPUHours)
  2498. }
  2499. if !util.IsApproximately(a.GPUCost, unit.GPUCost) {
  2500. t.Fatalf("allocation %s: expected %f; got %f", k, unit.GPUCost, a.GPUCost)
  2501. }
  2502. if !util.IsApproximately(a.PVByteHours(), unit.PVByteHours()) {
  2503. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVByteHours(), a.PVByteHours())
  2504. }
  2505. if !util.IsApproximately(a.PVCost(), unit.PVCost()) {
  2506. t.Fatalf("allocation %s: expected %f; got %f", k, unit.PVCost(), a.PVCost())
  2507. }
  2508. if !util.IsApproximately(a.NetworkCost, unit.NetworkCost) {
  2509. t.Fatalf("allocation %s: expected %f; got %f", k, unit.NetworkCost, a.NetworkCost)
  2510. }
  2511. if !util.IsApproximately(a.LoadBalancerCost, unit.LoadBalancerCost) {
  2512. t.Fatalf("allocation %s: expected %f; got %f", k, unit.LoadBalancerCost, a.LoadBalancerCost)
  2513. }
  2514. if !util.IsApproximately(a.TotalCost(), unit.TotalCost()) {
  2515. t.Fatalf("allocation %s: expected %f; got %f", k, unit.TotalCost(), a.TotalCost())
  2516. }
  2517. }
  2518. }
  2519. // TODO niko/etl
  2520. // func TestAllocationSetRange_Length(t *testing.T) {}
  2521. func TestAllocationSetRange_MarshalJSON(t *testing.T) {
  2522. tests := []struct {
  2523. name string
  2524. arg *AllocationSetRange
  2525. expected *AllocationSetRange
  2526. }{
  2527. {
  2528. name: "Nil ASR",
  2529. arg: nil,
  2530. },
  2531. {
  2532. name: "Nil AS in ASR",
  2533. arg: NewAllocationSetRange(nil),
  2534. },
  2535. {
  2536. name: "Normal ASR",
  2537. arg: &AllocationSetRange{
  2538. Allocations: []*AllocationSet{
  2539. {
  2540. Allocations: map[string]*Allocation{
  2541. "a": {
  2542. Start: time.Now().UTC().Truncate(day),
  2543. },
  2544. },
  2545. },
  2546. },
  2547. },
  2548. },
  2549. }
  2550. for _, test := range tests {
  2551. bytes, err := json.Marshal(test.arg)
  2552. if err != nil {
  2553. t.Fatalf("ASR Marshal: test %s, unexpected error: %s", test.name, err)
  2554. }
  2555. var testASR []*AllocationSet
  2556. marshaled := &testASR
  2557. err = json.Unmarshal(bytes, marshaled)
  2558. if err != nil {
  2559. t.Fatalf("ASR Unmarshal: test %s: unexpected error: %s", test.name, err)
  2560. }
  2561. if test.arg.Length() != len(testASR) {
  2562. t.Fatalf("ASR Unmarshal: test %s: length mutated in encoding: expected %d but got %d", test.name, test.arg.Length(), len(testASR))
  2563. }
  2564. // Allocations don't unmarshal back from json
  2565. }
  2566. }
  2567. // TODO niko/etl
  2568. // func TestAllocationSetRange_Slice(t *testing.T) {}
  2569. // TODO niko/etl
  2570. // func TestAllocationSetRange_Window(t *testing.T) {}
  2571. func TestAllocationSetRange_Start(t *testing.T) {
  2572. tests := []struct {
  2573. name string
  2574. arg *AllocationSetRange
  2575. expectError bool
  2576. expected time.Time
  2577. }{
  2578. {
  2579. name: "Empty ASR",
  2580. arg: nil,
  2581. expectError: true,
  2582. },
  2583. {
  2584. name: "Single allocation",
  2585. arg: &AllocationSetRange{
  2586. Allocations: []*AllocationSet{
  2587. {
  2588. Allocations: map[string]*Allocation{
  2589. "a": {
  2590. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2591. },
  2592. },
  2593. },
  2594. },
  2595. },
  2596. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2597. },
  2598. {
  2599. name: "Two allocations",
  2600. arg: &AllocationSetRange{
  2601. Allocations: []*AllocationSet{
  2602. {
  2603. Allocations: map[string]*Allocation{
  2604. "a": {
  2605. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2606. },
  2607. "b": {
  2608. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2609. },
  2610. },
  2611. },
  2612. },
  2613. },
  2614. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2615. },
  2616. {
  2617. name: "Two AllocationSets",
  2618. arg: &AllocationSetRange{
  2619. Allocations: []*AllocationSet{
  2620. {
  2621. Allocations: map[string]*Allocation{
  2622. "a": {
  2623. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2624. },
  2625. },
  2626. },
  2627. {
  2628. Allocations: map[string]*Allocation{
  2629. "b": {
  2630. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2631. },
  2632. },
  2633. },
  2634. },
  2635. },
  2636. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2637. },
  2638. }
  2639. for _, test := range tests {
  2640. result, err := test.arg.Start()
  2641. if test.expectError && err != nil {
  2642. continue
  2643. }
  2644. if test.expectError && err == nil {
  2645. t.Errorf("%s: expected error and got none", test.name)
  2646. } else if result != test.expected {
  2647. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2648. }
  2649. }
  2650. }
  2651. func TestAllocationSetRange_End(t *testing.T) {
  2652. tests := []struct {
  2653. name string
  2654. arg *AllocationSetRange
  2655. expectError bool
  2656. expected time.Time
  2657. }{
  2658. {
  2659. name: "Empty ASR",
  2660. arg: nil,
  2661. expectError: true,
  2662. },
  2663. {
  2664. name: "Single allocation",
  2665. arg: &AllocationSetRange{
  2666. Allocations: []*AllocationSet{
  2667. {
  2668. Allocations: map[string]*Allocation{
  2669. "a": {
  2670. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2671. },
  2672. },
  2673. },
  2674. },
  2675. },
  2676. expected: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2677. },
  2678. {
  2679. name: "Two allocations",
  2680. arg: &AllocationSetRange{
  2681. Allocations: []*AllocationSet{
  2682. {
  2683. Allocations: map[string]*Allocation{
  2684. "a": {
  2685. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2686. },
  2687. "b": {
  2688. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2689. },
  2690. },
  2691. },
  2692. },
  2693. },
  2694. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2695. },
  2696. {
  2697. name: "Two AllocationSets",
  2698. arg: &AllocationSetRange{
  2699. Allocations: []*AllocationSet{
  2700. {
  2701. Allocations: map[string]*Allocation{
  2702. "a": {
  2703. End: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2704. },
  2705. },
  2706. },
  2707. {
  2708. Allocations: map[string]*Allocation{
  2709. "b": {
  2710. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2711. },
  2712. },
  2713. },
  2714. },
  2715. },
  2716. expected: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2717. },
  2718. }
  2719. for _, test := range tests {
  2720. result, err := test.arg.End()
  2721. if test.expectError && err != nil {
  2722. continue
  2723. }
  2724. if test.expectError && err == nil {
  2725. t.Errorf("%s: expected error and got none", test.name)
  2726. } else if result != test.expected {
  2727. t.Errorf("%s: expected %s but got %s", test.name, test.expected, result)
  2728. }
  2729. }
  2730. }
  2731. func TestAllocationSetRange_Minutes(t *testing.T) {
  2732. tests := []struct {
  2733. name string
  2734. arg *AllocationSetRange
  2735. expected float64
  2736. }{
  2737. {
  2738. name: "Empty ASR",
  2739. arg: nil,
  2740. expected: 0,
  2741. },
  2742. {
  2743. name: "Single allocation",
  2744. arg: &AllocationSetRange{
  2745. Allocations: []*AllocationSet{
  2746. {
  2747. Allocations: map[string]*Allocation{
  2748. "a": {
  2749. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2750. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2751. },
  2752. },
  2753. },
  2754. },
  2755. },
  2756. expected: 24 * 60,
  2757. },
  2758. {
  2759. name: "Two allocations",
  2760. arg: &AllocationSetRange{
  2761. Allocations: []*AllocationSet{
  2762. {
  2763. Allocations: map[string]*Allocation{
  2764. "a": {
  2765. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2766. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2767. },
  2768. "b": {
  2769. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2770. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  2771. },
  2772. },
  2773. },
  2774. },
  2775. },
  2776. expected: 2 * 24 * 60,
  2777. },
  2778. {
  2779. name: "Two AllocationSets",
  2780. arg: &AllocationSetRange{
  2781. Allocations: []*AllocationSet{
  2782. {
  2783. Allocations: map[string]*Allocation{
  2784. "a": {
  2785. Start: time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC),
  2786. End: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2787. },
  2788. },
  2789. },
  2790. {
  2791. Allocations: map[string]*Allocation{
  2792. "b": {
  2793. Start: time.Date(1970, 1, 2, 0, 0, 0, 0, time.UTC),
  2794. End: time.Date(1970, 1, 3, 0, 0, 0, 0, time.UTC),
  2795. },
  2796. },
  2797. },
  2798. },
  2799. },
  2800. expected: 2 * 24 * 60,
  2801. },
  2802. }
  2803. for _, test := range tests {
  2804. result := test.arg.Minutes()
  2805. if result != test.expected {
  2806. t.Errorf("%s: expected %f but got %f", test.name, test.expected, result)
  2807. }
  2808. }
  2809. }
  2810. func TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate(t *testing.T) {
  2811. today := time.Now().Round(day)
  2812. start := today.AddDate(0, 0, -4)
  2813. var allocationSets []*AllocationSet
  2814. for i := 0; i < 4; i++ {
  2815. allocationSets = append(allocationSets, GenerateMockAllocationSet(start))
  2816. start = start.AddDate(0, 0, 1)
  2817. }
  2818. var originalAllocationSets []*AllocationSet
  2819. for _, as := range allocationSets {
  2820. originalAllocationSets = append(originalAllocationSets, as.Clone())
  2821. }
  2822. asr := NewAllocationSetRange()
  2823. for _, as := range allocationSets {
  2824. asr.Append(as.Clone())
  2825. }
  2826. expected, err := asr.accumulate()
  2827. if err != nil {
  2828. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: AllocationSetRange.Accumulate() returned an error\n")
  2829. }
  2830. var got *AllocationSet
  2831. for i := 0; i < len(allocationSets); i++ {
  2832. got, err = got.Accumulate(allocationSets[i])
  2833. if err != nil {
  2834. t.Errorf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Accumulate(allocationSets[%d]) returned an error\n", i)
  2835. }
  2836. }
  2837. // compare the got and expected Allocation sets, ensure that they match
  2838. if len(got.Allocations) != len(expected.Allocations) {
  2839. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.Allocations does not match length of expected.Allocations\n")
  2840. }
  2841. for key, a := range got.Allocations {
  2842. if _, ok := expected.Allocations[key]; !ok {
  2843. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] not found in expected.Allocations\n", key)
  2844. }
  2845. if !a.Equal(expected.Allocations[key]) {
  2846. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: got.Allocations[%s] did not match expected.Allocations[%[1]s]", key)
  2847. }
  2848. }
  2849. if len(got.ExternalKeys) != len(expected.ExternalKeys) {
  2850. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.ExternalKeys does not match length of expected.ExternalKeys\n")
  2851. }
  2852. if len(got.IdleKeys) != len(expected.IdleKeys) {
  2853. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: length of got.IdleKeys does not match length of expected.IdleKeys\n")
  2854. }
  2855. if !got.Window.Start().UTC().Equal(expected.Window.Start().UTC()) {
  2856. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.start: got:%s, expected:%s\n", got.Window.Start(), expected.Window.Start())
  2857. }
  2858. if !got.Window.End().UTC().Equal(expected.Window.End().UTC()) {
  2859. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: Window.end: got:%s, expected:%s\n", got.Window.End(), expected.Window.End())
  2860. }
  2861. for i := range allocationSets {
  2862. for key, allocation := range allocationSets[i].Allocations {
  2863. if !allocation.Equal(originalAllocationSets[i].Allocations[key]) {
  2864. t.Fatalf("TestAllocationSet_Accumulate_Equals_AllocationSetRange_Accumulate: allocationSet has been mutated in Accumulate; allocationSet: %d, allocation: %s\n", i, key)
  2865. }
  2866. }
  2867. }
  2868. }
  2869. func Test_AggregateByService_UnmountedLBs(t *testing.T) {
  2870. end := time.Now().UTC().Truncate(day)
  2871. start := end.Add(-day)
  2872. normalProps := &AllocationProperties{
  2873. Cluster: "cluster-one",
  2874. Container: "nginx-plus-nginx-ingress",
  2875. Controller: "nginx-plus-nginx-ingress",
  2876. ControllerKind: "deployment",
  2877. Namespace: "nginx-plus",
  2878. Pod: "nginx-plus-nginx-ingress-123a4b5678-ab12c",
  2879. ProviderID: "test",
  2880. Node: "testnode",
  2881. Services: []string{
  2882. "nginx-plus-nginx-ingress",
  2883. },
  2884. }
  2885. problematicProps := &AllocationProperties{
  2886. Cluster: "cluster-one",
  2887. Container: UnmountedSuffix,
  2888. Namespace: UnmountedSuffix,
  2889. Pod: UnmountedSuffix,
  2890. ProviderID: "test",
  2891. Node: "testnode",
  2892. Services: []string{
  2893. "nginx-plus-nginx-ingress",
  2894. "ingress-nginx-controller",
  2895. "pacman",
  2896. },
  2897. }
  2898. idle := NewMockUnitAllocation(fmt.Sprintf("cluster-one/%s", IdleSuffix), start, day, &AllocationProperties{
  2899. Cluster: "cluster-one",
  2900. })
  2901. // this allocation is the main point of the test; an unmounted LB that has services
  2902. problematicAllocation := NewMockUnitAllocation("cluster-one//__unmounted__/__unmounted__/__unmounted__", start, day, problematicProps)
  2903. two := NewMockUnitAllocation("cluster-one//nginx-plus/nginx-plus-nginx-ingress-123a4b5678-ab12c/nginx-plus-nginx-ingress", start, day, normalProps)
  2904. three := NewMockUnitAllocation("cluster-one//nginx-plus/nginx-plus-nginx-ingress-123a4b5678-ab12c/nginx-plus-nginx-ingress", start, day, normalProps)
  2905. four := NewMockUnitAllocation("cluster-one//nginx-plus/nginx-plus-nginx-ingress-123a4b5678-ab12c/nginx-plus-nginx-ingress", start, day, normalProps)
  2906. problematicAllocation.ExternalCost = 2.35
  2907. two.ExternalCost = 1.35
  2908. three.ExternalCost = 2.60
  2909. four.ExternalCost = 4.30
  2910. set := NewAllocationSet(start, start.Add(day), problematicAllocation, two, three, four)
  2911. set.Insert(idle)
  2912. set.AggregateBy([]string{AllocationServiceProp}, &AllocationAggregationOptions{
  2913. Filter: ops.Contains(afilter.FieldServices, "nginx-plus-nginx-ingress"),
  2914. })
  2915. for _, alloc := range set.Allocations {
  2916. if !strings.Contains(UnmountedSuffix, alloc.Name) {
  2917. props := alloc.Properties
  2918. if props.Cluster == UnmountedSuffix {
  2919. t.Error("cluster unmounted")
  2920. }
  2921. if props.Container == UnmountedSuffix {
  2922. t.Error("container unmounted")
  2923. }
  2924. if props.Namespace == UnmountedSuffix {
  2925. t.Error("namespace unmounted")
  2926. }
  2927. if props.Pod == UnmountedSuffix {
  2928. t.Error("pod unmounted")
  2929. }
  2930. if props.Controller == UnmountedSuffix {
  2931. t.Error("controller unmounted")
  2932. }
  2933. }
  2934. }
  2935. spew.Config.DisableMethods = true
  2936. t.Logf("%s", spew.Sdump(set.Allocations))
  2937. }
  2938. func Test_DetermineSharingName(t *testing.T) {
  2939. var alloc *Allocation
  2940. var name string
  2941. var err error
  2942. // test nil allocation with nil options
  2943. name, err = alloc.determineSharingName(nil)
  2944. if err == nil {
  2945. t.Fatalf("determineSharingName: expected error; actual nil")
  2946. }
  2947. // test nil with non-nil options
  2948. name, err = alloc.determineSharingName(&AllocationAggregationOptions{})
  2949. if err == nil {
  2950. t.Fatalf("determineSharingName: expected error; actual nil")
  2951. }
  2952. alloc = &Allocation{}
  2953. alloc.Properties = &AllocationProperties{
  2954. Cluster: "cluster1",
  2955. Labels: map[string]string{
  2956. "app": "app1",
  2957. "env": "env1",
  2958. },
  2959. Namespace: "namespace1",
  2960. }
  2961. // test non-nil allocation with nil options
  2962. name, err = alloc.determineSharingName(nil)
  2963. if err != nil {
  2964. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  2965. } else if err != nil || name != "unknown" {
  2966. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  2967. }
  2968. // test non-nil allocation with empty options
  2969. options := &AllocationAggregationOptions{}
  2970. name, err = alloc.determineSharingName(options)
  2971. if err != nil {
  2972. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  2973. } else if err != nil || name != "unknown" {
  2974. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  2975. }
  2976. // test non-nil allocation with matching namespace options
  2977. options.SharedNamespaces = []string{"namespace1"}
  2978. name, err = alloc.determineSharingName(options)
  2979. if err != nil {
  2980. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  2981. } else if err != nil || name != "namespace1" {
  2982. t.Fatalf("determineSharingName: expected \"namespace1\"; actual \"%s\"", name)
  2983. }
  2984. // test non-nil allocation with non-matching namespace options
  2985. options.SharedNamespaces = []string{"namespace2"}
  2986. name, err = alloc.determineSharingName(options)
  2987. if err != nil {
  2988. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  2989. } else if err != nil || name != "unknown" {
  2990. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  2991. }
  2992. // test non-nil allocation with matching label options
  2993. options.SharedNamespaces = nil
  2994. options.SharedLabels = map[string][]string{
  2995. "app": {"app1"},
  2996. }
  2997. name, err = alloc.determineSharingName(options)
  2998. if err != nil {
  2999. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3000. } else if err != nil || name != "app1" {
  3001. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3002. }
  3003. // test non-nil allocation with partial-matching label options
  3004. options.SharedLabels = map[string][]string{
  3005. "app": {"app1", "app2"},
  3006. }
  3007. name, err = alloc.determineSharingName(options)
  3008. if err != nil {
  3009. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3010. } else if err != nil || name != "app1" {
  3011. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3012. }
  3013. // test non-nil allocation with non-matching label options
  3014. options.SharedLabels = map[string][]string{
  3015. "app": {"app2"},
  3016. }
  3017. name, err = alloc.determineSharingName(options)
  3018. if err != nil {
  3019. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3020. } else if err != nil || name != "unknown" {
  3021. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3022. }
  3023. // test non-nil allocation with matching namespace and label options
  3024. options.SharedNamespaces = []string{"namespace1"}
  3025. options.SharedLabels = map[string][]string{
  3026. "app": {"app1"},
  3027. }
  3028. name, err = alloc.determineSharingName(options)
  3029. if err != nil {
  3030. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3031. } else if err != nil || name != "app1" {
  3032. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3033. }
  3034. // test non-nil allocation with non-matching namespace and matching label options
  3035. options.SharedNamespaces = []string{"namespace2"}
  3036. options.SharedLabels = map[string][]string{
  3037. "app": {"app1"},
  3038. }
  3039. name, err = alloc.determineSharingName(options)
  3040. if err != nil {
  3041. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3042. } else if err != nil || name != "app1" {
  3043. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3044. }
  3045. // test non-nil allocation with non-matching namespace and non-matching label options
  3046. options.SharedNamespaces = []string{"namespace2"}
  3047. options.SharedLabels = map[string][]string{
  3048. "app": {"app2"},
  3049. }
  3050. name, err = alloc.determineSharingName(options)
  3051. if err != nil {
  3052. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3053. } else if err != nil || name != "unknown" {
  3054. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3055. }
  3056. // test non-nil allocation with multiple matching label options
  3057. alloc.Properties.Labels = map[string]string{
  3058. "app": "app1",
  3059. "env": "env1",
  3060. }
  3061. options.SharedNamespaces = nil
  3062. options.SharedLabels = map[string][]string{
  3063. "app": {"app1"},
  3064. "env": {"env1"},
  3065. }
  3066. name, err = alloc.determineSharingName(options)
  3067. if err != nil {
  3068. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3069. } else if err != nil || name != "app1" {
  3070. t.Fatalf("determineSharingName: expected \"app1\"; actual \"%s\"", name)
  3071. }
  3072. // test non-nil allocation with one matching label option
  3073. alloc.Properties.Labels = map[string]string{
  3074. "app": "app2",
  3075. "env": "env1",
  3076. }
  3077. options.SharedNamespaces = nil
  3078. options.SharedLabels = map[string][]string{
  3079. "app": {"app1"},
  3080. "env": {"env1"},
  3081. }
  3082. name, err = alloc.determineSharingName(options)
  3083. if err != nil {
  3084. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3085. } else if err != nil || name != "env1" {
  3086. t.Fatalf("determineSharingName: expected \"env1\"; actual \"%s\"", name)
  3087. }
  3088. // test non-nil allocation with one matching namespace option
  3089. alloc.Properties.Namespace = "namespace1"
  3090. options.SharedNamespaces = []string{"namespace1", "namespace2"}
  3091. options.SharedLabels = nil
  3092. name, err = alloc.determineSharingName(options)
  3093. if err != nil {
  3094. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3095. } else if err != nil || name != "namespace1" {
  3096. t.Fatalf("determineSharingName: expected \"namespace1\"; actual \"%s\"", name)
  3097. }
  3098. // test non-nil allocation with another one matching namespace option
  3099. alloc.Properties.Namespace = "namespace2"
  3100. options.SharedNamespaces = []string{"namespace1", "namespace2"}
  3101. options.SharedLabels = nil
  3102. name, err = alloc.determineSharingName(options)
  3103. if err != nil {
  3104. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3105. } else if err != nil || name != "namespace2" {
  3106. t.Fatalf("determineSharingName: expected \"namespace2\"; actual \"%s\"", name)
  3107. }
  3108. // test non-nil allocation with non-matching namespace options
  3109. alloc.Properties.Namespace = "namespace3"
  3110. options.SharedNamespaces = []string{"namespace1", "namespace2"}
  3111. name, err = alloc.determineSharingName(options)
  3112. if err != nil {
  3113. t.Fatalf("determineSharingName: expected no error; actual \"%s\"", err)
  3114. } else if err != nil || name != "unknown" {
  3115. t.Fatalf("determineSharingName: expected \"unknown\"; actual \"%s\"", name)
  3116. }
  3117. }
  3118. func TestIsFilterEmptyTrue(t *testing.T) {
  3119. compiler := NewAllocationMatchCompiler(nil)
  3120. matcher, err := compiler.Compile(nil)
  3121. if err != nil {
  3122. t.Fatalf("compiling nil filter: %s", err)
  3123. }
  3124. result := isFilterEmpty(matcher)
  3125. if !result {
  3126. t.Errorf("matcher '%+v' should be reported empty but wasn't", matcher)
  3127. }
  3128. }
  3129. func TestIsFilterEmptyFalse(t *testing.T) {
  3130. compiler := NewAllocationMatchCompiler(nil)
  3131. matcher, err := compiler.Compile(ops.Eq(afilter.FieldClusterID, "test"))
  3132. if err != nil {
  3133. t.Fatalf("compiling nil filter: %s", err)
  3134. }
  3135. result := isFilterEmpty(matcher)
  3136. if result {
  3137. t.Errorf("matcher '%+v' should be not be reported empty but was", matcher)
  3138. }
  3139. }