allocation_test.go 115 KB

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