allocation.go 77 KB

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