allocation.go 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006
  1. package kubecost
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "time"
  7. "github.com/opencost/opencost/pkg/log"
  8. "github.com/opencost/opencost/pkg/util"
  9. "github.com/opencost/opencost/pkg/util/timeutil"
  10. "golang.org/x/exp/slices"
  11. )
  12. // TODO Clean-up use of IsEmpty; nil checks should be separated for safety.
  13. // TODO Consider making Allocation an interface, which is fulfilled by structs
  14. // like KubernetesAllocation, IdleAllocation, and ExternalAllocation.
  15. // ExternalSuffix indicates an external allocation
  16. const ExternalSuffix = "__external__"
  17. // IdleSuffix indicates an idle allocation property
  18. const IdleSuffix = "__idle__"
  19. // SharedSuffix indicates an shared allocation property
  20. const SharedSuffix = "__shared__"
  21. // UnallocatedSuffix indicates an unallocated allocation property
  22. const UnallocatedSuffix = "__unallocated__"
  23. // UnmountedSuffix indicated allocation to an unmounted resource (PV or LB)
  24. const UnmountedSuffix = "__unmounted__"
  25. // ShareWeighted indicates that a shared resource should be shared as a
  26. // proportion of the cost of the remaining allocations.
  27. const ShareWeighted = "__weighted__"
  28. // ShareEven indicates that a shared resource should be shared evenly across
  29. // all remaining allocations.
  30. const ShareEven = "__even__"
  31. // ShareNone indicates that a shareable resource should not be shared
  32. const ShareNone = "__none__"
  33. // Allocation is a unit of resource allocation and cost for a given window
  34. // of time and for a given kubernetes construct with its associated set of
  35. // properties.
  36. // TODO:CLEANUP consider dropping name in favor of just Allocation and an
  37. // Assets-style key() function for AllocationSet.
  38. type Allocation struct {
  39. Name string `json:"name"`
  40. Properties *AllocationProperties `json:"properties,omitempty"`
  41. Window Window `json:"window"`
  42. Start time.Time `json:"start"`
  43. End time.Time `json:"end"`
  44. CPUCoreHours float64 `json:"cpuCoreHours"`
  45. CPUCoreRequestAverage float64 `json:"cpuCoreRequestAverage"`
  46. CPUCoreUsageAverage float64 `json:"cpuCoreUsageAverage"`
  47. CPUCost float64 `json:"cpuCost"`
  48. CPUCostAdjustment float64 `json:"cpuCostAdjustment"`
  49. GPUHours float64 `json:"gpuHours"`
  50. GPUCost float64 `json:"gpuCost"`
  51. GPUCostAdjustment float64 `json:"gpuCostAdjustment"`
  52. NetworkTransferBytes float64 `json:"networkTransferBytes"`
  53. NetworkReceiveBytes float64 `json:"networkReceiveBytes"`
  54. NetworkCost float64 `json:"networkCost"`
  55. NetworkCrossZoneCost float64 `json:"networkCrossZoneCost"` // @bingen:field[version=16]
  56. NetworkCrossRegionCost float64 `json:"networkCrossRegionCost"` // @bingen:field[version=16]
  57. NetworkInternetCost float64 `json:"networkInternetCost"` // @bingen:field[version=16]
  58. NetworkCostAdjustment float64 `json:"networkCostAdjustment"`
  59. LoadBalancerCost float64 `json:"loadBalancerCost"`
  60. LoadBalancerCostAdjustment float64 `json:"loadBalancerCostAdjustment"`
  61. PVs PVAllocations `json:"pvs"`
  62. PVCostAdjustment float64 `json:"pvCostAdjustment"`
  63. RAMByteHours float64 `json:"ramByteHours"`
  64. RAMBytesRequestAverage float64 `json:"ramByteRequestAverage"`
  65. RAMBytesUsageAverage float64 `json:"ramByteUsageAverage"`
  66. RAMCost float64 `json:"ramCost"`
  67. RAMCostAdjustment float64 `json:"ramCostAdjustment"`
  68. SharedCost float64 `json:"sharedCost"`
  69. ExternalCost float64 `json:"externalCost"`
  70. // RawAllocationOnly is a pointer so if it is not present it will be
  71. // marshalled as null rather than as an object with Go default values.
  72. RawAllocationOnly *RawAllocationOnlyData `json:"rawAllocationOnly"`
  73. // ProportionalAssetResourceCost represents the per-resource costs of the
  74. // allocation as a percentage of the per-resource total cost of the
  75. // asset on which the allocation was run. It is optionally computed
  76. // and appended to an Allocation, and so by default is is nil.
  77. ProportionalAssetResourceCosts ProportionalAssetResourceCosts `json:"proportionalAssetResourceCosts"` //@bingen:field[ignore]
  78. SharedCostBreakdown SharedCostBreakdowns `json:"sharedCostBreakdown"` //@bingen:field[ignore]
  79. }
  80. // RawAllocationOnlyData is information that only belong in "raw" Allocations,
  81. // those which have not undergone aggregation, accumulation, or any other form
  82. // of combination to produce a new Allocation from other Allocations.
  83. //
  84. // Max usage data belongs here because computing the overall maximum from two
  85. // or more Allocations is a non-trivial operation that cannot be defined without
  86. // maintaining a large amount of state. Consider the following example:
  87. // _______________________________________________
  88. //
  89. // A1 Using 3 CPU ---- ----- ------
  90. // A2 Using 2 CPU ---- ----- ----
  91. // A3 Using 1 CPU --- --
  92. // _______________________________________________
  93. //
  94. // Time ---->
  95. //
  96. // The logical maximum CPU usage is 5, but this cannot be calculated iteratively,
  97. // which is how we calculate aggregations and accumulations of Allocations currently.
  98. // This becomes a problem I could call "maximum sum of overlapping intervals" and is
  99. // essentially a variant of an interval scheduling algorithm.
  100. //
  101. // If we had types to differentiate between regular Allocations and AggregatedAllocations
  102. // then this type would be unnecessary and its fields would go into the regular Allocation
  103. // and not in the AggregatedAllocation.
  104. type RawAllocationOnlyData struct {
  105. CPUCoreUsageMax float64 `json:"cpuCoreUsageMax"`
  106. RAMBytesUsageMax float64 `json:"ramByteUsageMax"`
  107. }
  108. // Clone returns a deep copy of the given RawAllocationOnlyData
  109. func (r *RawAllocationOnlyData) Clone() *RawAllocationOnlyData {
  110. if r == nil {
  111. return nil
  112. }
  113. return &RawAllocationOnlyData{
  114. CPUCoreUsageMax: r.CPUCoreUsageMax,
  115. RAMBytesUsageMax: r.RAMBytesUsageMax,
  116. }
  117. }
  118. // Equal returns true if the RawAllocationOnlyData is approximately equal
  119. func (r *RawAllocationOnlyData) Equal(that *RawAllocationOnlyData) bool {
  120. if r == nil && that == nil {
  121. return true
  122. }
  123. if r == nil || that == nil {
  124. return false
  125. }
  126. return util.IsApproximately(r.CPUCoreUsageMax, that.CPUCoreUsageMax) &&
  127. util.IsApproximately(r.RAMBytesUsageMax, that.RAMBytesUsageMax)
  128. }
  129. // PVAllocations is a map of Disk Asset Identifiers to the
  130. // usage of them by an Allocation as recorded in a PVAllocation
  131. type PVAllocations map[PVKey]*PVAllocation
  132. // Clone creates a deep copy of a PVAllocations
  133. func (pv PVAllocations) Clone() PVAllocations {
  134. if pv == nil {
  135. return nil
  136. }
  137. clonePV := make(map[PVKey]*PVAllocation, len(pv))
  138. for k, v := range pv {
  139. clonePV[k] = &PVAllocation{
  140. ByteHours: v.ByteHours,
  141. Cost: v.Cost,
  142. }
  143. }
  144. return clonePV
  145. }
  146. // Add adds contents of that to the calling PVAllocations
  147. func (pv PVAllocations) Add(that PVAllocations) PVAllocations {
  148. apv := pv.Clone()
  149. if that != nil {
  150. if apv == nil {
  151. apv = PVAllocations{}
  152. }
  153. for pvKey, thatPVAlloc := range that {
  154. apvAlloc, ok := apv[pvKey]
  155. if !ok {
  156. apvAlloc = &PVAllocation{}
  157. }
  158. apvAlloc.Cost += thatPVAlloc.Cost
  159. apvAlloc.ByteHours += thatPVAlloc.ByteHours
  160. apv[pvKey] = apvAlloc
  161. }
  162. }
  163. return apv
  164. }
  165. // Equal returns true if the two PVAllocations are equal in length and contain the same keys
  166. // and values.
  167. func (this PVAllocations) Equal(that PVAllocations) bool {
  168. if this == nil && that == nil {
  169. return true
  170. }
  171. if this == nil || that == nil {
  172. return false
  173. }
  174. if len(this) != len(that) {
  175. return false
  176. }
  177. for k, pv := range this {
  178. tv, ok := that[k]
  179. if !ok || !pv.Equal(tv) {
  180. return false
  181. }
  182. }
  183. return true
  184. }
  185. // PVKey for identifying Disk type assets
  186. type PVKey struct {
  187. Cluster string `json:"cluster"`
  188. Name string `json:"name"`
  189. }
  190. func (pvk *PVKey) String() string {
  191. return fmt.Sprintf("cluster=%s:name=%s", pvk.Cluster, pvk.Name)
  192. }
  193. // FromString populates PVKey fields from string
  194. func (pvk *PVKey) FromString(key string) error {
  195. splitKey := strings.Split(key, ":")
  196. if len(splitKey) != 2 {
  197. return fmt.Errorf("PVKey string '%s' has the incorrect format", key)
  198. }
  199. pvk.Cluster = strings.TrimPrefix(splitKey[0], "cluster=")
  200. pvk.Name = strings.TrimPrefix(splitKey[1], "name=")
  201. return nil
  202. }
  203. // PVAllocation contains the byte hour usage
  204. // and cost of an Allocation for a single PV
  205. type PVAllocation struct {
  206. ByteHours float64 `json:"byteHours"`
  207. Cost float64 `json:"cost"`
  208. }
  209. // Equal returns true if the two PVAllocation instances contain approximately the same
  210. // values.
  211. func (pva *PVAllocation) Equal(that *PVAllocation) bool {
  212. if pva == nil && that == nil {
  213. return true
  214. }
  215. if pva == nil || that == nil {
  216. return false
  217. }
  218. return util.IsApproximately(pva.ByteHours, that.ByteHours) &&
  219. util.IsApproximately(pva.Cost, that.Cost)
  220. }
  221. type ProportionalAssetResourceCost struct {
  222. Cluster string `json:"cluster"`
  223. Node string `json:"node,omitempty"`
  224. ProviderID string `json:"providerID,omitempty"`
  225. CPUPercentage float64 `json:"cpuPercentage"`
  226. GPUPercentage float64 `json:"gpuPercentage"`
  227. RAMPercentage float64 `json:"ramPercentage"`
  228. NodeResourceCostPercentage float64 `json:"nodeResourceCostPercentage"`
  229. GPUTotalCost float64 `json:"-"`
  230. GPUProportionalCost float64 `json:"-"`
  231. CPUTotalCost float64 `json:"-"`
  232. CPUProportionalCost float64 `json:"-"`
  233. RAMTotalCost float64 `json:"-"`
  234. RAMProportionalCost float64 `json:"-"`
  235. }
  236. func (parc ProportionalAssetResourceCost) Key(insertByNode bool) string {
  237. if insertByNode {
  238. return parc.Cluster + "," + parc.Node
  239. } else {
  240. return parc.Cluster
  241. }
  242. }
  243. type ProportionalAssetResourceCosts map[string]ProportionalAssetResourceCost
  244. func (parcs ProportionalAssetResourceCosts) Clone() ProportionalAssetResourceCosts {
  245. cloned := ProportionalAssetResourceCosts{}
  246. for key, parc := range parcs {
  247. cloned[key] = parc
  248. }
  249. return cloned
  250. }
  251. func (parcs ProportionalAssetResourceCosts) Insert(parc ProportionalAssetResourceCost, insertByNode bool) {
  252. if !insertByNode {
  253. parc.Node = ""
  254. parc.ProviderID = ""
  255. }
  256. if curr, ok := parcs[parc.Key(insertByNode)]; ok {
  257. toInsert := ProportionalAssetResourceCost{
  258. Node: curr.Node,
  259. Cluster: curr.Cluster,
  260. ProviderID: curr.ProviderID,
  261. CPUTotalCost: curr.CPUTotalCost + parc.CPUTotalCost,
  262. CPUProportionalCost: curr.CPUProportionalCost + parc.CPUProportionalCost,
  263. RAMTotalCost: curr.RAMTotalCost + parc.RAMTotalCost,
  264. RAMProportionalCost: curr.RAMProportionalCost + parc.RAMProportionalCost,
  265. GPUProportionalCost: curr.GPUProportionalCost + parc.GPUProportionalCost,
  266. GPUTotalCost: curr.GPUTotalCost + parc.GPUTotalCost,
  267. }
  268. computePercentages(&toInsert)
  269. parcs[parc.Key(insertByNode)] = toInsert
  270. } else {
  271. computePercentages(&parc)
  272. parcs[parc.Key(insertByNode)] = parc
  273. }
  274. }
  275. func computePercentages(toInsert *ProportionalAssetResourceCost) {
  276. // compute percentages
  277. totalCost := toInsert.RAMTotalCost + toInsert.CPUTotalCost + toInsert.GPUTotalCost
  278. if toInsert.CPUTotalCost > 0 {
  279. toInsert.CPUPercentage = toInsert.CPUProportionalCost / toInsert.CPUTotalCost
  280. }
  281. if toInsert.GPUTotalCost > 0 {
  282. toInsert.GPUPercentage = toInsert.GPUProportionalCost / toInsert.GPUTotalCost
  283. }
  284. if toInsert.RAMTotalCost > 0 {
  285. toInsert.RAMPercentage = toInsert.RAMProportionalCost / toInsert.RAMTotalCost
  286. }
  287. ramFraction := toInsert.RAMTotalCost / totalCost
  288. if ramFraction != ramFraction || ramFraction < 0 {
  289. ramFraction = 0
  290. }
  291. cpuFraction := toInsert.CPUTotalCost / totalCost
  292. if cpuFraction != cpuFraction || cpuFraction < 0 {
  293. cpuFraction = 0
  294. }
  295. gpuFraction := toInsert.GPUTotalCost / totalCost
  296. if gpuFraction != gpuFraction || gpuFraction < 0 {
  297. gpuFraction = 0
  298. }
  299. toInsert.NodeResourceCostPercentage = (toInsert.RAMPercentage * ramFraction) +
  300. (toInsert.CPUPercentage * cpuFraction) + (toInsert.GPUPercentage * gpuFraction)
  301. }
  302. func (parcs ProportionalAssetResourceCosts) Add(that ProportionalAssetResourceCosts) {
  303. for _, parc := range that {
  304. // if node field is empty, we know this is a cluster level PARC aggregation
  305. insertByNode := true
  306. if parc.Node == "" {
  307. insertByNode = false
  308. }
  309. parcs.Insert(parc, insertByNode)
  310. }
  311. }
  312. type SharedCostBreakdown struct {
  313. Name string `json:"name"`
  314. TotalCost float64 `json:"totalCost"`
  315. CPUCost float64 `json:"cpuCost,omitempty"`
  316. GPUCost float64 `json:"gpuCost,omitempty"`
  317. RAMCost float64 `json:"ramCost,omitempty"`
  318. PVCost float64 `json:"pvCost,omitempty"`
  319. NetworkCost float64 `json:"networkCost,omitempty"`
  320. LBCost float64 `json:"loadBalancerCost,omitempty"`
  321. ExternalCost float64 `json:"externalCost,omitempty"`
  322. }
  323. type SharedCostBreakdowns map[string]SharedCostBreakdown
  324. func (scbs SharedCostBreakdowns) Clone() SharedCostBreakdowns {
  325. cloned := SharedCostBreakdowns{}
  326. for key, scb := range scbs {
  327. cloned[key] = scb
  328. }
  329. return cloned
  330. }
  331. func (scbs SharedCostBreakdowns) Insert(scb SharedCostBreakdown) {
  332. if curr, ok := scbs[scb.Name]; ok {
  333. scbs[scb.Name] = SharedCostBreakdown{
  334. Name: curr.Name,
  335. TotalCost: curr.TotalCost + scb.TotalCost,
  336. CPUCost: curr.CPUCost + scb.CPUCost,
  337. GPUCost: curr.GPUCost + scb.GPUCost,
  338. RAMCost: curr.RAMCost + scb.RAMCost,
  339. PVCost: curr.PVCost + scb.PVCost,
  340. NetworkCost: curr.NetworkCost + scb.NetworkCost,
  341. LBCost: curr.LBCost + scb.LBCost,
  342. ExternalCost: curr.ExternalCost + scb.ExternalCost,
  343. }
  344. } else {
  345. scbs[scb.Name] = scb
  346. }
  347. }
  348. func (scbs SharedCostBreakdowns) Add(that SharedCostBreakdowns) {
  349. for _, scb := range that {
  350. scbs.Insert(scb)
  351. }
  352. }
  353. // GetWindow returns the window of the struct
  354. func (a *Allocation) GetWindow() Window {
  355. return a.Window
  356. }
  357. // AllocationMatchFunc is a function that can be used to match Allocations by
  358. // returning true for any given Allocation if a condition is met.
  359. type AllocationMatchFunc func(*Allocation) bool
  360. // Add returns the result of summing the two given Allocations, which sums the
  361. // summary fields (e.g. costs, resources) and recomputes efficiency. Neither of
  362. // the two original Allocations are mutated in the process.
  363. func (a *Allocation) Add(that *Allocation) (*Allocation, error) {
  364. if a == nil {
  365. return that.Clone(), nil
  366. }
  367. if that == nil {
  368. return a.Clone(), nil
  369. }
  370. // Note: no need to clone "that", as add only mutates the receiver
  371. agg := a.Clone()
  372. agg.add(that)
  373. return agg, nil
  374. }
  375. // Clone returns a deep copy of the given Allocation
  376. func (a *Allocation) Clone() *Allocation {
  377. if a == nil {
  378. return nil
  379. }
  380. return &Allocation{
  381. Name: a.Name,
  382. Properties: a.Properties.Clone(),
  383. Window: a.Window.Clone(),
  384. Start: a.Start,
  385. End: a.End,
  386. CPUCoreHours: a.CPUCoreHours,
  387. CPUCoreRequestAverage: a.CPUCoreRequestAverage,
  388. CPUCoreUsageAverage: a.CPUCoreUsageAverage,
  389. CPUCost: a.CPUCost,
  390. CPUCostAdjustment: a.CPUCostAdjustment,
  391. GPUHours: a.GPUHours,
  392. GPUCost: a.GPUCost,
  393. GPUCostAdjustment: a.GPUCostAdjustment,
  394. NetworkTransferBytes: a.NetworkTransferBytes,
  395. NetworkReceiveBytes: a.NetworkReceiveBytes,
  396. NetworkCost: a.NetworkCost,
  397. NetworkCrossZoneCost: a.NetworkCrossZoneCost,
  398. NetworkCrossRegionCost: a.NetworkCrossRegionCost,
  399. NetworkInternetCost: a.NetworkInternetCost,
  400. NetworkCostAdjustment: a.NetworkCostAdjustment,
  401. LoadBalancerCost: a.LoadBalancerCost,
  402. LoadBalancerCostAdjustment: a.LoadBalancerCostAdjustment,
  403. PVs: a.PVs.Clone(),
  404. PVCostAdjustment: a.PVCostAdjustment,
  405. RAMByteHours: a.RAMByteHours,
  406. RAMBytesRequestAverage: a.RAMBytesRequestAverage,
  407. RAMBytesUsageAverage: a.RAMBytesUsageAverage,
  408. RAMCost: a.RAMCost,
  409. RAMCostAdjustment: a.RAMCostAdjustment,
  410. SharedCost: a.SharedCost,
  411. ExternalCost: a.ExternalCost,
  412. RawAllocationOnly: a.RawAllocationOnly.Clone(),
  413. ProportionalAssetResourceCosts: a.ProportionalAssetResourceCosts.Clone(),
  414. SharedCostBreakdown: a.SharedCostBreakdown.Clone(),
  415. }
  416. }
  417. // Equal returns true if the values held in the given Allocation precisely
  418. // match those of the receiving Allocation. nil does not match nil. Floating
  419. // point values need to match according to util.IsApproximately, which accounts
  420. // for small, reasonable floating point error margins.
  421. func (a *Allocation) Equal(that *Allocation) bool {
  422. if a == nil || that == nil {
  423. return false
  424. }
  425. if a.Name != that.Name {
  426. return false
  427. }
  428. if !a.Properties.Equal(that.Properties) {
  429. return false
  430. }
  431. if !a.Window.Equal(that.Window) {
  432. return false
  433. }
  434. if !a.Start.Equal(that.Start) {
  435. return false
  436. }
  437. if !a.End.Equal(that.End) {
  438. return false
  439. }
  440. if !util.IsApproximately(a.CPUCoreHours, that.CPUCoreHours) {
  441. return false
  442. }
  443. if !util.IsApproximately(a.CPUCost, that.CPUCost) {
  444. return false
  445. }
  446. if !util.IsApproximately(a.CPUCostAdjustment, that.CPUCostAdjustment) {
  447. return false
  448. }
  449. if !util.IsApproximately(a.GPUHours, that.GPUHours) {
  450. return false
  451. }
  452. if !util.IsApproximately(a.GPUCost, that.GPUCost) {
  453. return false
  454. }
  455. if !util.IsApproximately(a.GPUCostAdjustment, that.GPUCostAdjustment) {
  456. return false
  457. }
  458. if !util.IsApproximately(a.NetworkTransferBytes, that.NetworkTransferBytes) {
  459. return false
  460. }
  461. if !util.IsApproximately(a.NetworkReceiveBytes, that.NetworkReceiveBytes) {
  462. return false
  463. }
  464. if !util.IsApproximately(a.NetworkCost, that.NetworkCost) {
  465. return false
  466. }
  467. if !util.IsApproximately(a.NetworkCrossZoneCost, that.NetworkCrossZoneCost) {
  468. return false
  469. }
  470. if !util.IsApproximately(a.NetworkCrossRegionCost, that.NetworkCrossRegionCost) {
  471. return false
  472. }
  473. if !util.IsApproximately(a.NetworkInternetCost, that.NetworkInternetCost) {
  474. return false
  475. }
  476. if !util.IsApproximately(a.NetworkCostAdjustment, that.NetworkCostAdjustment) {
  477. return false
  478. }
  479. if !util.IsApproximately(a.LoadBalancerCost, that.LoadBalancerCost) {
  480. return false
  481. }
  482. if !util.IsApproximately(a.LoadBalancerCostAdjustment, that.LoadBalancerCostAdjustment) {
  483. return false
  484. }
  485. if !util.IsApproximately(a.PVCostAdjustment, that.PVCostAdjustment) {
  486. return false
  487. }
  488. if !util.IsApproximately(a.RAMByteHours, that.RAMByteHours) {
  489. return false
  490. }
  491. if !util.IsApproximately(a.RAMCost, that.RAMCost) {
  492. return false
  493. }
  494. if !util.IsApproximately(a.RAMCostAdjustment, that.RAMCostAdjustment) {
  495. return false
  496. }
  497. if !util.IsApproximately(a.SharedCost, that.SharedCost) {
  498. return false
  499. }
  500. if !util.IsApproximately(a.ExternalCost, that.ExternalCost) {
  501. return false
  502. }
  503. if !a.RawAllocationOnly.Equal(that.RawAllocationOnly) {
  504. return false
  505. }
  506. if !a.PVs.Equal(that.PVs) {
  507. return false
  508. }
  509. return true
  510. }
  511. // TotalCost is the total cost of the Allocation including adjustments
  512. func (a *Allocation) TotalCost() float64 {
  513. if a == nil {
  514. return 0.0
  515. }
  516. return a.CPUTotalCost() + a.GPUTotalCost() + a.RAMTotalCost() + a.PVTotalCost() + a.NetworkTotalCost() + a.LBTotalCost() + a.SharedTotalCost() + a.ExternalCost
  517. }
  518. // CPUTotalCost calculates total CPU cost of Allocation including adjustment
  519. func (a *Allocation) CPUTotalCost() float64 {
  520. if a == nil {
  521. return 0.0
  522. }
  523. return a.CPUCost + a.CPUCostAdjustment
  524. }
  525. // GPUTotalCost calculates total GPU cost of Allocation including adjustment
  526. func (a *Allocation) GPUTotalCost() float64 {
  527. if a == nil {
  528. return 0.0
  529. }
  530. return a.GPUCost + a.GPUCostAdjustment
  531. }
  532. // RAMTotalCost calculates total RAM cost of Allocation including adjustment
  533. func (a *Allocation) RAMTotalCost() float64 {
  534. if a == nil {
  535. return 0.0
  536. }
  537. return a.RAMCost + a.RAMCostAdjustment
  538. }
  539. // PVTotalCost calculates total PV cost of Allocation including adjustment
  540. func (a *Allocation) PVTotalCost() float64 {
  541. if a == nil {
  542. return 0.0
  543. }
  544. return a.PVCost() + a.PVCostAdjustment
  545. }
  546. // NetworkTotalCost calculates total Network cost of Allocation including adjustment
  547. func (a *Allocation) NetworkTotalCost() float64 {
  548. if a == nil {
  549. return 0.0
  550. }
  551. return a.NetworkCost + a.NetworkCostAdjustment
  552. }
  553. // LBTotalCost calculates total LB cost of Allocation including adjustment
  554. // TODO deprecate
  555. func (a *Allocation) LBTotalCost() float64 {
  556. return a.LoadBalancerTotalCost()
  557. }
  558. // LoadBalancerTotalCost calculates total LB cost of Allocation including adjustment
  559. func (a *Allocation) LoadBalancerTotalCost() float64 {
  560. if a == nil {
  561. return 0.0
  562. }
  563. return a.LoadBalancerCost + a.LoadBalancerCostAdjustment
  564. }
  565. // SharedTotalCost calculates total shared cost of Allocation including adjustment
  566. func (a *Allocation) SharedTotalCost() float64 {
  567. if a == nil {
  568. return 0.0
  569. }
  570. return a.SharedCost
  571. }
  572. // PVCost calculate cumulative cost of all PVs that Allocation is attached to
  573. func (a *Allocation) PVCost() float64 {
  574. if a == nil {
  575. return 0.0
  576. }
  577. cost := 0.0
  578. for _, pv := range a.PVs {
  579. cost += pv.Cost
  580. }
  581. return cost
  582. }
  583. // PVByteHours calculate cumulative ByteHours of all PVs that Allocation is attached to
  584. func (a *Allocation) PVByteHours() float64 {
  585. if a == nil {
  586. return 0.0
  587. }
  588. byteHours := 0.0
  589. for _, pv := range a.PVs {
  590. byteHours += pv.ByteHours
  591. }
  592. return byteHours
  593. }
  594. // CPUEfficiency is the ratio of usage to request. If there is no request and
  595. // no usage or cost, then efficiency is zero. If there is no request, but there
  596. // is usage or cost, then efficiency is 100%.
  597. func (a *Allocation) CPUEfficiency() float64 {
  598. if a == nil {
  599. return 0.0
  600. }
  601. if a.CPUCoreRequestAverage > 0 {
  602. return a.CPUCoreUsageAverage / a.CPUCoreRequestAverage
  603. }
  604. if a.CPUCoreUsageAverage == 0.0 || a.CPUCost == 0.0 {
  605. return 0.0
  606. }
  607. return 1.0
  608. }
  609. // RAMEfficiency is the ratio of usage to request. If there is no request and
  610. // no usage or cost, then efficiency is zero. If there is no request, but there
  611. // is usage or cost, then efficiency is 100%.
  612. func (a *Allocation) RAMEfficiency() float64 {
  613. if a == nil {
  614. return 0.0
  615. }
  616. if a.RAMBytesRequestAverage > 0 {
  617. return a.RAMBytesUsageAverage / a.RAMBytesRequestAverage
  618. }
  619. if a.RAMBytesUsageAverage == 0.0 || a.RAMCost == 0.0 {
  620. return 0.0
  621. }
  622. return 1.0
  623. }
  624. // TotalEfficiency is the cost-weighted average of CPU and RAM efficiency. If
  625. // there is no cost at all, then efficiency is zero.
  626. func (a *Allocation) TotalEfficiency() float64 {
  627. if a == nil {
  628. return 0.0
  629. }
  630. if a.RAMTotalCost()+a.CPUTotalCost() > 0 {
  631. ramCostEff := a.RAMEfficiency() * a.RAMTotalCost()
  632. cpuCostEff := a.CPUEfficiency() * a.CPUTotalCost()
  633. return (ramCostEff + cpuCostEff) / (a.CPUTotalCost() + a.RAMTotalCost())
  634. }
  635. return 0.0
  636. }
  637. // CPUCores converts the Allocation's CPUCoreHours into average CPUCores
  638. func (a *Allocation) CPUCores() float64 {
  639. if a.Minutes() <= 0.0 {
  640. return 0.0
  641. }
  642. return a.CPUCoreHours / (a.Minutes() / 60.0)
  643. }
  644. // RAMBytes converts the Allocation's RAMByteHours into average RAMBytes
  645. func (a *Allocation) RAMBytes() float64 {
  646. if a.Minutes() <= 0.0 {
  647. return 0.0
  648. }
  649. return a.RAMByteHours / (a.Minutes() / 60.0)
  650. }
  651. // GPUs converts the Allocation's GPUHours into average GPUs
  652. func (a *Allocation) GPUs() float64 {
  653. if a.Minutes() <= 0.0 {
  654. return 0.0
  655. }
  656. return a.GPUHours / (a.Minutes() / 60.0)
  657. }
  658. // PVBytes converts the Allocation's PVByteHours into average PVBytes
  659. func (a *Allocation) PVBytes() float64 {
  660. if a.Minutes() <= 0.0 {
  661. return 0.0
  662. }
  663. return a.PVByteHours() / (a.Minutes() / 60.0)
  664. }
  665. // ResetAdjustments sets all cost adjustment fields to zero
  666. func (a *Allocation) ResetAdjustments() {
  667. if a == nil {
  668. return
  669. }
  670. a.CPUCostAdjustment = 0.0
  671. a.GPUCostAdjustment = 0.0
  672. a.RAMCostAdjustment = 0.0
  673. a.PVCostAdjustment = 0.0
  674. a.NetworkCostAdjustment = 0.0
  675. a.LoadBalancerCostAdjustment = 0.0
  676. }
  677. // Resolution returns the duration of time covered by the Allocation
  678. func (a *Allocation) Resolution() time.Duration {
  679. return a.End.Sub(a.Start)
  680. }
  681. // IsAggregated is true if the given Allocation has been aggregated, which we
  682. // define by a lack of AllocationProperties.
  683. func (a *Allocation) IsAggregated() bool {
  684. return a == nil || a.Properties == nil
  685. }
  686. // IsExternal is true if the given Allocation represents external costs.
  687. func (a *Allocation) IsExternal() bool {
  688. if a == nil {
  689. return false
  690. }
  691. return strings.Contains(a.Name, ExternalSuffix)
  692. }
  693. // IsIdle is true if the given Allocation represents idle costs.
  694. func (a *Allocation) IsIdle() bool {
  695. if a == nil {
  696. return false
  697. }
  698. return strings.Contains(a.Name, IdleSuffix)
  699. }
  700. // IsUnallocated is true if the given Allocation represents unallocated costs.
  701. func (a *Allocation) IsUnallocated() bool {
  702. if a == nil {
  703. return false
  704. }
  705. return strings.Contains(a.Name, UnallocatedSuffix)
  706. }
  707. // IsUnmounted is true if the given Allocation represents unmounted volume costs.
  708. func (a *Allocation) IsUnmounted() bool {
  709. if a == nil {
  710. return false
  711. }
  712. return strings.Contains(a.Name, UnmountedSuffix)
  713. }
  714. // Minutes returns the number of minutes the Allocation represents, as defined
  715. // by the difference between the end and start times.
  716. func (a *Allocation) Minutes() float64 {
  717. if a == nil {
  718. return 0.0
  719. }
  720. return a.End.Sub(a.Start).Minutes()
  721. }
  722. // Share adds the TotalCost of the given Allocation to the SharedCost of the
  723. // receiving Allocation. No Start, End, Window, or AllocationProperties are considered.
  724. // Neither Allocation is mutated; a new Allocation is always returned.
  725. func (a *Allocation) Share(that *Allocation) (*Allocation, error) {
  726. if that == nil {
  727. return a.Clone(), nil
  728. }
  729. if a == nil {
  730. return nil, fmt.Errorf("cannot share with nil Allocation")
  731. }
  732. agg := a.Clone()
  733. agg.SharedCost += that.TotalCost()
  734. return agg, nil
  735. }
  736. // String represents the given Allocation as a string
  737. func (a *Allocation) String() string {
  738. if a == nil {
  739. return "<nil>"
  740. }
  741. return fmt.Sprintf("%s%s=%.2f", a.Name, NewWindow(&a.Start, &a.End), a.TotalCost())
  742. }
  743. func (a *Allocation) add(that *Allocation) {
  744. if a == nil {
  745. log.Warnf("Allocation.AggregateBy: trying to add a nil receiver")
  746. return
  747. }
  748. // Generate keys for each allocation to allow for special logic to set the controller
  749. // in the case of keys matching but controllers not matching.
  750. aggByForKey := []string{"cluster", "node", "namespace", "pod", "container"}
  751. leftKey := a.generateKey(aggByForKey, nil)
  752. rightKey := that.generateKey(aggByForKey, nil)
  753. leftProperties := a.Properties
  754. rightProperties := that.Properties
  755. // Preserve string properties that are matching between the two allocations
  756. a.Properties = a.Properties.Intersection(that.Properties)
  757. // If both Allocations have ProportionalAssetResourceCosts, then
  758. // add those from the given Allocation into the receiver.
  759. if a.ProportionalAssetResourceCosts != nil || that.ProportionalAssetResourceCosts != nil {
  760. // init empty PARCs if either operand has nil PARCs
  761. if a.ProportionalAssetResourceCosts == nil {
  762. a.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  763. }
  764. if that.ProportionalAssetResourceCosts == nil {
  765. that.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  766. }
  767. a.ProportionalAssetResourceCosts.Add(that.ProportionalAssetResourceCosts)
  768. }
  769. // If both Allocations have SharedCostBreakdowns, then
  770. // add those from the given Allocation into the receiver.
  771. if a.SharedCostBreakdown != nil || that.SharedCostBreakdown != nil {
  772. if a.SharedCostBreakdown == nil {
  773. a.SharedCostBreakdown = SharedCostBreakdowns{}
  774. }
  775. if that.SharedCostBreakdown == nil {
  776. that.SharedCostBreakdown = SharedCostBreakdowns{}
  777. }
  778. a.SharedCostBreakdown.Add(that.SharedCostBreakdown)
  779. }
  780. // Overwrite regular intersection logic for the controller name property in the
  781. // case that the Allocation keys are the same but the controllers are not.
  782. if leftKey == rightKey &&
  783. leftProperties != nil &&
  784. rightProperties != nil &&
  785. leftProperties.Controller != rightProperties.Controller {
  786. if leftProperties.Controller == "" {
  787. a.Properties.Controller = rightProperties.Controller
  788. } else if rightProperties.Controller == "" {
  789. a.Properties.Controller = leftProperties.Controller
  790. } else {
  791. controllers := []string{
  792. leftProperties.Controller,
  793. rightProperties.Controller,
  794. }
  795. sort.Strings(controllers)
  796. a.Properties.Controller = controllers[0]
  797. }
  798. }
  799. // Expand the window to encompass both Allocations
  800. a.Window = a.Window.Expand(that.Window)
  801. // Sum non-cumulative fields by turning them into cumulative, adding them,
  802. // and then converting them back into averages after minutes have been
  803. // combined (just below).
  804. cpuReqCoreMins := a.CPUCoreRequestAverage * a.Minutes()
  805. cpuReqCoreMins += that.CPUCoreRequestAverage * that.Minutes()
  806. cpuUseCoreMins := a.CPUCoreUsageAverage * a.Minutes()
  807. cpuUseCoreMins += that.CPUCoreUsageAverage * that.Minutes()
  808. ramReqByteMins := a.RAMBytesRequestAverage * a.Minutes()
  809. ramReqByteMins += that.RAMBytesRequestAverage * that.Minutes()
  810. ramUseByteMins := a.RAMBytesUsageAverage * a.Minutes()
  811. ramUseByteMins += that.RAMBytesUsageAverage * that.Minutes()
  812. // Expand Start and End to be the "max" of among the given Allocations
  813. if that.Start.Before(a.Start) {
  814. a.Start = that.Start
  815. }
  816. if that.End.After(a.End) {
  817. a.End = that.End
  818. }
  819. // Convert cumulative request and usage back into rates
  820. // TODO:TEST write a unit test that fails if this is done incorrectly
  821. if a.Minutes() > 0 {
  822. a.CPUCoreRequestAverage = cpuReqCoreMins / a.Minutes()
  823. a.CPUCoreUsageAverage = cpuUseCoreMins / a.Minutes()
  824. a.RAMBytesRequestAverage = ramReqByteMins / a.Minutes()
  825. a.RAMBytesUsageAverage = ramUseByteMins / a.Minutes()
  826. } else {
  827. a.CPUCoreRequestAverage = 0.0
  828. a.CPUCoreUsageAverage = 0.0
  829. a.RAMBytesRequestAverage = 0.0
  830. a.RAMBytesUsageAverage = 0.0
  831. }
  832. // Sum all cumulative resource fields
  833. a.CPUCoreHours += that.CPUCoreHours
  834. a.GPUHours += that.GPUHours
  835. a.RAMByteHours += that.RAMByteHours
  836. a.NetworkTransferBytes += that.NetworkTransferBytes
  837. a.NetworkReceiveBytes += that.NetworkReceiveBytes
  838. // Sum all cumulative cost fields
  839. a.CPUCost += that.CPUCost
  840. a.GPUCost += that.GPUCost
  841. a.RAMCost += that.RAMCost
  842. a.NetworkCost += that.NetworkCost
  843. a.NetworkCrossZoneCost += that.NetworkCrossZoneCost
  844. a.NetworkCrossRegionCost += that.NetworkCrossRegionCost
  845. a.NetworkInternetCost += that.NetworkInternetCost
  846. a.LoadBalancerCost += that.LoadBalancerCost
  847. a.SharedCost += that.SharedCost
  848. a.ExternalCost += that.ExternalCost
  849. // Sum PVAllocations
  850. a.PVs = a.PVs.Add(that.PVs)
  851. // Sum all cumulative adjustment fields
  852. a.CPUCostAdjustment += that.CPUCostAdjustment
  853. a.RAMCostAdjustment += that.RAMCostAdjustment
  854. a.GPUCostAdjustment += that.GPUCostAdjustment
  855. a.PVCostAdjustment += that.PVCostAdjustment
  856. a.NetworkCostAdjustment += that.NetworkCostAdjustment
  857. a.LoadBalancerCostAdjustment += that.LoadBalancerCostAdjustment
  858. // Any data that is in a "raw allocation only" is not valid in any
  859. // sort of cumulative Allocation (like one that is added).
  860. a.RawAllocationOnly = nil
  861. }
  862. // AllocationSet stores a set of Allocations, each with a unique name, that share
  863. // a window. An AllocationSet is mutable, so treat it like a threadsafe map.
  864. type AllocationSet struct {
  865. Allocations map[string]*Allocation
  866. ExternalKeys map[string]bool
  867. IdleKeys map[string]bool
  868. FromSource string // stores the name of the source used to compute the data
  869. Window Window
  870. Warnings []string
  871. Errors []string
  872. }
  873. // NewAllocationSet instantiates a new AllocationSet and, optionally, inserts
  874. // the given list of Allocations
  875. func NewAllocationSet(start, end time.Time, allocs ...*Allocation) *AllocationSet {
  876. as := &AllocationSet{
  877. Allocations: map[string]*Allocation{},
  878. ExternalKeys: map[string]bool{},
  879. IdleKeys: map[string]bool{},
  880. Window: NewWindow(&start, &end),
  881. }
  882. for _, a := range allocs {
  883. as.Insert(a)
  884. }
  885. return as
  886. }
  887. // AllocationAggregationOptions provide advanced functionality to AggregateBy, including
  888. // filtering results and sharing allocations. FilterFuncs are a list of match
  889. // functions such that, if any function fails, the allocation is ignored.
  890. // ShareFuncs are a list of match functions such that, if any function
  891. // succeeds, the allocation is marked as a shared resource. ShareIdle is a
  892. // simple flag for sharing idle resources.
  893. type AllocationAggregationOptions struct {
  894. AllocationTotalsStore AllocationTotalsStore
  895. Filter AllocationFilter
  896. IdleByNode bool
  897. IncludeProportionalAssetResourceCosts bool
  898. LabelConfig *LabelConfig
  899. MergeUnallocated bool
  900. Reconcile bool
  901. ReconcileNetwork bool
  902. ShareFuncs []AllocationMatchFunc
  903. SharedNamespaces []string
  904. SharedLabels map[string][]string
  905. ShareIdle string
  906. ShareSplit string
  907. SharedHourlyCosts map[string]float64
  908. IncludeSharedCostBreakdown bool
  909. SplitIdle bool
  910. IncludeAggregatedMetadata bool
  911. }
  912. // AggregateBy aggregates the Allocations in the given AllocationSet by the given
  913. // AllocationProperty. This will only be legal if the AllocationSet is divisible by the
  914. // given AllocationProperty; e.g. Containers can be divided by Namespace, but not vice-a-versa.
  915. func (as *AllocationSet) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  916. // The order of operations for aggregating allocations is as follows:
  917. //
  918. // 1. Partition external, idle, and shared allocations into separate sets.
  919. // Also, create the aggSet into which the results will be aggregated.
  920. //
  921. // 2. Compute sharing coefficients for idle and shared resources
  922. // a) if idle allocation is to be shared, or if proportional asset
  923. // resource costs are to be included, then compute idle coefficients
  924. // (proportional asset resource costs are derived from idle coefficients)
  925. // b) if proportional asset costs are to be included, derive them from
  926. // idle coefficients and add them to the allocations.
  927. // c) if idle allocation is NOT shared, but filters are present, compute
  928. // idle filtration coefficients for the purpose of only returning the
  929. // portion of idle allocation that would have been shared with the
  930. // unfiltered results. (See unit tests 5.a,b,c)
  931. // d) generate shared allocation for them given shared overhead, which
  932. // must happen after (2a) and (2b)
  933. // e) if there are shared resources, compute share coefficients
  934. //
  935. // 3. Drop any allocation that fails any of the filters
  936. //
  937. // 4. Distribute idle allocations according to the idle coefficients
  938. //
  939. // 5. Generate aggregation key and insert allocation into the output set
  940. //
  941. // 6. If idle is shared and resources are shared, some idle might be shared
  942. // with a shared resource. Distribute that to the shared resources
  943. // prior to sharing them with the aggregated results.
  944. //
  945. // 7. Apply idle filtration coefficients from step (2b)
  946. //
  947. // 8. Distribute shared allocations according to the share coefficients.
  948. //
  949. // 9. If there are external allocations that can be aggregated into
  950. // the output (i.e. they can be used to generate a valid key for
  951. // the given properties) then aggregate; otherwise... ignore them?
  952. //
  953. // 10. Distribute any undistributed idle, in the case that idle
  954. // coefficients end up being zero and some idle is not shared.
  955. //
  956. // 11. If the merge idle option is enabled, merge any remaining idle
  957. // allocations into a single idle allocation. If there was any idle
  958. // whose costs were not distributed because there was no usage of a
  959. // specific resource type, re-add the idle to the aggregation with
  960. // only that type.
  961. if as.IsEmpty() {
  962. return nil
  963. }
  964. if options == nil {
  965. options = &AllocationAggregationOptions{}
  966. }
  967. if options.LabelConfig == nil {
  968. options.LabelConfig = NewLabelConfig()
  969. }
  970. // idleFiltrationCoefficients relies on this being explicitly set
  971. if options.ShareIdle != ShareWeighted {
  972. options.ShareIdle = ShareNone
  973. }
  974. // Pre-flatten the filter so we can just check == nil to see if there are
  975. // filters.
  976. if options.Filter != nil {
  977. options.Filter = options.Filter.Flattened()
  978. }
  979. var allocatedTotalsMap map[string]map[string]float64
  980. // If aggregateBy is nil, we don't aggregate anything. On the other hand,
  981. // an empty slice implies that we should aggregate everything. See
  982. // generateKey for why that makes sense.
  983. shouldAggregate := aggregateBy != nil
  984. shouldFilter := options.Filter != nil
  985. shouldShare := len(options.SharedHourlyCosts) > 0 || len(options.ShareFuncs) > 0
  986. if !shouldAggregate && !shouldFilter && !shouldShare && options.ShareIdle == ShareNone && !options.IncludeProportionalAssetResourceCosts {
  987. // There is nothing for AggregateBy to do, so simply return nil
  988. return nil
  989. }
  990. // aggSet will collect the aggregated allocations
  991. aggSet := &AllocationSet{
  992. Window: as.Window.Clone(),
  993. }
  994. // externalSet will collect external allocations
  995. externalSet := &AllocationSet{
  996. Window: as.Window.Clone(),
  997. }
  998. // idleSet will be shared among aggSet after initial aggregation
  999. // is complete
  1000. idleSet := &AllocationSet{
  1001. Window: as.Window.Clone(),
  1002. }
  1003. // parcSet is used to compute proportionalAssetResourceCosts
  1004. // for surfacing in the API
  1005. parcSet := &AllocationSet{
  1006. Window: as.Window.Clone(),
  1007. }
  1008. // shareSet will be shared among aggSet after initial aggregation
  1009. // is complete
  1010. shareSet := &AllocationSet{
  1011. Window: as.Window.Clone(),
  1012. }
  1013. // (1) Loop and find all of the external, idle, and shared allocations. Add
  1014. // them to their respective sets, removing them from the set of allocations
  1015. // to aggregate.
  1016. for _, alloc := range as.Allocations {
  1017. // if the user does not want any aggregated labels/annotations returned
  1018. // set the properties accordingly
  1019. alloc.Properties.AggregatedMetadata = options.IncludeAggregatedMetadata
  1020. // External allocations get aggregated post-hoc (see step 6) and do
  1021. // not necessarily contain complete sets of properties, so they are
  1022. // moved to a separate AllocationSet.
  1023. if alloc.IsExternal() {
  1024. delete(as.ExternalKeys, alloc.Name)
  1025. delete(as.Allocations, alloc.Name)
  1026. externalSet.Insert(alloc)
  1027. continue
  1028. }
  1029. // Idle allocations should be separated into idleSet if they are to be
  1030. // shared later on. If they are not to be shared, then add them to the
  1031. // aggSet like any other allocation.
  1032. if alloc.IsIdle() {
  1033. delete(as.IdleKeys, alloc.Name)
  1034. delete(as.Allocations, alloc.Name)
  1035. if options.ShareIdle == ShareEven || options.ShareIdle == ShareWeighted {
  1036. idleSet.Insert(alloc)
  1037. } else {
  1038. aggSet.Insert(alloc)
  1039. }
  1040. // build a parallel set of allocations to only be used
  1041. // for computing PARCs
  1042. if options.IncludeProportionalAssetResourceCosts {
  1043. parcSet.Insert(alloc.Clone())
  1044. }
  1045. continue
  1046. }
  1047. // Shared allocations must be identified and separated prior to
  1048. // aggregation and filtering. That is, if any of the ShareFuncs return
  1049. // true for the allocation, then move it to shareSet.
  1050. for _, sf := range options.ShareFuncs {
  1051. if sf(alloc) {
  1052. delete(as.IdleKeys, alloc.Name)
  1053. delete(as.Allocations, alloc.Name)
  1054. shareSet.Insert(alloc)
  1055. break
  1056. }
  1057. }
  1058. }
  1059. // It's possible that no more un-shared, non-idle, non-external allocations
  1060. // remain at this point. This always results in an emptySet, so return early.
  1061. if len(as.Allocations) == 0 {
  1062. emptySet := &AllocationSet{
  1063. Window: as.Window.Clone(),
  1064. }
  1065. as.Allocations = emptySet.Allocations
  1066. return nil
  1067. }
  1068. // (2) In order to correctly share idle and shared costs, we first compute
  1069. // sharing coefficients, which represent the proportion of each cost to
  1070. // share with each allocation. Idle allocations are shared per-cluster or per-node,
  1071. // per-allocation, and per-resource, while shared resources are shared per-
  1072. // allocation only.
  1073. //
  1074. // For an idleCoefficient example, the entries:
  1075. // [cluster1][cluster1/namespace1/pod1/container1][cpu] = 0.166667
  1076. // [cluster1][cluster1/namespace1/pod1/container1][gpu] = 0.166667
  1077. // [cluster1][cluster1/namespace1/pod1/container1][ram] = 0.687500
  1078. // mean that the allocation "cluster1/namespace1/pod1/container1" will
  1079. // receive 16.67% of cluster1's idle CPU and GPU costs and 68.75% of its
  1080. // RAM costs.
  1081. //
  1082. // For a shareCoefficient example, the entries:
  1083. // [namespace2] = 0.666667
  1084. // [__filtered__] = 0.333333
  1085. // mean that the post-aggregation allocation "namespace2" will receive
  1086. // 66.67% of the shared resource costs, while the remaining 33.33% will
  1087. // be filtered out, as they were shared with allocations that did not pass
  1088. // one of the given filters.
  1089. //
  1090. // In order to maintain stable results when multiple operations are being
  1091. // carried out (e.g. sharing idle, sharing resources, and filtering) these
  1092. // coefficients are computed for the full set of allocations prior to
  1093. // adding shared overhead and prior to applying filters.
  1094. var err error
  1095. // (2a) If there are idle costs to be shared, compute the coefficients for
  1096. // sharing them among the non-idle, non-aggregated allocations (including
  1097. // the shared allocations).
  1098. var idleCoefficients map[string]map[string]map[string]float64
  1099. if idleSet.Length() > 0 && options.ShareIdle != ShareNone {
  1100. idleCoefficients, allocatedTotalsMap, err = computeIdleCoeffs(options, as, shareSet)
  1101. if err != nil {
  1102. log.Warnf("AllocationSet.AggregateBy: compute idle coeff: %s", err)
  1103. return fmt.Errorf("error computing idle coefficients: %s", err)
  1104. }
  1105. }
  1106. // (2b) If proportional asset resource costs are to be included, compute them
  1107. // and add them to the allocations.
  1108. if options.IncludeProportionalAssetResourceCosts {
  1109. err := deriveProportionalAssetResourceCosts(options, as, shareSet)
  1110. if err != nil {
  1111. log.Debugf("AggregateBy: failed to derive proportional asset resource costs from idle coefficients: %s", err)
  1112. return fmt.Errorf("AggregateBy: failed to derive proportional asset resource costs from idle coefficients: %s", err)
  1113. }
  1114. }
  1115. // (2c) If idle costs are not to be shared, but there are filters, then we
  1116. // need to track the amount of each idle allocation to "filter" in order to
  1117. // maintain parity with the results when idle is shared. That is, we want
  1118. // to return only the idle costs that would have been shared with the given
  1119. // results, even if the filter had not been applied.
  1120. //
  1121. // For example, consider these results from aggregating by namespace with
  1122. // two clusters:
  1123. //
  1124. // namespace1: 25.00
  1125. // namespace2: 30.00
  1126. // namespace3: 15.00
  1127. // idle: 30.00
  1128. //
  1129. // When we then filter by cluster==cluster1, namespaces 2 and 3 are
  1130. // reduced by the amount that existed on cluster2. Then, idle must also be
  1131. // reduced by the relevant amount:
  1132. //
  1133. // namespace1: 25.00
  1134. // namespace2: 15.00
  1135. // idle: 20.00
  1136. //
  1137. // Note that this can happen for any field, not just cluster, so we again
  1138. // need to track this on a per-cluster or per-node, per-allocation, per-resource basis.
  1139. var idleFiltrationCoefficients map[string]map[string]map[string]float64
  1140. if shouldFilter && options.ShareIdle == ShareNone {
  1141. idleFiltrationCoefficients, _, err = computeIdleCoeffs(options, as, shareSet)
  1142. if err != nil {
  1143. return fmt.Errorf("error computing idle filtration coefficients: %s", err)
  1144. }
  1145. }
  1146. // (2d) Convert SharedHourlyCosts to Allocations in the shareSet. This must
  1147. // come after idle coefficients are computed so that allocations generated
  1148. // by shared overhead do not skew the idle coefficient computation.
  1149. for name, cost := range options.SharedHourlyCosts {
  1150. if cost > 0.0 {
  1151. hours := as.Resolution().Hours()
  1152. // If set ends in the future, adjust hours accordingly
  1153. diff := time.Since(as.End())
  1154. if diff < 0.0 {
  1155. hours += diff.Hours()
  1156. }
  1157. totalSharedCost := cost * hours
  1158. shareSet.Insert(&Allocation{
  1159. Name: fmt.Sprintf("%s/%s", name, SharedSuffix),
  1160. Start: as.Start(),
  1161. End: as.End(),
  1162. SharedCost: totalSharedCost,
  1163. Properties: &AllocationProperties{Cluster: SharedSuffix}, // The allocation needs to belong to a cluster,but it really doesn't matter which one, so just make it clear.
  1164. })
  1165. }
  1166. }
  1167. // (2e) Compute share coefficients for shared resources. These are computed
  1168. // after idle coefficients, and are computed for the aggregated allocations
  1169. // of the main allocation set. See above for details and an example.
  1170. var shareCoefficients map[string]float64
  1171. if shareSet.Length() > 0 {
  1172. shareCoefficients, err = computeShareCoeffs(aggregateBy, options, as)
  1173. if err != nil {
  1174. return fmt.Errorf("error computing share coefficients: %s", err)
  1175. }
  1176. }
  1177. // (3-5) Filter, distribute idle cost, and aggregate (in that order)
  1178. for _, alloc := range as.Allocations {
  1179. idleId, err := alloc.getIdleId(options)
  1180. if err != nil {
  1181. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  1182. }
  1183. skip := false
  1184. // (3) If the allocation does not match the filter, immediately skip the
  1185. // allocation.
  1186. if options.Filter != nil {
  1187. skip = !options.Filter.Matches(alloc)
  1188. }
  1189. if skip {
  1190. // If we are tracking idle filtration coefficients, delete the
  1191. // entry corresponding to the filtered allocation. (Deleting the
  1192. // entry will result in that proportional amount being removed
  1193. // from the idle allocation at the end of the process.)
  1194. if idleFiltrationCoefficients != nil {
  1195. if ifcc, ok := idleFiltrationCoefficients[idleId]; ok {
  1196. delete(ifcc, alloc.Name)
  1197. }
  1198. }
  1199. continue
  1200. }
  1201. // (4) Distribute idle allocations according to the idle coefficients
  1202. // NOTE: if idle allocation is off (i.e. ShareIdle == ShareNone) then
  1203. // all idle allocations will be in the aggSet at this point, so idleSet
  1204. // will be empty and we won't enter this block.
  1205. if idleSet.Length() > 0 {
  1206. // Distribute idle allocations by coefficient per-idleId, per-allocation
  1207. for _, idleAlloc := range idleSet.Allocations {
  1208. // Only share idle if the idleId matches; i.e. the allocation
  1209. // is from the same idleId as the idle costs
  1210. iaidleId, err := idleAlloc.getIdleId(options)
  1211. if err != nil {
  1212. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1213. return err
  1214. }
  1215. if iaidleId != idleId {
  1216. continue
  1217. }
  1218. // Make sure idle coefficients exist
  1219. if _, ok := idleCoefficients[idleId]; !ok {
  1220. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  1221. continue
  1222. }
  1223. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  1224. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  1225. continue
  1226. }
  1227. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  1228. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  1229. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  1230. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  1231. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  1232. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  1233. alloc.CPUCost += idleCPUCost
  1234. alloc.GPUCost += idleGPUCost
  1235. alloc.RAMCost += idleRAMCost
  1236. }
  1237. }
  1238. // (5) generate key to use for aggregation-by-key and allocation name
  1239. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1240. alloc.Name = key
  1241. if options.MergeUnallocated && alloc.IsUnallocated() {
  1242. alloc.Name = UnallocatedSuffix
  1243. }
  1244. // Inserting the allocation with the generated key for a name will
  1245. // perform the actual basic aggregation step.
  1246. aggSet.Insert(alloc)
  1247. }
  1248. // (6) If idle is shared and resources are shared, it's possible that some
  1249. // amount of idle cost will be shared with a shared resource. Distribute
  1250. // that idle allocation, if it exists, to the respective shared allocations
  1251. // before sharing with the aggregated allocations.
  1252. if idleSet.Length() > 0 && shareSet.Length() > 0 {
  1253. for _, alloc := range shareSet.Allocations {
  1254. idleId, err := alloc.getIdleId(options)
  1255. if err != nil {
  1256. log.DedupedWarningf(3, "AllocationSet.AggregateBy: missing idleId for allocation: %s", alloc.Name)
  1257. }
  1258. // Distribute idle allocations by coefficient per-idleId, per-allocation
  1259. for _, idleAlloc := range idleSet.Allocations {
  1260. // Only share idle if the idleId matches; i.e. the allocation
  1261. // is from the same idleId as the idle costs
  1262. iaidleId, _ := idleAlloc.getIdleId(options)
  1263. if iaidleId != idleId {
  1264. continue
  1265. }
  1266. // Make sure idle coefficients exist
  1267. if _, ok := idleCoefficients[idleId]; !ok {
  1268. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient: no idleId '%s' for '%s'", idleId, alloc.Name)
  1269. continue
  1270. }
  1271. if _, ok := idleCoefficients[idleId][alloc.Name]; !ok {
  1272. log.Warnf("AllocationSet.AggregateBy: error getting idle coefficient for '%s'", alloc.Name)
  1273. continue
  1274. }
  1275. alloc.CPUCoreHours += idleAlloc.CPUCoreHours * idleCoefficients[idleId][alloc.Name]["cpu"]
  1276. alloc.GPUHours += idleAlloc.GPUHours * idleCoefficients[idleId][alloc.Name]["gpu"]
  1277. alloc.RAMByteHours += idleAlloc.RAMByteHours * idleCoefficients[idleId][alloc.Name]["ram"]
  1278. idleCPUCost := idleAlloc.CPUCost * idleCoefficients[idleId][alloc.Name]["cpu"]
  1279. idleGPUCost := idleAlloc.GPUCost * idleCoefficients[idleId][alloc.Name]["gpu"]
  1280. idleRAMCost := idleAlloc.RAMCost * idleCoefficients[idleId][alloc.Name]["ram"]
  1281. alloc.CPUCost += idleCPUCost
  1282. alloc.GPUCost += idleGPUCost
  1283. alloc.RAMCost += idleRAMCost
  1284. }
  1285. }
  1286. }
  1287. // groupingIdleFiltrationCoeffs is used to track per-resource idle
  1288. // coefficients on a cluster-by-cluster or node-by-node basis depending
  1289. // on the IdleByNode option. It is, essentially, an aggregation of
  1290. // idleFiltrationCoefficients after they have been
  1291. // filtered above (in step 3)
  1292. var groupingIdleFiltrationCoeffs map[string]map[string]float64
  1293. if idleFiltrationCoefficients != nil {
  1294. groupingIdleFiltrationCoeffs = map[string]map[string]float64{}
  1295. for idleId, m := range idleFiltrationCoefficients {
  1296. if _, ok := groupingIdleFiltrationCoeffs[idleId]; !ok {
  1297. groupingIdleFiltrationCoeffs[idleId] = map[string]float64{
  1298. "cpu": 0.0,
  1299. "gpu": 0.0,
  1300. "ram": 0.0,
  1301. }
  1302. }
  1303. for _, n := range m {
  1304. for resource, val := range n {
  1305. groupingIdleFiltrationCoeffs[idleId][resource] += val
  1306. }
  1307. }
  1308. }
  1309. }
  1310. // (7) If we have both un-shared idle allocations and idle filtration
  1311. // coefficients then apply those. See step (2b) for an example.
  1312. if len(aggSet.IdleKeys) > 0 && groupingIdleFiltrationCoeffs != nil {
  1313. for idleKey := range aggSet.IdleKeys {
  1314. idleAlloc := aggSet.Get(idleKey)
  1315. iaidleId, err := idleAlloc.getIdleId(options)
  1316. if err != nil {
  1317. log.Errorf("AllocationSet.AggregateBy: Idle allocation is missing idleId %s", idleAlloc.Name)
  1318. return err
  1319. }
  1320. if resourceCoeffs, ok := groupingIdleFiltrationCoeffs[iaidleId]; ok {
  1321. idleAlloc.CPUCost *= resourceCoeffs["cpu"]
  1322. idleAlloc.CPUCoreHours *= resourceCoeffs["cpu"]
  1323. idleAlloc.RAMCost *= resourceCoeffs["ram"]
  1324. idleAlloc.RAMByteHours *= resourceCoeffs["ram"]
  1325. idleAlloc.GPUCost *= resourceCoeffs["gpu"]
  1326. idleAlloc.GPUHours *= resourceCoeffs["gpu"]
  1327. }
  1328. }
  1329. }
  1330. // (8) Distribute shared allocations according to the share coefficients.
  1331. if shareSet.Length() > 0 {
  1332. for _, alloc := range aggSet.Allocations {
  1333. for _, sharedAlloc := range shareSet.Allocations {
  1334. if _, ok := shareCoefficients[alloc.Name]; !ok {
  1335. if !alloc.IsIdle() && !alloc.IsUnmounted() {
  1336. log.Warnf("AllocationSet.AggregateBy: error getting share coefficient for '%s'", alloc.Name)
  1337. }
  1338. continue
  1339. }
  1340. if options.IncludeSharedCostBreakdown {
  1341. if alloc.SharedCostBreakdown == nil {
  1342. alloc.SharedCostBreakdown = map[string]SharedCostBreakdown{}
  1343. }
  1344. sharedCostName, err := sharedAlloc.determineSharingName(options)
  1345. if err != nil {
  1346. return fmt.Errorf("failed to group shared costs: %s", err)
  1347. }
  1348. // check if current allocation is a shared flat overhead cost
  1349. if strings.Contains(sharedAlloc.Name, SharedSuffix) {
  1350. sharedCostName = "overheadCost"
  1351. }
  1352. scb := SharedCostBreakdown{
  1353. Name: sharedCostName,
  1354. TotalCost: sharedAlloc.TotalCost() * shareCoefficients[alloc.Name],
  1355. CPUCost: sharedAlloc.CPUTotalCost() * shareCoefficients[alloc.Name],
  1356. GPUCost: sharedAlloc.GPUTotalCost() * shareCoefficients[alloc.Name],
  1357. RAMCost: sharedAlloc.RAMTotalCost() * shareCoefficients[alloc.Name],
  1358. PVCost: sharedAlloc.PVCost() * shareCoefficients[alloc.Name],
  1359. NetworkCost: sharedAlloc.NetworkTotalCost() * shareCoefficients[alloc.Name],
  1360. LBCost: sharedAlloc.LBTotalCost() * shareCoefficients[alloc.Name],
  1361. ExternalCost: sharedAlloc.ExternalCost * shareCoefficients[alloc.Name],
  1362. }
  1363. // fmt.Printf("shared cost: %+v", scb)
  1364. alloc.SharedCostBreakdown.Insert(scb)
  1365. }
  1366. alloc.SharedCost += sharedAlloc.TotalCost() * shareCoefficients[alloc.Name]
  1367. }
  1368. }
  1369. }
  1370. // (9) Aggregate external allocations into aggregated allocations. This may
  1371. // not be possible for every external allocation, but attempt to find an
  1372. // exact key match, given each external allocation's proerties, and
  1373. // aggregate if an exact match is found.
  1374. for _, alloc := range externalSet.Allocations {
  1375. skip := false
  1376. if options.Filter != nil {
  1377. skip = !options.Filter.Matches(alloc)
  1378. }
  1379. if !skip {
  1380. key := alloc.generateKey(aggregateBy, options.LabelConfig)
  1381. alloc.Name = key
  1382. aggSet.Insert(alloc)
  1383. }
  1384. }
  1385. // (10) In the edge case that some idle has not been distributed because
  1386. // there is no usage of that resource type, add idle back to
  1387. // aggregations with only that cost applied.
  1388. // E.g. in the case where we have a result that looks like this on the
  1389. // frontend:
  1390. // Name CPU GPU RAM
  1391. // __idle__ $10 $12 $6
  1392. // kubecost $2 $0 $1
  1393. // Sharing idle weighted would result in no idle GPU cost being
  1394. // distributed, because the coefficient for the kubecost GPU cost would
  1395. // be zero. Thus, instead we re-add idle to the aggSet with distributed
  1396. // costs zeroed out but the undistributed costs left in.
  1397. // Name CPU GPU RAM
  1398. // __idle__ $0 $12 $0
  1399. // kubecost $12 $0 $7
  1400. if idleSet.Length() > 0 {
  1401. for _, idleAlloc := range idleSet.Allocations {
  1402. // if the idle does not apply to the non-filtered values, skip it
  1403. skip := false
  1404. if options.Filter != nil {
  1405. skip = !options.Filter.Matches(idleAlloc)
  1406. }
  1407. if skip {
  1408. continue
  1409. }
  1410. idleId, err := idleAlloc.getIdleId(options)
  1411. if err != nil {
  1412. log.Errorf("AllocationSet.AggregateBy: idle allocation is missing idleId %s", idleAlloc.Name)
  1413. continue
  1414. }
  1415. hasUndistributableCost := false
  1416. if idleAlloc.CPUCost > 0 && allocatedTotalsMap[idleId]["cpu"] == 0 {
  1417. hasUndistributableCost = true
  1418. } else {
  1419. idleAlloc.CPUCost = 0
  1420. }
  1421. if idleAlloc.GPUCost > 0 && allocatedTotalsMap[idleId]["gpu"] == 0 {
  1422. hasUndistributableCost = true
  1423. } else {
  1424. idleAlloc.GPUCost = 0
  1425. }
  1426. if idleAlloc.RAMCost > 0 && allocatedTotalsMap[idleId]["ram"] == 0 {
  1427. hasUndistributableCost = true
  1428. } else {
  1429. idleAlloc.RAMCost = 0
  1430. }
  1431. if hasUndistributableCost {
  1432. idleAlloc.Name = fmt.Sprintf("%s/%s", idleId, IdleSuffix)
  1433. aggSet.Insert(idleAlloc)
  1434. }
  1435. }
  1436. }
  1437. // (11) Combine all idle allocations into a single "__idle__" allocation
  1438. if !options.SplitIdle {
  1439. for _, idleAlloc := range aggSet.IdleAllocations() {
  1440. aggSet.Delete(idleAlloc.Name)
  1441. idleAlloc.Name = IdleSuffix
  1442. aggSet.Insert(idleAlloc)
  1443. }
  1444. }
  1445. // TODO revisit this (ideally we just remove sharing from this function!)
  1446. // If filters and shared resources and shared idle are all enabled then
  1447. // we will over-count idle by exactly the portion that gets shared with the
  1448. // filtered allocations -- and idle filtration will miss this because it
  1449. // only filters the non-idle filtered costs.
  1450. //
  1451. // Consider the following example, from unit tests:
  1452. // - namespace1 28.000
  1453. // - namespace2 36.000
  1454. // - namespace3 18.000
  1455. // - cluster1/idle 20.000
  1456. // - cluster2/idle 10.000
  1457. //
  1458. // Now, we want to share namespace1, filter namespace2, and share idle:
  1459. //
  1460. // 1. Distribute idle
  1461. // ns1 ns2 ns3
  1462. // non-idle 28.000 36.000 18.000
  1463. // idle 14.688 10.312 5.000
  1464. //
  1465. // 2. Share namespace1
  1466. //
  1467. // ns2 ns3
  1468. // non-idle 36.000 18.000
  1469. // idle 10.312 5.000
  1470. // shared non-idle 18.667 9.333
  1471. // shared idle 9.792 4.896 (***)
  1472. //
  1473. // 3. Filter out all but namespace2
  1474. //
  1475. // ns2 = 36.000 + 10.312 + 18.667 + 9.792 = 74.771
  1476. //
  1477. // So, if we had NOT shared idle, we would expect something like this:
  1478. //
  1479. // ns2 = 36.000 + 18.667 = 54.667
  1480. // idle = 10.312 + 9.792 = 20.104
  1481. //
  1482. // But we will instead get this:
  1483. //
  1484. // ns2 = 36.000 + 18.667 = 54.667
  1485. // idle = 10.312 + 14.688 = 25.000
  1486. //
  1487. // Which over-shoots idle by 4.896 (***), i.e. precisely the amount of idle
  1488. // cost corresponding to namespace1 AND shared with namespace3. Phew.
  1489. //
  1490. // I originally wanted to fix this, but after 2 days, I'm punting with the
  1491. // recommendation that we rewrite this function soon. Too difficult.
  1492. // - Niko
  1493. as.Allocations = aggSet.Allocations
  1494. return nil
  1495. }
  1496. func computeShareCoeffs(aggregateBy []string, options *AllocationAggregationOptions, as *AllocationSet) (map[string]float64, error) {
  1497. // Compute coeffs by totalling per-allocation, then dividing by the total.
  1498. coeffs := map[string]float64{}
  1499. // Compute totals for all allocations
  1500. total := 0.0
  1501. // ShareEven counts each aggregation with even weight, whereas ShareWeighted
  1502. // counts each aggregation proportionally to its respective costs
  1503. shareType := options.ShareSplit
  1504. // Record allocation values first, then normalize by totals to get percentages
  1505. for _, alloc := range as.Allocations {
  1506. if alloc.IsIdle() {
  1507. // Skip idle allocations in coefficient calculation
  1508. continue
  1509. }
  1510. if alloc.IsUnmounted() {
  1511. // Skip unmounted allocations in coefficient calculation
  1512. continue
  1513. }
  1514. // Determine the post-aggregation key under which the allocation will
  1515. // be shared.
  1516. name := alloc.generateKey(aggregateBy, options.LabelConfig)
  1517. // If the current allocation will be filtered out in step 3, contribute
  1518. // its share of the shared coefficient to a "__filtered__" bin, which
  1519. // will ultimately be dropped. This step ensures that the shared cost
  1520. // of a non-filtered allocation will be conserved even when the filter
  1521. // is removed. (Otherwise, all the shared cost will get redistributed
  1522. // over the unfiltered results, inflating their shared costs.)
  1523. filtered := false
  1524. if options.Filter != nil {
  1525. filtered = !options.Filter.Matches(alloc)
  1526. }
  1527. if filtered {
  1528. name = "__filtered__"
  1529. }
  1530. if shareType == ShareEven {
  1531. // Even distribution is not additive - set to 1.0 for everything
  1532. coeffs[name] = 1.0
  1533. // Total for even distribution is always the number of coefficients
  1534. total = float64(len(coeffs))
  1535. } else {
  1536. // Both are additive for weighted distribution, where each
  1537. // cumulative coefficient will be divided by the total.
  1538. coeffs[name] += alloc.TotalCost() - alloc.SharedCost
  1539. total += alloc.TotalCost() - alloc.SharedCost
  1540. }
  1541. }
  1542. // Normalize coefficients by totals
  1543. for a := range coeffs {
  1544. if coeffs[a] > 0 && total > 0 {
  1545. coeffs[a] /= total
  1546. } else {
  1547. log.Warnf("ETL: invalid values for shared coefficients: %v, %v", coeffs[a], total)
  1548. coeffs[a] = 0.0
  1549. }
  1550. }
  1551. return coeffs, nil
  1552. }
  1553. func computeIdleCoeffs(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) (map[string]map[string]map[string]float64, map[string]map[string]float64, error) {
  1554. types := []string{"cpu", "gpu", "ram"}
  1555. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1556. // [idle_id][allocation name][resource] = [coeff]
  1557. coeffs := map[string]map[string]map[string]float64{}
  1558. // Compute totals per resource for CPU, GPU, RAM, and PV
  1559. // [idle_id][resource] = [total]
  1560. totals := map[string]map[string]float64{}
  1561. // Record allocation values first, then normalize by totals to get percentages
  1562. for _, alloc := range as.Allocations {
  1563. if alloc.IsIdle() {
  1564. // Skip idle allocations in coefficient calculation
  1565. continue
  1566. }
  1567. idleId, err := alloc.getIdleId(options)
  1568. if err != nil {
  1569. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1570. }
  1571. // get the name key for the allocation
  1572. name := alloc.Name
  1573. // Create key based tables if they don't exist
  1574. if _, ok := coeffs[idleId]; !ok {
  1575. coeffs[idleId] = map[string]map[string]float64{}
  1576. }
  1577. if _, ok := totals[idleId]; !ok {
  1578. totals[idleId] = map[string]float64{}
  1579. }
  1580. if _, ok := coeffs[idleId][name]; !ok {
  1581. coeffs[idleId][name] = map[string]float64{}
  1582. }
  1583. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1584. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1585. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1586. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1587. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1588. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1589. }
  1590. // Do the same for shared allocations
  1591. for _, alloc := range shareSet.Allocations {
  1592. if alloc.IsIdle() {
  1593. // Skip idle allocations in coefficient calculation
  1594. continue
  1595. }
  1596. // idleId will be providerId or cluster
  1597. idleId, err := alloc.getIdleId(options)
  1598. if err != nil {
  1599. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1600. }
  1601. // get the name key for the allocation
  1602. name := alloc.Name
  1603. // Create idleId based tables if they don't exist
  1604. if _, ok := coeffs[idleId]; !ok {
  1605. coeffs[idleId] = map[string]map[string]float64{}
  1606. }
  1607. if _, ok := totals[idleId]; !ok {
  1608. totals[idleId] = map[string]float64{}
  1609. }
  1610. if _, ok := coeffs[idleId][name]; !ok {
  1611. coeffs[idleId][name] = map[string]float64{}
  1612. }
  1613. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1614. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1615. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1616. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1617. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1618. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1619. }
  1620. // Normalize coefficients by totals
  1621. for id := range coeffs {
  1622. for a := range coeffs[id] {
  1623. for _, r := range types {
  1624. if coeffs[id][a][r] > 0 && totals[id][r] > 0 {
  1625. coeffs[id][a][r] /= totals[id][r]
  1626. }
  1627. }
  1628. }
  1629. }
  1630. return coeffs, totals, nil
  1631. }
  1632. func deriveProportionalAssetResourceCosts(options *AllocationAggregationOptions, as *AllocationSet, shareSet *AllocationSet) error {
  1633. // Compute idle coefficients, then save them in AllocationAggregationOptions
  1634. // [idle_id][allocation name][resource] = [coeff]
  1635. coeffs := map[string]map[string]map[string]float64{}
  1636. // Compute totals per resource for CPU, GPU, RAM, and PV
  1637. // [idle_id][resource] = [total]
  1638. totals := map[string]map[string]float64{}
  1639. // Record allocation values first, then normalize by totals to get percentages
  1640. for _, alloc := range as.Allocations {
  1641. if alloc.IsIdle() {
  1642. // Skip idle allocations in coefficient calculation
  1643. continue
  1644. }
  1645. idleId, err := alloc.getIdleId(options)
  1646. if err != nil {
  1647. log.DedupedWarningf(3, "Missing Idle Key for %s", alloc.Name)
  1648. }
  1649. // get the name key for the allocation
  1650. name := alloc.Name
  1651. // Create key based tables if they don't exist
  1652. if _, ok := coeffs[idleId]; !ok {
  1653. coeffs[idleId] = map[string]map[string]float64{}
  1654. }
  1655. if _, ok := totals[idleId]; !ok {
  1656. totals[idleId] = map[string]float64{}
  1657. }
  1658. if _, ok := coeffs[idleId][name]; !ok {
  1659. coeffs[idleId][name] = map[string]float64{}
  1660. }
  1661. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1662. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1663. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1664. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1665. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1666. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1667. }
  1668. // Do the same for shared allocations
  1669. for _, alloc := range shareSet.Allocations {
  1670. if alloc.IsIdle() {
  1671. // Skip idle allocations in coefficient calculation
  1672. continue
  1673. }
  1674. // idleId will be providerId or cluster
  1675. idleId, err := alloc.getIdleId(options)
  1676. if err != nil {
  1677. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1678. }
  1679. // get the name key for the allocation
  1680. name := alloc.Name
  1681. // Create idleId based tables if they don't exist
  1682. if _, ok := coeffs[idleId]; !ok {
  1683. coeffs[idleId] = map[string]map[string]float64{}
  1684. }
  1685. if _, ok := totals[idleId]; !ok {
  1686. totals[idleId] = map[string]float64{}
  1687. }
  1688. if _, ok := coeffs[idleId][name]; !ok {
  1689. coeffs[idleId][name] = map[string]float64{}
  1690. }
  1691. coeffs[idleId][name]["cpu"] += alloc.CPUTotalCost()
  1692. coeffs[idleId][name]["gpu"] += alloc.GPUTotalCost()
  1693. coeffs[idleId][name]["ram"] += alloc.RAMTotalCost()
  1694. totals[idleId]["cpu"] += alloc.CPUTotalCost()
  1695. totals[idleId]["gpu"] += alloc.GPUTotalCost()
  1696. totals[idleId]["ram"] += alloc.RAMTotalCost()
  1697. }
  1698. // after totals are computed, loop through and set parcs on allocations
  1699. for _, alloc := range as.Allocations {
  1700. idleId, err := alloc.getIdleId(options)
  1701. if err != nil {
  1702. log.DedupedWarningf(3, "Missing Idle Key in share set for %s", alloc.Name)
  1703. }
  1704. alloc.ProportionalAssetResourceCosts = ProportionalAssetResourceCosts{}
  1705. alloc.ProportionalAssetResourceCosts.Insert(ProportionalAssetResourceCost{
  1706. Cluster: alloc.Properties.Cluster,
  1707. Node: alloc.Properties.Node,
  1708. ProviderID: alloc.Properties.ProviderID,
  1709. GPUTotalCost: totals[idleId]["gpu"],
  1710. CPUTotalCost: totals[idleId]["cpu"],
  1711. RAMTotalCost: totals[idleId]["ram"],
  1712. GPUProportionalCost: coeffs[idleId][alloc.Name]["gpu"],
  1713. CPUProportionalCost: coeffs[idleId][alloc.Name]["cpu"],
  1714. RAMProportionalCost: coeffs[idleId][alloc.Name]["ram"],
  1715. }, options.IdleByNode)
  1716. }
  1717. return nil
  1718. }
  1719. func (a *Allocation) determineSharingName(options *AllocationAggregationOptions) (string, error) {
  1720. if a == nil {
  1721. return "", fmt.Errorf("determineSharingName called on nil Allocation")
  1722. } else if options == nil {
  1723. return "unknown", nil
  1724. }
  1725. // grab SharedLabels keys and sort them, to keep this function deterministic
  1726. var labelKeys []string
  1727. for labelKey, _ := range options.SharedLabels {
  1728. labelKeys = append(labelKeys, labelKey)
  1729. }
  1730. slices.Sort(labelKeys)
  1731. var sharedAggregateBy []string
  1732. var sharedLabels [][]string
  1733. for _, labelKey := range labelKeys {
  1734. sharedAgg := fmt.Sprintf("label:%s", labelKey)
  1735. if !slices.Contains(sharedAggregateBy, sharedAgg) {
  1736. sharedAggregateBy = append(sharedAggregateBy, sharedAgg)
  1737. }
  1738. sharedLabels = append(sharedLabels, options.SharedLabels[labelKey])
  1739. }
  1740. if len(options.SharedNamespaces) > 0 {
  1741. sharedAggregateBy = append(sharedAggregateBy, "namespace")
  1742. }
  1743. sharedCostName := a.generateKey(sharedAggregateBy, options.LabelConfig)
  1744. // get each value in the generated key, then reset the name
  1745. sharedCostNameValues := strings.Split(sharedCostName, "/")
  1746. sharedCostName = ""
  1747. // if we don't have as many values as aggregateBys, something went wrong in generateKey
  1748. if len(sharedCostNameValues) != len(sharedAggregateBy) {
  1749. log.Warnf("Unable to determine share cost group for allocation \"%s\"", a.Name)
  1750. } else {
  1751. // try to match to the first label
  1752. for i, sharedLabelValues := range sharedLabels {
  1753. allocLabel := sharedCostNameValues[i]
  1754. if slices.Contains(sharedLabelValues, allocLabel) {
  1755. return allocLabel, nil
  1756. }
  1757. }
  1758. // if we didn't match to a label, try to match to a namespace
  1759. if len(options.SharedNamespaces) > 0 {
  1760. // namespace will always be the last value, if SharedNamespaces is set
  1761. allocNamespace := sharedCostNameValues[len(sharedCostNameValues)-1]
  1762. if slices.Contains(options.SharedNamespaces, allocNamespace) {
  1763. return allocNamespace, nil
  1764. }
  1765. }
  1766. // if neither the labels nor the namespaces matched, we log a warning and mark this allocation
  1767. // as unknown
  1768. if len(sharedCostName) == 0 {
  1769. log.Warnf("Failed to determine shared cost grouping for allocation \"%s\"", a.Name)
  1770. }
  1771. }
  1772. return "unknown", nil
  1773. }
  1774. // getIdleId returns the providerId or cluster of an Allocation depending on the IdleByNode
  1775. // option in the AllocationAggregationOptions and an error if the respective field is missing
  1776. func (a *Allocation) getIdleId(options *AllocationAggregationOptions) (string, error) {
  1777. var idleId string
  1778. if options.IdleByNode {
  1779. // Key allocations to ProviderId to match against node
  1780. idleId = fmt.Sprintf("%s/%s", a.Properties.Cluster, a.Properties.Node)
  1781. if idleId == "" {
  1782. return idleId, fmt.Errorf("ProviderId is not set")
  1783. }
  1784. } else {
  1785. // key the allocations by cluster id
  1786. idleId = a.Properties.Cluster
  1787. if idleId == "" {
  1788. return idleId, fmt.Errorf("ClusterProp is not set")
  1789. }
  1790. }
  1791. return idleId, nil
  1792. }
  1793. func (a *Allocation) generateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  1794. if a == nil {
  1795. return ""
  1796. }
  1797. return a.Properties.GenerateKey(aggregateBy, labelConfig)
  1798. }
  1799. func (a *Allocation) StringProperty(property string) (string, error) {
  1800. switch property {
  1801. case AllocationClusterProp:
  1802. if a.Properties == nil {
  1803. return "", nil
  1804. }
  1805. return a.Properties.Cluster, nil
  1806. case AllocationNodeProp:
  1807. if a.Properties == nil {
  1808. return "", nil
  1809. }
  1810. return a.Properties.Node, nil
  1811. case AllocationContainerProp:
  1812. if a.Properties == nil {
  1813. return "", nil
  1814. }
  1815. return a.Properties.Container, nil
  1816. case AllocationControllerProp:
  1817. if a.Properties == nil {
  1818. return "", nil
  1819. }
  1820. return a.Properties.Controller, nil
  1821. case AllocationControllerKindProp:
  1822. if a.Properties == nil {
  1823. return "", nil
  1824. }
  1825. return a.Properties.ControllerKind, nil
  1826. case AllocationNamespaceProp:
  1827. if a.Properties == nil {
  1828. return "", nil
  1829. }
  1830. return a.Properties.Namespace, nil
  1831. case AllocationPodProp:
  1832. if a.Properties == nil {
  1833. return "", nil
  1834. }
  1835. return a.Properties.Pod, nil
  1836. case AllocationProviderIDProp:
  1837. if a.Properties == nil {
  1838. return "", nil
  1839. }
  1840. return a.Properties.ProviderID, nil
  1841. default:
  1842. return "", fmt.Errorf("Allocation: StringProperty: invalid property name: %s", property)
  1843. }
  1844. }
  1845. func (a *Allocation) StringSliceProperty(property string) ([]string, error) {
  1846. switch property {
  1847. case AllocationServiceProp:
  1848. if a.Properties == nil {
  1849. return nil, nil
  1850. }
  1851. return a.Properties.Services, nil
  1852. default:
  1853. return nil, fmt.Errorf("Allocation: StringSliceProperty: invalid property name: %s", property)
  1854. }
  1855. }
  1856. func (a *Allocation) StringMapProperty(property string) (map[string]string, error) {
  1857. switch property {
  1858. case AllocationLabelProp:
  1859. if a.Properties == nil {
  1860. return nil, nil
  1861. }
  1862. return a.Properties.Labels, nil
  1863. case AllocationAnnotationProp:
  1864. if a.Properties == nil {
  1865. return nil, nil
  1866. }
  1867. return a.Properties.Annotations, nil
  1868. default:
  1869. return nil, fmt.Errorf("Allocation: StringMapProperty: invalid property name: %s", property)
  1870. }
  1871. }
  1872. // Clone returns a new AllocationSet with a deep copy of the given
  1873. // AllocationSet's allocations.
  1874. func (as *AllocationSet) Clone() *AllocationSet {
  1875. if as == nil {
  1876. return nil
  1877. }
  1878. allocs := make(map[string]*Allocation, len(as.Allocations))
  1879. for k, v := range as.Allocations {
  1880. allocs[k] = v.Clone()
  1881. }
  1882. externalKeys := make(map[string]bool, len(as.ExternalKeys))
  1883. for k, v := range as.ExternalKeys {
  1884. externalKeys[k] = v
  1885. }
  1886. idleKeys := make(map[string]bool, len(as.IdleKeys))
  1887. for k, v := range as.IdleKeys {
  1888. idleKeys[k] = v
  1889. }
  1890. var errors []string
  1891. var warnings []string
  1892. if as.Errors != nil {
  1893. errors = make([]string, len(as.Errors))
  1894. copy(errors, as.Errors)
  1895. } else {
  1896. errors = nil
  1897. }
  1898. if as.Warnings != nil {
  1899. warnings := make([]string, len(as.Warnings))
  1900. copy(warnings, as.Warnings)
  1901. } else {
  1902. warnings = nil
  1903. }
  1904. return &AllocationSet{
  1905. Allocations: allocs,
  1906. ExternalKeys: externalKeys,
  1907. IdleKeys: idleKeys,
  1908. Window: as.Window.Clone(),
  1909. Errors: errors,
  1910. Warnings: warnings,
  1911. }
  1912. }
  1913. // Delete removes the allocation with the given name from the set
  1914. func (as *AllocationSet) Delete(name string) {
  1915. if as == nil {
  1916. return
  1917. }
  1918. delete(as.ExternalKeys, name)
  1919. delete(as.IdleKeys, name)
  1920. delete(as.Allocations, name)
  1921. }
  1922. // End returns the End time of the AllocationSet window
  1923. func (as *AllocationSet) End() time.Time {
  1924. if as == nil {
  1925. log.Warnf("AllocationSet: calling End on nil AllocationSet")
  1926. return time.Unix(0, 0)
  1927. }
  1928. if as.Window.End() == nil {
  1929. log.Warnf("AllocationSet: AllocationSet with illegal window: End is nil; len(as.allocations)=%d", len(as.Allocations))
  1930. return time.Unix(0, 0)
  1931. }
  1932. return *as.Window.End()
  1933. }
  1934. // Get returns the Allocation at the given key in the AllocationSet
  1935. func (as *AllocationSet) Get(key string) *Allocation {
  1936. if alloc, ok := as.Allocations[key]; ok {
  1937. return alloc
  1938. }
  1939. return nil
  1940. }
  1941. // ExternalAllocations returns a map of the external allocations in the set.
  1942. // Returns clones of the actual Allocations, so mutability is not a problem.
  1943. func (as *AllocationSet) ExternalAllocations() map[string]*Allocation {
  1944. externals := map[string]*Allocation{}
  1945. if as.IsEmpty() {
  1946. return externals
  1947. }
  1948. for key := range as.ExternalKeys {
  1949. if alloc, ok := as.Allocations[key]; ok {
  1950. externals[key] = alloc.Clone()
  1951. }
  1952. }
  1953. return externals
  1954. }
  1955. // ExternalCost returns the total aggregated external costs of the set
  1956. func (as *AllocationSet) ExternalCost() float64 {
  1957. if as.IsEmpty() {
  1958. return 0.0
  1959. }
  1960. externalCost := 0.0
  1961. for _, alloc := range as.Allocations {
  1962. externalCost += alloc.ExternalCost
  1963. }
  1964. return externalCost
  1965. }
  1966. // IdleAllocations returns a map of the idle allocations in the AllocationSet.
  1967. // Returns clones of the actual Allocations, so mutability is not a problem.
  1968. func (as *AllocationSet) IdleAllocations() map[string]*Allocation {
  1969. idles := map[string]*Allocation{}
  1970. if as.IsEmpty() {
  1971. return idles
  1972. }
  1973. for key := range as.IdleKeys {
  1974. if alloc, ok := as.Allocations[key]; ok {
  1975. idles[key] = alloc.Clone()
  1976. }
  1977. }
  1978. return idles
  1979. }
  1980. // Insert aggregates the current entry in the AllocationSet by the given Allocation,
  1981. // but only if the Allocation is valid, i.e. matches the AllocationSet's window. If
  1982. // there is no existing entry, one is created. Nil error response indicates success.
  1983. func (as *AllocationSet) Insert(that *Allocation) error {
  1984. if as == nil {
  1985. return fmt.Errorf("cannot insert into nil AllocationSet")
  1986. }
  1987. if as.Allocations == nil {
  1988. as.Allocations = map[string]*Allocation{}
  1989. }
  1990. if as.ExternalKeys == nil {
  1991. as.ExternalKeys = map[string]bool{}
  1992. }
  1993. if as.IdleKeys == nil {
  1994. as.IdleKeys = map[string]bool{}
  1995. }
  1996. // Add the given Allocation to the existing entry, if there is one;
  1997. // otherwise just set directly into allocations
  1998. if _, ok := as.Allocations[that.Name]; !ok {
  1999. as.Allocations[that.Name] = that
  2000. } else {
  2001. as.Allocations[that.Name].add(that)
  2002. }
  2003. // If the given Allocation is an external one, record that
  2004. if that.IsExternal() {
  2005. as.ExternalKeys[that.Name] = true
  2006. }
  2007. // If the given Allocation is an idle one, record that
  2008. if that.IsIdle() {
  2009. as.IdleKeys[that.Name] = true
  2010. }
  2011. // Expand the window, just to be safe. It's possible that the Allocation will
  2012. // be set into the map without expanding it to the AllocationSet's window.
  2013. as.Allocations[that.Name].Window = as.Allocations[that.Name].Window.Expand(as.Window)
  2014. return nil
  2015. }
  2016. // IsEmpty returns true if the AllocationSet is nil, or if it contains
  2017. // zero allocations.
  2018. func (as *AllocationSet) IsEmpty() bool {
  2019. if as == nil || len(as.Allocations) == 0 {
  2020. return true
  2021. }
  2022. return false
  2023. }
  2024. // Length returns the number of Allocations in the set
  2025. func (as *AllocationSet) Length() int {
  2026. if as == nil {
  2027. return 0
  2028. }
  2029. return len(as.Allocations)
  2030. }
  2031. // ResetAdjustments sets all cost adjustment fields to zero
  2032. func (as *AllocationSet) ResetAdjustments() {
  2033. if as == nil {
  2034. return
  2035. }
  2036. for _, a := range as.Allocations {
  2037. a.ResetAdjustments()
  2038. }
  2039. }
  2040. // Resolution returns the AllocationSet's window duration
  2041. func (as *AllocationSet) Resolution() time.Duration {
  2042. return as.Window.Duration()
  2043. }
  2044. // GetWindow returns the AllocationSet's window
  2045. func (as *AllocationSet) GetWindow() Window {
  2046. return as.Window
  2047. }
  2048. // Set uses the given Allocation to overwrite the existing entry in the
  2049. // AllocationSet under the Allocation's name.
  2050. func (as *AllocationSet) Set(alloc *Allocation) error {
  2051. if as.IsEmpty() {
  2052. as.Allocations = map[string]*Allocation{}
  2053. as.ExternalKeys = map[string]bool{}
  2054. as.IdleKeys = map[string]bool{}
  2055. }
  2056. as.Allocations[alloc.Name] = alloc
  2057. // If the given Allocation is an external one, record that
  2058. if alloc.IsExternal() {
  2059. as.ExternalKeys[alloc.Name] = true
  2060. }
  2061. // If the given Allocation is an idle one, record that
  2062. if alloc.IsIdle() {
  2063. as.IdleKeys[alloc.Name] = true
  2064. }
  2065. return nil
  2066. }
  2067. // Start returns the Start time of the AllocationSet window
  2068. func (as *AllocationSet) Start() time.Time {
  2069. if as == nil {
  2070. log.Warnf("AllocationSet: calling Start on nil AllocationSet")
  2071. return time.Unix(0, 0)
  2072. }
  2073. if as.Window.Start() == nil {
  2074. log.Warnf("AllocationSet: AllocationSet with illegal window: Start is nil; len(as.allocations)=%d", len(as.Allocations))
  2075. return time.Unix(0, 0)
  2076. }
  2077. return *as.Window.Start()
  2078. }
  2079. // String represents the given Allocation as a string
  2080. func (as *AllocationSet) String() string {
  2081. if as == nil {
  2082. return "<nil>"
  2083. }
  2084. return fmt.Sprintf(
  2085. "AllocationSet{length: %d; window: %s; totalCost: %.2f}",
  2086. as.Length(),
  2087. as.Window,
  2088. as.TotalCost())
  2089. }
  2090. // TotalCost returns the sum of all TotalCosts of the allocations contained
  2091. func (as *AllocationSet) TotalCost() float64 {
  2092. if as.IsEmpty() {
  2093. return 0.0
  2094. }
  2095. tc := 0.0
  2096. for _, a := range as.Allocations {
  2097. tc += a.TotalCost()
  2098. }
  2099. return tc
  2100. }
  2101. // UTCOffset returns the AllocationSet's configured UTCOffset.
  2102. func (as *AllocationSet) UTCOffset() time.Duration {
  2103. _, zone := as.Start().Zone()
  2104. return time.Duration(zone) * time.Second
  2105. }
  2106. func (as *AllocationSet) Accumulate(that *AllocationSet) (*AllocationSet, error) {
  2107. if as.IsEmpty() {
  2108. return that.Clone(), nil
  2109. }
  2110. if that.IsEmpty() {
  2111. return as.Clone(), nil
  2112. }
  2113. // Set start, end to min(start), max(end)
  2114. start := as.Start()
  2115. end := as.End()
  2116. if that.Start().Before(start) {
  2117. start = that.Start()
  2118. }
  2119. if that.End().After(end) {
  2120. end = that.End()
  2121. }
  2122. acc := NewAllocationSet(start, end)
  2123. for _, alloc := range as.Allocations {
  2124. err := acc.Insert(alloc)
  2125. if err != nil {
  2126. return nil, err
  2127. }
  2128. }
  2129. for _, alloc := range that.Allocations {
  2130. err := acc.Insert(alloc)
  2131. if err != nil {
  2132. return nil, err
  2133. }
  2134. }
  2135. return acc, nil
  2136. }
  2137. // AllocationSetRange is a thread-safe slice of AllocationSets. It is meant to
  2138. // be used such that the AllocationSets held are consecutive and coherent with
  2139. // respect to using the same aggregation properties, UTC offset, and
  2140. // resolution. However these rules are not necessarily enforced, so use wisely.
  2141. type AllocationSetRange struct {
  2142. Allocations []*AllocationSet
  2143. FromStore string // stores the name of the store used to retrieve the data
  2144. }
  2145. // NewAllocationSetRange instantiates a new range composed of the given
  2146. // AllocationSets in the order provided.
  2147. func NewAllocationSetRange(allocs ...*AllocationSet) *AllocationSetRange {
  2148. return &AllocationSetRange{
  2149. Allocations: allocs,
  2150. }
  2151. }
  2152. // Get safely retrieves the AllocationSet at the given index of the range.
  2153. func (asr *AllocationSetRange) Get(i int) (*AllocationSet, error) {
  2154. if i < 0 || i >= len(asr.Allocations) {
  2155. return nil, fmt.Errorf("AllocationSetRange: index out of range: %d", i)
  2156. }
  2157. return asr.Allocations[i], nil
  2158. }
  2159. // Accumulate sums each AllocationSet in the given range, returning a single cumulative
  2160. // AllocationSet for the entire range.
  2161. func (asr *AllocationSetRange) accumulate() (*AllocationSet, error) {
  2162. var allocSet *AllocationSet
  2163. var err error
  2164. for _, as := range asr.Allocations {
  2165. allocSet, err = allocSet.Accumulate(as)
  2166. if err != nil {
  2167. return nil, err
  2168. }
  2169. }
  2170. return allocSet, nil
  2171. }
  2172. // newAccumulation clones the first available AllocationSet to use as the data structure to
  2173. // Accumulate the remaining data. This leaves the original AllocationSetRange intact.
  2174. func (asr *AllocationSetRange) newAccumulation() (*AllocationSet, error) {
  2175. // NOTE: Adding this API for consistency across SummaryAllocation and Assets, but this
  2176. // NOTE: implementation is almost identical to regular Accumulate(). The Accumulate() method
  2177. // NOTE: for Allocation returns Clone() of the input, which is required for Accumulate
  2178. // NOTE: support (unit tests are great for verifying this information).
  2179. var allocSet *AllocationSet
  2180. var err error
  2181. if asr == nil {
  2182. return nil, fmt.Errorf("nil AllocationSetRange in accumulation")
  2183. }
  2184. if len(asr.Allocations) == 0 {
  2185. return nil, fmt.Errorf("AllocationSetRange has empty AssetSet in accumulation")
  2186. }
  2187. for _, as := range asr.Allocations {
  2188. if allocSet == nil {
  2189. allocSet = as.Clone()
  2190. continue
  2191. }
  2192. var allocSetCopy *AllocationSet = nil
  2193. if as != nil {
  2194. allocSetCopy = as.Clone()
  2195. }
  2196. allocSet, err = allocSet.Accumulate(allocSetCopy)
  2197. if err != nil {
  2198. return nil, err
  2199. }
  2200. }
  2201. return allocSet, nil
  2202. }
  2203. // Accumulate sums AllocationSets based on the AccumulateOption (calendar week or calendar month).
  2204. // The accumulated set is determined by the start of the window of the allocation set.
  2205. func (asr *AllocationSetRange) Accumulate(accumulateBy AccumulateOption) (*AllocationSetRange, error) {
  2206. switch accumulateBy {
  2207. case AccumulateOptionNone:
  2208. return asr.accumulateByNone()
  2209. case AccumulateOptionAll:
  2210. return asr.accumulateByAll()
  2211. case AccumulateOptionHour:
  2212. return asr.accumulateByHour()
  2213. case AccumulateOptionDay:
  2214. return asr.accumulateByDay()
  2215. case AccumulateOptionWeek:
  2216. return asr.accumulateByWeek()
  2217. case AccumulateOptionMonth:
  2218. return asr.accumulateByMonth()
  2219. default:
  2220. // ideally, this should never happen
  2221. return nil, fmt.Errorf("unexpected error, invalid accumulateByType: %s", accumulateBy)
  2222. }
  2223. }
  2224. func (asr *AllocationSetRange) accumulateByAll() (*AllocationSetRange, error) {
  2225. var err error
  2226. var as *AllocationSet
  2227. as, err = asr.newAccumulation()
  2228. if err != nil {
  2229. return nil, fmt.Errorf("error accumulating all:%s", err)
  2230. }
  2231. accumulated := NewAllocationSetRange(as)
  2232. return accumulated, nil
  2233. }
  2234. func (asr *AllocationSetRange) accumulateByNone() (*AllocationSetRange, error) {
  2235. return asr.Clone(), nil
  2236. }
  2237. func (asr *AllocationSetRange) accumulateByHour() (*AllocationSetRange, error) {
  2238. // ensure that the summary allocation sets have a 1-hour window, if a set exists
  2239. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() != time.Hour {
  2240. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", asr.Allocations[0].Window.Duration())
  2241. }
  2242. return asr.Clone(), nil
  2243. }
  2244. func (asr *AllocationSetRange) accumulateByDay() (*AllocationSetRange, error) {
  2245. // if the allocation set window is 1-day, just return the existing allocation set range
  2246. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() == time.Hour*24 {
  2247. return asr, nil
  2248. }
  2249. var toAccumulate *AllocationSetRange
  2250. result := NewAllocationSetRange()
  2251. for i, as := range asr.Allocations {
  2252. if as.Window.Duration() != time.Hour {
  2253. return nil, fmt.Errorf("window duration must equal 1 hour; got:%s", as.Window.Duration())
  2254. }
  2255. hour := as.Window.Start().Hour()
  2256. if toAccumulate == nil {
  2257. toAccumulate = NewAllocationSetRange()
  2258. as = as.Clone()
  2259. }
  2260. toAccumulate.Append(as)
  2261. asAccumulated, err := toAccumulate.accumulate()
  2262. if err != nil {
  2263. return nil, fmt.Errorf("error accumulating result: %s", err)
  2264. }
  2265. toAccumulate = NewAllocationSetRange(asAccumulated)
  2266. if hour == 23 || i == len(asr.Allocations)-1 {
  2267. if length := len(toAccumulate.Allocations); length != 1 {
  2268. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2269. }
  2270. result.Append(toAccumulate.Allocations[0])
  2271. toAccumulate = nil
  2272. }
  2273. }
  2274. return result, nil
  2275. }
  2276. func (asr *AllocationSetRange) accumulateByMonth() (*AllocationSetRange, error) {
  2277. var toAccumulate *AllocationSetRange
  2278. result := NewAllocationSetRange()
  2279. for i, as := range asr.Allocations {
  2280. if as.Window.Duration() != time.Hour*24 {
  2281. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  2282. }
  2283. _, month, _ := as.Window.Start().Date()
  2284. _, nextDayMonth, _ := as.Window.Start().Add(time.Hour * 24).Date()
  2285. if toAccumulate == nil {
  2286. toAccumulate = NewAllocationSetRange()
  2287. as = as.Clone()
  2288. }
  2289. toAccumulate.Append(as)
  2290. asAccumulated, err := toAccumulate.accumulate()
  2291. if err != nil {
  2292. return nil, fmt.Errorf("error accumulating result: %s", err)
  2293. }
  2294. toAccumulate = NewAllocationSetRange(asAccumulated)
  2295. // either the month has ended, or there are no more allocation sets
  2296. if month != nextDayMonth || i == len(asr.Allocations)-1 {
  2297. if length := len(toAccumulate.Allocations); length != 1 {
  2298. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2299. }
  2300. result.Append(toAccumulate.Allocations[0])
  2301. toAccumulate = nil
  2302. }
  2303. }
  2304. return result, nil
  2305. }
  2306. func (asr *AllocationSetRange) accumulateByWeek() (*AllocationSetRange, error) {
  2307. if len(asr.Allocations) > 0 && asr.Allocations[0].Window.Duration() == timeutil.Week {
  2308. return asr, nil
  2309. }
  2310. var toAccumulate *AllocationSetRange
  2311. result := NewAllocationSetRange()
  2312. for i, as := range asr.Allocations {
  2313. if as.Window.Duration() != time.Hour*24 {
  2314. return nil, fmt.Errorf("window duration must equal 24 hours; got:%s", as.Window.Duration())
  2315. }
  2316. dayOfWeek := as.Window.Start().Weekday()
  2317. if toAccumulate == nil {
  2318. toAccumulate = NewAllocationSetRange()
  2319. as = as.Clone()
  2320. }
  2321. toAccumulate.Append(as)
  2322. asAccumulated, err := toAccumulate.accumulate()
  2323. if err != nil {
  2324. return nil, fmt.Errorf("error accumulating result: %s", err)
  2325. }
  2326. toAccumulate = NewAllocationSetRange(asAccumulated)
  2327. // current assumption is the week always ends on Saturday, or there are no more allocation sets
  2328. if dayOfWeek == time.Saturday || i == len(asr.Allocations)-1 {
  2329. if length := len(toAccumulate.Allocations); length != 1 {
  2330. return nil, fmt.Errorf("failed accumulation, detected %d sets instead of 1", length)
  2331. }
  2332. result.Append(toAccumulate.Allocations[0])
  2333. toAccumulate = nil
  2334. }
  2335. }
  2336. return result, nil
  2337. }
  2338. // AggregateBy aggregates each AllocationSet in the range by the given
  2339. // properties and options.
  2340. func (asr *AllocationSetRange) AggregateBy(aggregateBy []string, options *AllocationAggregationOptions) error {
  2341. aggRange := &AllocationSetRange{Allocations: []*AllocationSet{}}
  2342. for _, as := range asr.Allocations {
  2343. err := as.AggregateBy(aggregateBy, options)
  2344. if err != nil {
  2345. return err
  2346. }
  2347. aggRange.Allocations = append(aggRange.Allocations, as)
  2348. }
  2349. asr.Allocations = aggRange.Allocations
  2350. return nil
  2351. }
  2352. // Append appends the given AllocationSet to the end of the range. It does not
  2353. // validate whether or not that violates window continuity.
  2354. func (asr *AllocationSetRange) Append(that *AllocationSet) {
  2355. asr.Allocations = append(asr.Allocations, that)
  2356. }
  2357. // InsertRange merges the given AllocationSetRange into the receiving one by
  2358. // lining up sets with matching windows, then inserting each allocation from
  2359. // the given ASR into the respective set in the receiving ASR. If the given
  2360. // ASR contains an AllocationSet from a window that does not exist in the
  2361. // receiving ASR, then an error is returned. However, the given ASR does not
  2362. // need to cover the full range of the receiver.
  2363. func (asr *AllocationSetRange) InsertRange(that *AllocationSetRange) error {
  2364. if asr == nil {
  2365. return fmt.Errorf("cannot insert range into nil AllocationSetRange")
  2366. }
  2367. // Providing an empty or nil set range is a no-op
  2368. if that == nil {
  2369. return nil
  2370. }
  2371. // keys maps window to index in asr
  2372. keys := map[string]int{}
  2373. for i, as := range asr.Allocations {
  2374. if as == nil {
  2375. continue
  2376. }
  2377. keys[as.Window.String()] = i
  2378. }
  2379. // Nothing to merge, so simply return
  2380. if len(keys) == 0 {
  2381. return nil
  2382. }
  2383. var err error
  2384. for _, thatAS := range that.Allocations {
  2385. if thatAS == nil || err != nil {
  2386. continue
  2387. }
  2388. // Find matching AllocationSet in asr
  2389. i, ok := keys[thatAS.Window.String()]
  2390. if !ok {
  2391. err = fmt.Errorf("cannot merge AllocationSet into window that does not exist: %s", thatAS.Window.String())
  2392. continue
  2393. }
  2394. as, err := asr.Get(i)
  2395. if err != nil {
  2396. err = fmt.Errorf("AllocationSetRange index does not exist: %d", i)
  2397. continue
  2398. }
  2399. // Insert each Allocation from the given set
  2400. for _, alloc := range thatAS.Allocations {
  2401. err = as.Insert(alloc)
  2402. if err != nil {
  2403. err = fmt.Errorf("error inserting allocation: %s", err)
  2404. continue
  2405. }
  2406. }
  2407. }
  2408. // err might be nil
  2409. return err
  2410. }
  2411. // Length returns the length of the range, which is zero if nil
  2412. func (asr *AllocationSetRange) Length() int {
  2413. if asr == nil || asr.Allocations == nil {
  2414. return 0
  2415. }
  2416. return len(asr.Allocations)
  2417. }
  2418. // Slice copies the underlying slice of AllocationSets, maintaining order,
  2419. // and returns the copied slice.
  2420. func (asr *AllocationSetRange) Slice() []*AllocationSet {
  2421. if asr == nil || asr.Allocations == nil {
  2422. return nil
  2423. }
  2424. copy := []*AllocationSet{}
  2425. for _, as := range asr.Allocations {
  2426. copy = append(copy, as.Clone())
  2427. }
  2428. return copy
  2429. }
  2430. // String represents the given AllocationSetRange as a string
  2431. func (asr *AllocationSetRange) String() string {
  2432. if asr == nil {
  2433. return "<nil>"
  2434. }
  2435. return fmt.Sprintf("AllocationSetRange{length: %d}", asr.Length())
  2436. }
  2437. // UTCOffset returns the detected UTCOffset of the AllocationSets within the
  2438. // range. Defaults to 0 if the range is nil or empty. Does not warn if there
  2439. // are sets with conflicting UTCOffsets (just returns the first).
  2440. func (asr *AllocationSetRange) UTCOffset() time.Duration {
  2441. if asr.Length() == 0 {
  2442. return 0
  2443. }
  2444. as, err := asr.Get(0)
  2445. if err != nil {
  2446. return 0
  2447. }
  2448. return as.UTCOffset()
  2449. }
  2450. // Window returns the full window that the AllocationSetRange spans, from the
  2451. // start of the first AllocationSet to the end of the last one.
  2452. func (asr *AllocationSetRange) Window() Window {
  2453. if asr == nil || asr.Length() == 0 {
  2454. return NewWindow(nil, nil)
  2455. }
  2456. start := asr.Allocations[0].Start()
  2457. end := asr.Allocations[asr.Length()-1].End()
  2458. return NewWindow(&start, &end)
  2459. }
  2460. // Start returns the earliest start of all Allocations in the AllocationSetRange.
  2461. // It returns an error if there are no allocations.
  2462. func (asr *AllocationSetRange) Start() (time.Time, error) {
  2463. start := time.Time{}
  2464. if asr == nil {
  2465. return start, fmt.Errorf("had no data to compute a start from")
  2466. }
  2467. firstStartNotSet := true
  2468. for _, as := range asr.Allocations {
  2469. for _, a := range as.Allocations {
  2470. if firstStartNotSet {
  2471. start = a.Start
  2472. firstStartNotSet = false
  2473. }
  2474. if a.Start.Before(start) {
  2475. start = a.Start
  2476. }
  2477. }
  2478. }
  2479. if firstStartNotSet {
  2480. return start, fmt.Errorf("had no data to compute a start from")
  2481. }
  2482. return start, nil
  2483. }
  2484. // End returns the latest end of all Allocations in the AllocationSetRange.
  2485. // It returns an error if there are no allocations.
  2486. func (asr *AllocationSetRange) End() (time.Time, error) {
  2487. end := time.Time{}
  2488. if asr == nil {
  2489. return end, fmt.Errorf("had no data to compute an end from")
  2490. }
  2491. firstEndNotSet := true
  2492. for _, as := range asr.Allocations {
  2493. for _, a := range as.Allocations {
  2494. if firstEndNotSet {
  2495. end = a.End
  2496. firstEndNotSet = false
  2497. }
  2498. if a.End.After(end) {
  2499. end = a.End
  2500. }
  2501. }
  2502. }
  2503. if firstEndNotSet {
  2504. return end, fmt.Errorf("had no data to compute an end from")
  2505. }
  2506. return end, nil
  2507. }
  2508. // StartAndEnd iterates over all AssetSets in the AssetSetRange and returns the earliest start and
  2509. // latest end over the entire range
  2510. func (asr *AllocationSetRange) StartAndEnd() (time.Time, time.Time, error) {
  2511. start := time.Time{}
  2512. end := time.Time{}
  2513. if asr == nil {
  2514. return start, end, fmt.Errorf("had no data to compute a start and end from")
  2515. }
  2516. firstStartNotSet := true
  2517. firstEndNotSet := true
  2518. for _, as := range asr.Allocations {
  2519. for _, a := range as.Allocations {
  2520. if firstStartNotSet {
  2521. start = a.Start
  2522. firstStartNotSet = false
  2523. }
  2524. if a.Start.Before(start) {
  2525. start = a.Start
  2526. }
  2527. if firstEndNotSet {
  2528. end = a.End
  2529. firstEndNotSet = false
  2530. }
  2531. if a.End.After(end) {
  2532. end = a.End
  2533. }
  2534. }
  2535. }
  2536. if firstStartNotSet {
  2537. return start, end, fmt.Errorf("had no data to compute a start from")
  2538. }
  2539. if firstEndNotSet {
  2540. return start, end, fmt.Errorf("had no data to compute an end from")
  2541. }
  2542. return start, end, nil
  2543. }
  2544. // Minutes returns the duration, in minutes, between the earliest start
  2545. // and the latest end of all assets in the AllocationSetRange.
  2546. func (asr *AllocationSetRange) Minutes() float64 {
  2547. if asr == nil {
  2548. return 0
  2549. }
  2550. start, end, err := asr.StartAndEnd()
  2551. if err != nil {
  2552. return 0
  2553. }
  2554. duration := end.Sub(start)
  2555. return duration.Minutes()
  2556. }
  2557. // TotalCost returns the sum of all TotalCosts of the allocations contained
  2558. func (asr *AllocationSetRange) TotalCost() float64 {
  2559. if asr == nil || len(asr.Allocations) == 0 {
  2560. return 0.0
  2561. }
  2562. tc := 0.0
  2563. for _, as := range asr.Allocations {
  2564. tc += as.TotalCost()
  2565. }
  2566. return tc
  2567. }
  2568. // Clone returns a new AllocationSetRange cloned from the existing ASR
  2569. func (asr *AllocationSetRange) Clone() *AllocationSetRange {
  2570. sasrClone := NewAllocationSetRange()
  2571. sasrClone.FromStore = asr.FromStore
  2572. for _, as := range asr.Allocations {
  2573. asClone := as.Clone()
  2574. sasrClone.Append(asClone)
  2575. }
  2576. return sasrClone
  2577. }