allocation_test.go 94 KB

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