asset.go 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591
  1. package kubecost
  2. import (
  3. "encoding"
  4. "fmt"
  5. "math"
  6. "strings"
  7. "time"
  8. "github.com/opencost/opencost/pkg/log"
  9. "github.com/opencost/opencost/pkg/util/json"
  10. )
  11. // UndefinedKey is used in composing Asset group keys if the group does not have that property defined.
  12. // E.g. if aggregating on Cluster, Assets in the AssetSet where Asset has no cluster will be grouped under key "__undefined__"
  13. const UndefinedKey = "__undefined__"
  14. // LocalStorageClass is used to assign storage class of local disks.
  15. const LocalStorageClass = "__local__"
  16. // UnknownStorageClass is used to assign storage class of persistent volume whose information is unable to be traced.
  17. const UnknownStorageClass = "__unknown__"
  18. // Asset defines an entity within a cluster that has a defined cost over a
  19. // given period of time.
  20. type Asset interface {
  21. // Type identifies the kind of Asset, which must always exist and should
  22. // be defined by the underlying type implementing the interface.
  23. Type() AssetType
  24. // GetProperties are a map of predefined traits, which may or may not exist,
  25. // but must conform to the AssetProperty schema
  26. GetProperties() *AssetProperties
  27. SetProperties(*AssetProperties)
  28. // GetLabels are a map of undefined string-to-string values
  29. GetLabels() AssetLabels
  30. SetLabels(AssetLabels)
  31. // Monetary values
  32. GetAdjustment() float64
  33. SetAdjustment(float64)
  34. TotalCost() float64
  35. // Temporal values
  36. GetStart() time.Time
  37. GetEnd() time.Time
  38. SetStartEnd(time.Time, time.Time)
  39. GetWindow() Window
  40. SetWindow(Window)
  41. ExpandWindow(Window)
  42. Minutes() float64
  43. // Operations and comparisons
  44. Add(Asset) Asset
  45. Clone() Asset
  46. Equal(Asset) bool
  47. // Representations
  48. encoding.BinaryMarshaler
  49. encoding.BinaryUnmarshaler
  50. json.Marshaler
  51. fmt.Stringer
  52. }
  53. // AssetToExternalAllocation converts the given asset to an Allocation, given
  54. // the Properties to use to aggregate, and the mapping from Allocation property
  55. // to Asset label. For example, consider this asset:
  56. //
  57. // CURRENT: Asset ETL stores its data ALREADY MAPPED from label to k8s concept. This isn't ideal-- see the TOOD.
  58. //
  59. // Cloud {
  60. // TotalCost: 10.00,
  61. // Labels{
  62. // "kubernetes_namespace":"monitoring",
  63. // "env":"prod"
  64. // }
  65. // }
  66. //
  67. // Given the following parameters, we expect to return:
  68. //
  69. // 1. single-prop full match
  70. // aggregateBy = ["namespace"]
  71. // => Allocation{Name: "monitoring", ExternalCost: 10.00, TotalCost: 10.00}, nil
  72. //
  73. // 2. multi-prop full match
  74. // aggregateBy = ["namespace", "label:env"]
  75. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  76. // => Allocation{Name: "monitoring/env=prod", ExternalCost: 10.00, TotalCost: 10.00}, nil
  77. //
  78. // 3. multi-prop partial match
  79. // aggregateBy = ["namespace", "label:foo"]
  80. // => Allocation{Name: "monitoring/__unallocated__", ExternalCost: 10.00, TotalCost: 10.00}, nil
  81. //
  82. // 4. no match
  83. // aggregateBy = ["cluster"]
  84. // => nil, err
  85. //
  86. // TODO:
  87. //
  88. // Cloud {
  89. // TotalCost: 10.00,
  90. // Labels{
  91. // "kubernetes_namespace":"monitoring",
  92. // "env":"prod"
  93. // }
  94. // }
  95. //
  96. // Given the following parameters, we expect to return:
  97. //
  98. // 1. single-prop full match
  99. // aggregateBy = ["namespace"]
  100. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  101. // => Allocation{Name: "monitoring", ExternalCost: 10.00, TotalCost: 10.00}, nil
  102. //
  103. // 2. multi-prop full match
  104. // aggregateBy = ["namespace", "label:env"]
  105. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  106. // => Allocation{Name: "monitoring/env=prod", ExternalCost: 10.00, TotalCost: 10.00}, nil
  107. //
  108. // 3. multi-prop partial match
  109. // aggregateBy = ["namespace", "label:foo"]
  110. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  111. // => Allocation{Name: "monitoring/__unallocated__", ExternalCost: 10.00, TotalCost: 10.00}, nil
  112. //
  113. // 4. no match
  114. // aggregateBy = ["cluster"]
  115. // allocationPropertyLabels = {"namespace":"kubernetes_namespace"}
  116. // => nil, err
  117. //
  118. // (See asset_test.go for assertions of these examples and more.)
  119. func AssetToExternalAllocation(asset Asset, aggregateBy []string, labelConfig *LabelConfig) (*Allocation, error) {
  120. if asset == nil {
  121. return nil, fmt.Errorf("asset is nil")
  122. }
  123. // Use default label config if one is not provided.
  124. if labelConfig == nil {
  125. labelConfig = NewLabelConfig()
  126. }
  127. // names will collect the slash-separated names accrued by iterating over
  128. // aggregateBy and checking the relevant labels.
  129. names := []string{}
  130. // match records whether or not a match was found in the Asset labels,
  131. // such that is can genuinely be turned into an external Allocation.
  132. match := false
  133. // props records the relevant Properties to set on the resultant Allocation
  134. props := AllocationProperties{}
  135. // For each aggregation parameter, try to find a match in the asset's
  136. // labels, using the labelConfig to translate. For an aggregation parameter
  137. // defined by a label (e.g. "label:app") this is simple: look for the label
  138. // and use it (e.g. if "app" is a defined label on the asset, then use its
  139. // value). For an aggregation parameter defined by a non-label property
  140. // (e.g. "namespace") this requires using the labelConfig to look up the
  141. // label name associated with that property and to use the value under that
  142. // label, if set (e.g. if the aggregation property is "namespace" and the
  143. // labelConfig is configured with "namespace_external_label" => "kubens"
  144. // and the asset has label "kubens":"kubecost", then file the asset as an
  145. // external cost under "kubecost").
  146. for _, aggBy := range aggregateBy {
  147. name := labelConfig.GetExternalAllocationName(asset.GetLabels(), aggBy)
  148. if name == "" {
  149. // No matching label has been defined in the cost-analyzer label config
  150. // relating to the given aggregateBy property.
  151. names = append(names, UnallocatedSuffix)
  152. continue
  153. } else {
  154. names = append(names, name)
  155. match = true
  156. // Default labels to an empty map, if necessary
  157. if props.Labels == nil {
  158. props.Labels = map[string]string{}
  159. }
  160. // Set the corresponding property on props
  161. switch aggBy {
  162. case AllocationClusterProp:
  163. props.Cluster = name
  164. case AllocationNodeProp:
  165. props.Node = name
  166. case AllocationNamespaceProp:
  167. props.Namespace = name
  168. case AllocationControllerKindProp:
  169. props.ControllerKind = name
  170. case AllocationControllerProp:
  171. props.Controller = name
  172. case AllocationPodProp:
  173. props.Pod = name
  174. case AllocationContainerProp:
  175. props.Container = name
  176. case AllocationServiceProp:
  177. props.Services = []string{name}
  178. case AllocationDeploymentProp:
  179. props.Controller = name
  180. props.ControllerKind = "deployment"
  181. case AllocationStatefulSetProp:
  182. props.Controller = name
  183. props.ControllerKind = "statefulset"
  184. case AllocationDaemonSetProp:
  185. props.Controller = name
  186. props.ControllerKind = "daemonset"
  187. case AllocationDepartmentProp:
  188. props.Labels[labelConfig.DepartmentLabel] = name
  189. case AllocationEnvironmentProp:
  190. props.Labels[labelConfig.EnvironmentLabel] = name
  191. case AllocationOwnerProp:
  192. props.Labels[labelConfig.OwnerLabel] = name
  193. case AllocationProductProp:
  194. props.Labels[labelConfig.ProductLabel] = name
  195. case AllocationTeamProp:
  196. props.Labels[labelConfig.TeamLabel] = name
  197. default:
  198. if strings.HasPrefix(aggBy, "label:") {
  199. // Set the corresponding label in props
  200. labelName := strings.TrimPrefix(aggBy, "label:")
  201. labelValue := strings.TrimPrefix(name, labelName+"=")
  202. props.Labels[labelName] = labelValue
  203. }
  204. }
  205. }
  206. }
  207. // If not a signle aggregation property generated a matching label property,
  208. // then consider the asset ineligible to be treated as an external allocation.
  209. if !match {
  210. return nil, fmt.Errorf("asset does not qualify as an external allocation")
  211. }
  212. // Use naming to label as an external allocation. See IsExternal() for more.
  213. names = append(names, ExternalSuffix)
  214. // TODO: external allocation: efficiency?
  215. // TODO: external allocation: resource totals?
  216. return &Allocation{
  217. Name: strings.Join(names, "/"),
  218. Properties: &props,
  219. Window: asset.GetWindow().Clone(),
  220. Start: asset.GetStart(),
  221. End: asset.GetEnd(),
  222. ExternalCost: asset.TotalCost(),
  223. }, nil
  224. }
  225. // key is used to determine uniqueness of an Asset, for instance during Insert
  226. // to determine if two Assets should be combined. Passing `nil` `aggregateBy` indicates
  227. // that all available `AssetProperty` keys should be used. Passing empty `aggregateBy` indicates that
  228. // no key should be used (e.g. to aggregate all assets). Passing one or more `aggregateBy`
  229. // values will key by only those values.
  230. // Valid values of `aggregateBy` elements are strings which are an `AssetProperty`, and strings prefixed
  231. // with `"label:"`.
  232. func key(a Asset, aggregateBy []string, labelConfig *LabelConfig) (string, error) {
  233. var buffer strings.Builder
  234. if labelConfig == nil {
  235. labelConfig = NewLabelConfig()
  236. }
  237. if aggregateBy == nil {
  238. aggregateBy = []string{
  239. string(AssetProviderProp),
  240. string(AssetAccountProp),
  241. string(AssetProjectProp),
  242. string(AssetCategoryProp),
  243. string(AssetClusterProp),
  244. string(AssetTypeProp),
  245. string(AssetServiceProp),
  246. string(AssetProviderIDProp),
  247. string(AssetNameProp),
  248. }
  249. }
  250. for i, s := range aggregateBy {
  251. key := ""
  252. switch true {
  253. case s == string(AssetProviderProp):
  254. key = a.GetProperties().Provider
  255. case s == string(AssetAccountProp):
  256. key = a.GetProperties().Account
  257. case s == string(AssetProjectProp):
  258. key = a.GetProperties().Project
  259. case s == string(AssetClusterProp):
  260. key = a.GetProperties().Cluster
  261. case s == string(AssetCategoryProp):
  262. key = a.GetProperties().Category
  263. case s == string(AssetTypeProp):
  264. key = a.Type().String()
  265. case s == string(AssetServiceProp):
  266. key = a.GetProperties().Service
  267. case s == string(AssetProviderIDProp):
  268. key = a.GetProperties().ProviderID
  269. case s == string(AssetNameProp):
  270. key = a.GetProperties().Name
  271. case s == string(AssetDepartmentProp):
  272. key = getKeyFromLabelConfig(a, labelConfig, labelConfig.DepartmentExternalLabel)
  273. case s == string(AssetEnvironmentProp):
  274. key = getKeyFromLabelConfig(a, labelConfig, labelConfig.EnvironmentExternalLabel)
  275. case s == string(AssetOwnerProp):
  276. key = getKeyFromLabelConfig(a, labelConfig, labelConfig.OwnerExternalLabel)
  277. case s == string(AssetProductProp):
  278. key = getKeyFromLabelConfig(a, labelConfig, labelConfig.ProductExternalLabel)
  279. case s == string(AssetTeamProp):
  280. key = getKeyFromLabelConfig(a, labelConfig, labelConfig.TeamExternalLabel)
  281. case strings.HasPrefix(s, "label:"):
  282. if labelKey := strings.TrimPrefix(s, "label:"); labelKey != "" {
  283. labelVal := a.GetLabels()[labelKey]
  284. if labelVal == "" {
  285. key = "__undefined__"
  286. } else {
  287. key = fmt.Sprintf("%s=%s", labelKey, labelVal)
  288. }
  289. } else {
  290. // Don't allow aggregating on label ""
  291. return "", fmt.Errorf("attempted to aggregate on invalid key: %s", s)
  292. }
  293. default:
  294. return "", fmt.Errorf("attempted to aggregate on invalid key: %s", s)
  295. }
  296. if key != "" {
  297. buffer.WriteString(key)
  298. } else {
  299. buffer.WriteString(UndefinedKey)
  300. }
  301. if i != (len(aggregateBy) - 1) {
  302. buffer.WriteString("/")
  303. }
  304. }
  305. return buffer.String(), nil
  306. }
  307. func getKeyFromLabelConfig(a Asset, labelConfig *LabelConfig, label string) string {
  308. labels := a.GetLabels()
  309. if labels == nil {
  310. return UnallocatedSuffix
  311. } else {
  312. key := UnallocatedSuffix
  313. labelNames := strings.Split(label, ",")
  314. for _, labelName := range labelNames {
  315. name := labelConfig.Sanitize(labelName)
  316. if labelValue, ok := labels[name]; ok {
  317. key = labelValue
  318. break
  319. }
  320. }
  321. return key
  322. }
  323. }
  324. func GetAssetKey(a Asset, aggregateBy []string) (string, error) {
  325. return key(a, aggregateBy, nil)
  326. }
  327. func toString(a Asset) string {
  328. return fmt.Sprintf("%s{%s}%s=%.2f", a.Type().String(), a.GetProperties(), a.GetWindow(), a.TotalCost())
  329. }
  330. // AssetLabels is a schema-free mapping of key/value pairs that can be
  331. // attributed to an Asset as a flexible a
  332. type AssetLabels map[string]string
  333. // Clone returns a cloned map of labels
  334. func (al AssetLabels) Clone() AssetLabels {
  335. clone := make(AssetLabels, len(al))
  336. for label, value := range al {
  337. clone[label] = value
  338. }
  339. return clone
  340. }
  341. // Equal returns true only if the two set of labels are exact matches
  342. func (al AssetLabels) Equal(that AssetLabels) bool {
  343. if len(al) != len(that) {
  344. return false
  345. }
  346. for label, value := range al {
  347. if thatValue, ok := that[label]; !ok || thatValue != value {
  348. return false
  349. }
  350. }
  351. return true
  352. }
  353. // Merge retains only the labels shared with the given AssetLabels
  354. func (al AssetLabels) Merge(that AssetLabels) AssetLabels {
  355. result := AssetLabels{}
  356. for label, value := range al {
  357. if thatValue, ok := that[label]; ok && thatValue == value {
  358. result[label] = value
  359. }
  360. }
  361. return result
  362. }
  363. // Append joins AssetLabels with a given map of labels
  364. func (al AssetLabels) Append(newLabels map[string]string, overwrite bool) {
  365. if len(newLabels) == 0 {
  366. return
  367. }
  368. for label, value := range newLabels {
  369. if _, ok := al[label]; ok {
  370. if overwrite {
  371. al[label] = value
  372. }
  373. } else {
  374. al[label] = value
  375. }
  376. }
  377. }
  378. // AssetMatchFunc is a function that can be used to match Assets by
  379. // returning true for any given Asset if a condition is met.
  380. type AssetMatchFunc func(Asset) bool
  381. // AssetType identifies a type of Asset
  382. type AssetType int
  383. const (
  384. // AnyAssetType describes the Any AssetType
  385. AnyAssetType AssetType = iota
  386. // CloudAssetType describes the Cloud AssetType
  387. CloudAssetType
  388. // ClusterManagementAssetType describes the ClusterManagement AssetType
  389. ClusterManagementAssetType
  390. // DiskAssetType describes the Disk AssetType
  391. DiskAssetType
  392. // LoadBalancerAssetType describes the LoadBalancer AssetType
  393. LoadBalancerAssetType
  394. // NetworkAssetType describes the Network AssetType
  395. NetworkAssetType
  396. // NodeAssetType describes the Node AssetType
  397. NodeAssetType
  398. // SharedAssetType describes the Shared AssetType
  399. SharedAssetType
  400. )
  401. // ParseAssetType attempts to parse the given string into an AssetType
  402. func ParseAssetType(text string) (AssetType, error) {
  403. switch strings.TrimSpace(strings.ToLower(text)) {
  404. case "cloud":
  405. return CloudAssetType, nil
  406. case "clustermanagement":
  407. return ClusterManagementAssetType, nil
  408. case "disk":
  409. return DiskAssetType, nil
  410. case "loadbalancer":
  411. return LoadBalancerAssetType, nil
  412. case "network":
  413. return NetworkAssetType, nil
  414. case "node":
  415. return NodeAssetType, nil
  416. case "shared":
  417. return SharedAssetType, nil
  418. }
  419. return AnyAssetType, fmt.Errorf("invalid asset type: %s", text)
  420. }
  421. // String converts the given AssetType to a string
  422. func (at AssetType) String() string {
  423. return [...]string{
  424. "Asset",
  425. "Cloud",
  426. "ClusterManagement",
  427. "Disk",
  428. "LoadBalancer",
  429. "Network",
  430. "Node",
  431. "Shared",
  432. }[at]
  433. }
  434. // Any is the most general Asset, which is usually created as a result of
  435. // adding two Assets of different types.
  436. type Any struct {
  437. Labels AssetLabels
  438. Properties *AssetProperties
  439. Start time.Time
  440. End time.Time
  441. Window Window
  442. Adjustment float64
  443. Cost float64
  444. }
  445. // NewAsset creates a new Any-type Asset for the given period of time
  446. func NewAsset(start, end time.Time, window Window) *Any {
  447. return &Any{
  448. Labels: AssetLabels{},
  449. Properties: &AssetProperties{},
  450. Start: start,
  451. End: end,
  452. Window: window.Clone(),
  453. }
  454. }
  455. // Type returns the Asset's type
  456. func (a *Any) Type() AssetType {
  457. return AnyAssetType
  458. }
  459. // Properties returns the Asset's Properties
  460. func (a *Any) GetProperties() *AssetProperties {
  461. return a.Properties
  462. }
  463. // SetProperties sets the Asset's Properties
  464. func (a *Any) SetProperties(props *AssetProperties) {
  465. a.Properties = props
  466. }
  467. // Labels returns the Asset's labels
  468. func (a *Any) GetLabels() AssetLabels {
  469. return a.Labels
  470. }
  471. // SetLabels sets the Asset's labels
  472. func (a *Any) SetLabels(labels AssetLabels) {
  473. a.Labels = labels
  474. }
  475. // Adjustment returns the Asset's cost adjustment
  476. func (a *Any) GetAdjustment() float64 {
  477. return a.Adjustment
  478. }
  479. // SetAdjustment sets the Asset's cost adjustment
  480. func (a *Any) SetAdjustment(adj float64) {
  481. a.Adjustment = adj
  482. }
  483. // TotalCost returns the Asset's TotalCost
  484. func (a *Any) TotalCost() float64 {
  485. return a.Cost + a.Adjustment
  486. }
  487. // Start returns the Asset's start time within the window
  488. func (a *Any) GetStart() time.Time {
  489. return a.Start
  490. }
  491. // End returns the Asset's end time within the window
  492. func (a *Any) GetEnd() time.Time {
  493. return a.End
  494. }
  495. // Minutes returns the number of minutes the Asset was active within the window
  496. func (a *Any) Minutes() float64 {
  497. return a.End.Sub(a.Start).Minutes()
  498. }
  499. // Window returns the Asset's window
  500. func (a *Any) GetWindow() Window {
  501. return a.Window
  502. }
  503. func (a *Any) SetWindow(window Window) {
  504. a.Window = window
  505. }
  506. // ExpandWindow expands the Asset's window by the given window
  507. func (a *Any) ExpandWindow(window Window) {
  508. a.Window = a.Window.Expand(window)
  509. }
  510. // SetStartEnd sets the Asset's Start and End fields
  511. func (a *Any) SetStartEnd(start, end time.Time) {
  512. if a.Window.Contains(start) {
  513. a.Start = start
  514. } else {
  515. log.Warnf("Any.SetStartEnd: start %s not in %s", start, a.Window)
  516. }
  517. if a.Window.Contains(end) {
  518. a.End = end
  519. } else {
  520. log.Warnf("Any.SetStartEnd: end %s not in %s", end, a.Window)
  521. }
  522. }
  523. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  524. // as much relevant information as possible (i.e. type, Properties, labels).
  525. func (a *Any) Add(that Asset) Asset {
  526. this := a.Clone().(*Any)
  527. props := a.Properties.Merge(that.GetProperties())
  528. labels := a.Labels.Merge(that.GetLabels())
  529. start := a.Start
  530. if that.GetStart().Before(start) {
  531. start = that.GetStart()
  532. }
  533. end := a.End
  534. if that.GetEnd().After(end) {
  535. end = that.GetEnd()
  536. }
  537. window := a.Window.Expand(that.GetWindow())
  538. this.Start = start
  539. this.End = end
  540. this.Window = window
  541. this.SetProperties(props)
  542. this.SetLabels(labels)
  543. this.Adjustment += that.GetAdjustment()
  544. this.Cost += (that.TotalCost() - that.GetAdjustment())
  545. return this
  546. }
  547. // Clone returns a cloned instance of the Asset
  548. func (a *Any) Clone() Asset {
  549. return &Any{
  550. Labels: a.Labels.Clone(),
  551. Properties: a.Properties.Clone(),
  552. Start: a.Start,
  553. End: a.End,
  554. Window: a.Window.Clone(),
  555. Adjustment: a.Adjustment,
  556. Cost: a.Cost,
  557. }
  558. }
  559. // Equal returns true if the given Asset is an exact match of the receiver
  560. func (a *Any) Equal(that Asset) bool {
  561. t, ok := that.(*Any)
  562. if !ok {
  563. return false
  564. }
  565. if !a.Labels.Equal(t.Labels) {
  566. return false
  567. }
  568. if !a.Properties.Equal(t.Properties) {
  569. return false
  570. }
  571. if !a.Start.Equal(t.Start) {
  572. return false
  573. }
  574. if !a.End.Equal(t.End) {
  575. return false
  576. }
  577. if !a.Window.Equal(t.Window) {
  578. return false
  579. }
  580. if a.Cost != t.Cost {
  581. return false
  582. }
  583. return true
  584. }
  585. // String implements fmt.Stringer
  586. func (a *Any) String() string {
  587. return toString(a)
  588. }
  589. // Cloud describes a cloud asset
  590. type Cloud struct {
  591. Labels AssetLabels
  592. Properties *AssetProperties
  593. Start time.Time
  594. End time.Time
  595. Window Window
  596. Adjustment float64
  597. Cost float64
  598. Credit float64 // Credit is a negative value representing dollars credited back to a given line-item
  599. }
  600. // NewCloud returns a new Cloud Asset
  601. func NewCloud(category, providerID string, start, end time.Time, window Window) *Cloud {
  602. properties := &AssetProperties{
  603. Category: category,
  604. ProviderID: providerID,
  605. }
  606. return &Cloud{
  607. Labels: AssetLabels{},
  608. Properties: properties,
  609. Start: start,
  610. End: end,
  611. Window: window.Clone(),
  612. }
  613. }
  614. // Type returns the AssetType
  615. func (ca *Cloud) Type() AssetType {
  616. return CloudAssetType
  617. }
  618. // Properties returns the AssetProperties
  619. func (ca *Cloud) GetProperties() *AssetProperties {
  620. return ca.Properties
  621. }
  622. // SetProperties sets the Asset's Properties
  623. func (ca *Cloud) SetProperties(props *AssetProperties) {
  624. ca.Properties = props
  625. }
  626. // Labels returns the AssetLabels
  627. func (ca *Cloud) GetLabels() AssetLabels {
  628. return ca.Labels
  629. }
  630. // SetLabels sets the Asset's labels
  631. func (ca *Cloud) SetLabels(labels AssetLabels) {
  632. ca.Labels = labels
  633. }
  634. // Adjustment returns the Asset's adjustment value
  635. func (ca *Cloud) GetAdjustment() float64 {
  636. return ca.Adjustment
  637. }
  638. // SetAdjustment sets the Asset's adjustment value
  639. func (ca *Cloud) SetAdjustment(adj float64) {
  640. ca.Adjustment = adj
  641. }
  642. // TotalCost returns the Asset's total cost
  643. func (ca *Cloud) TotalCost() float64 {
  644. return ca.Cost + ca.Adjustment + ca.Credit
  645. }
  646. // Start returns the Asset's precise start time within the window
  647. func (ca *Cloud) GetStart() time.Time {
  648. return ca.Start
  649. }
  650. // End returns the Asset's precise end time within the window
  651. func (ca *Cloud) GetEnd() time.Time {
  652. return ca.End
  653. }
  654. // Minutes returns the number of Minutes the Asset ran
  655. func (ca *Cloud) Minutes() float64 {
  656. return ca.End.Sub(ca.Start).Minutes()
  657. }
  658. // Window returns the window within which the Asset ran
  659. func (ca *Cloud) GetWindow() Window {
  660. return ca.Window
  661. }
  662. func (ca *Cloud) SetWindow(window Window) {
  663. ca.Window = window
  664. }
  665. // ExpandWindow expands the Asset's window by the given window
  666. func (ca *Cloud) ExpandWindow(window Window) {
  667. ca.Window = ca.Window.Expand(window)
  668. }
  669. // SetStartEnd sets the Asset's Start and End fields
  670. func (ca *Cloud) SetStartEnd(start, end time.Time) {
  671. if ca.Window.Contains(start) {
  672. ca.Start = start
  673. } else {
  674. log.Warnf("Cloud.SetStartEnd: start %s not in %s", start, ca.Window)
  675. }
  676. if ca.Window.Contains(end) {
  677. ca.End = end
  678. } else {
  679. log.Warnf("Cloud.SetStartEnd: end %s not in %s", end, ca.Window)
  680. }
  681. }
  682. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  683. // as much relevant information as possible (i.e. type, Properties, labels).
  684. func (ca *Cloud) Add(a Asset) Asset {
  685. // Cloud + Cloud = Cloud
  686. if that, ok := a.(*Cloud); ok {
  687. this := ca.Clone().(*Cloud)
  688. this.add(that)
  689. return this
  690. }
  691. props := ca.Properties.Merge(a.GetProperties())
  692. labels := ca.Labels.Merge(a.GetLabels())
  693. start := ca.Start
  694. if a.GetStart().Before(start) {
  695. start = a.GetStart()
  696. }
  697. end := ca.End
  698. if a.GetEnd().After(end) {
  699. end = a.GetEnd()
  700. }
  701. window := ca.Window.Expand(a.GetWindow())
  702. // Cloud + !Cloud = Any
  703. any := NewAsset(start, end, window)
  704. any.SetProperties(props)
  705. any.SetLabels(labels)
  706. any.Adjustment = ca.Adjustment + a.GetAdjustment()
  707. any.Cost = (ca.TotalCost() - ca.Adjustment) + (a.TotalCost() - a.GetAdjustment())
  708. return any
  709. }
  710. func (ca *Cloud) add(that *Cloud) {
  711. if ca == nil {
  712. ca = that
  713. return
  714. }
  715. props := ca.Properties.Merge(that.Properties)
  716. labels := ca.Labels.Merge(that.Labels)
  717. start := ca.Start
  718. if that.Start.Before(start) {
  719. start = that.Start
  720. }
  721. end := ca.End
  722. if that.End.After(end) {
  723. end = that.End
  724. }
  725. window := ca.Window.Expand(that.Window)
  726. ca.Start = start
  727. ca.End = end
  728. ca.Window = window
  729. ca.SetProperties(props)
  730. ca.SetLabels(labels)
  731. ca.Adjustment += that.Adjustment
  732. ca.Cost += that.Cost
  733. ca.Credit += that.Credit
  734. }
  735. // Clone returns a cloned instance of the Asset
  736. func (ca *Cloud) Clone() Asset {
  737. return &Cloud{
  738. Labels: ca.Labels.Clone(),
  739. Properties: ca.Properties.Clone(),
  740. Start: ca.Start,
  741. End: ca.End,
  742. Window: ca.Window.Clone(),
  743. Adjustment: ca.Adjustment,
  744. Cost: ca.Cost,
  745. Credit: ca.Credit,
  746. }
  747. }
  748. // Equal returns true if the given Asset precisely equals the Asset
  749. func (ca *Cloud) Equal(a Asset) bool {
  750. that, ok := a.(*Cloud)
  751. if !ok {
  752. return false
  753. }
  754. if !ca.Labels.Equal(that.Labels) {
  755. return false
  756. }
  757. if !ca.Properties.Equal(that.Properties) {
  758. return false
  759. }
  760. if !ca.Start.Equal(that.Start) {
  761. return false
  762. }
  763. if !ca.End.Equal(that.End) {
  764. return false
  765. }
  766. if !ca.Window.Equal(that.Window) {
  767. return false
  768. }
  769. if ca.Adjustment != that.Adjustment {
  770. return false
  771. }
  772. if ca.Cost != that.Cost {
  773. return false
  774. }
  775. if ca.Credit != that.Credit {
  776. return false
  777. }
  778. return true
  779. }
  780. // String implements fmt.Stringer
  781. func (ca *Cloud) String() string {
  782. return toString(ca)
  783. }
  784. // ClusterManagement describes a provider's cluster management fee
  785. type ClusterManagement struct {
  786. Labels AssetLabels
  787. Properties *AssetProperties
  788. Window Window
  789. Cost float64
  790. Adjustment float64 // @bingen:field[version=16]
  791. }
  792. // NewClusterManagement creates and returns a new ClusterManagement instance
  793. func NewClusterManagement(provider, cluster string, window Window) *ClusterManagement {
  794. properties := &AssetProperties{
  795. Category: ManagementCategory,
  796. Provider: ParseProvider(provider),
  797. Cluster: cluster,
  798. Service: KubernetesService,
  799. }
  800. return &ClusterManagement{
  801. Labels: AssetLabels{},
  802. Properties: properties,
  803. Window: window.Clone(),
  804. }
  805. }
  806. // Type returns the Asset's type
  807. func (cm *ClusterManagement) Type() AssetType {
  808. return ClusterManagementAssetType
  809. }
  810. // Properties returns the Asset's Properties
  811. func (cm *ClusterManagement) GetProperties() *AssetProperties {
  812. return cm.Properties
  813. }
  814. // SetProperties sets the Asset's Properties
  815. func (cm *ClusterManagement) SetProperties(props *AssetProperties) {
  816. cm.Properties = props
  817. }
  818. // Labels returns the Asset's labels
  819. func (cm *ClusterManagement) GetLabels() AssetLabels {
  820. return cm.Labels
  821. }
  822. // SetLabels sets the Asset's Properties
  823. func (cm *ClusterManagement) SetLabels(props AssetLabels) {
  824. cm.Labels = props
  825. }
  826. // Adjustment does not apply to ClusterManagement
  827. func (cm *ClusterManagement) GetAdjustment() float64 {
  828. return cm.Adjustment
  829. }
  830. // SetAdjustment does not apply to ClusterManagement
  831. func (cm *ClusterManagement) SetAdjustment(adj float64) {
  832. cm.Adjustment = adj
  833. }
  834. // TotalCost returns the Asset's total cost
  835. func (cm *ClusterManagement) TotalCost() float64 {
  836. return cm.Cost + cm.Adjustment
  837. }
  838. // Start returns the Asset's precise start time within the window
  839. func (cm *ClusterManagement) GetStart() time.Time {
  840. return *cm.Window.Start()
  841. }
  842. // End returns the Asset's precise end time within the window
  843. func (cm *ClusterManagement) GetEnd() time.Time {
  844. return *cm.Window.End()
  845. }
  846. // Minutes returns the number of minutes the Asset ran
  847. func (cm *ClusterManagement) Minutes() float64 {
  848. return cm.Window.Minutes()
  849. }
  850. // Window return the Asset's window
  851. func (cm *ClusterManagement) GetWindow() Window {
  852. return cm.Window
  853. }
  854. func (cm *ClusterManagement) SetWindow(window Window) {
  855. cm.Window = window
  856. }
  857. // ExpandWindow expands the Asset's window by the given window
  858. func (cm *ClusterManagement) ExpandWindow(window Window) {
  859. cm.Window = cm.Window.Expand(window)
  860. }
  861. // SetStartEnd sets the Asset's Start and End fields (not applicable here)
  862. func (cm *ClusterManagement) SetStartEnd(start, end time.Time) {
  863. return
  864. }
  865. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  866. // as much relevant information as possible (i.e. type, Properties, labels).
  867. func (cm *ClusterManagement) Add(a Asset) Asset {
  868. // ClusterManagement + ClusterManagement = ClusterManagement
  869. if that, ok := a.(*ClusterManagement); ok {
  870. this := cm.Clone().(*ClusterManagement)
  871. this.add(that)
  872. return this
  873. }
  874. props := cm.Properties.Merge(a.GetProperties())
  875. labels := cm.Labels.Merge(a.GetLabels())
  876. start := cm.GetStart()
  877. if a.GetStart().Before(start) {
  878. start = a.GetStart()
  879. }
  880. end := cm.GetEnd()
  881. if a.GetEnd().After(end) {
  882. end = a.GetEnd()
  883. }
  884. window := cm.Window.Expand(a.GetWindow())
  885. // ClusterManagement + !ClusterManagement = Any
  886. any := NewAsset(start, end, window)
  887. any.SetProperties(props)
  888. any.SetLabels(labels)
  889. any.Adjustment = cm.Adjustment + a.GetAdjustment()
  890. any.Cost = (cm.TotalCost() - cm.Adjustment) + (a.TotalCost() - a.GetAdjustment())
  891. return any
  892. }
  893. func (cm *ClusterManagement) add(that *ClusterManagement) {
  894. if cm == nil {
  895. cm = that
  896. return
  897. }
  898. props := cm.Properties.Merge(that.Properties)
  899. labels := cm.Labels.Merge(that.Labels)
  900. window := cm.Window.Expand(that.Window)
  901. cm.Window = window
  902. cm.SetProperties(props)
  903. cm.SetLabels(labels)
  904. cm.Adjustment += that.Adjustment
  905. cm.Cost += that.Cost
  906. }
  907. // Clone returns a cloned instance of the Asset
  908. func (cm *ClusterManagement) Clone() Asset {
  909. return &ClusterManagement{
  910. Labels: cm.Labels.Clone(),
  911. Properties: cm.Properties.Clone(),
  912. Window: cm.Window.Clone(),
  913. Adjustment: cm.Adjustment,
  914. Cost: cm.Cost,
  915. }
  916. }
  917. // Equal returns true if the given Asset exactly matches the Asset
  918. func (cm *ClusterManagement) Equal(a Asset) bool {
  919. that, ok := a.(*ClusterManagement)
  920. if !ok {
  921. return false
  922. }
  923. if !cm.Labels.Equal(that.Labels) {
  924. return false
  925. }
  926. if !cm.Properties.Equal(that.Properties) {
  927. return false
  928. }
  929. if !cm.Window.Equal(that.Window) {
  930. return false
  931. }
  932. if cm.Adjustment != that.Adjustment {
  933. return false
  934. }
  935. if cm.Cost != that.Cost {
  936. return false
  937. }
  938. return true
  939. }
  940. // String implements fmt.Stringer
  941. func (cm *ClusterManagement) String() string {
  942. return toString(cm)
  943. }
  944. // Disk represents an in-cluster disk Asset
  945. type Disk struct {
  946. Labels AssetLabels
  947. Properties *AssetProperties
  948. Start time.Time
  949. End time.Time
  950. Window Window
  951. Adjustment float64
  952. Cost float64
  953. ByteHours float64
  954. Local float64
  955. Breakdown *Breakdown
  956. StorageClass string // @bingen:field[version=17]
  957. ByteHoursUsed *float64 // @bingen:field[version=18]
  958. ByteUsageMax *float64 // @bingen:field[version=18]
  959. VolumeName string // @bingen:field[version=18]
  960. ClaimName string // @bingen:field[version=18]
  961. ClaimNamespace string // @bingen:field[version=18]
  962. }
  963. // NewDisk creates and returns a new Disk Asset
  964. func NewDisk(name, cluster, providerID string, start, end time.Time, window Window) *Disk {
  965. properties := &AssetProperties{
  966. Category: StorageCategory,
  967. Name: name,
  968. Cluster: cluster,
  969. ProviderID: providerID,
  970. Service: KubernetesService,
  971. }
  972. return &Disk{
  973. Labels: AssetLabels{},
  974. Properties: properties,
  975. Start: start,
  976. End: end,
  977. Window: window,
  978. Breakdown: &Breakdown{},
  979. }
  980. }
  981. // Type returns the AssetType of the Asset
  982. func (d *Disk) Type() AssetType {
  983. return DiskAssetType
  984. }
  985. // Properties returns the Asset's Properties
  986. func (d *Disk) GetProperties() *AssetProperties {
  987. return d.Properties
  988. }
  989. // SetProperties sets the Asset's Properties
  990. func (d *Disk) SetProperties(props *AssetProperties) {
  991. d.Properties = props
  992. }
  993. // Labels returns the Asset's labels
  994. func (d *Disk) GetLabels() AssetLabels {
  995. return d.Labels
  996. }
  997. // SetLabels sets the Asset's labels
  998. func (d *Disk) SetLabels(labels AssetLabels) {
  999. d.Labels = labels
  1000. }
  1001. // Adjustment returns the Asset's cost adjustment
  1002. func (d *Disk) GetAdjustment() float64 {
  1003. return d.Adjustment
  1004. }
  1005. // SetAdjustment sets the Asset's cost adjustment
  1006. func (d *Disk) SetAdjustment(adj float64) {
  1007. d.Adjustment = adj
  1008. }
  1009. // TotalCost returns the Asset's total cost
  1010. func (d *Disk) TotalCost() float64 {
  1011. return d.Cost + d.Adjustment
  1012. }
  1013. // Start returns the precise start time of the Asset within the window
  1014. func (d *Disk) GetStart() time.Time {
  1015. return d.Start
  1016. }
  1017. // End returns the precise start time of the Asset within the window
  1018. func (d *Disk) GetEnd() time.Time {
  1019. return d.End
  1020. }
  1021. // Minutes returns the number of minutes the Asset ran
  1022. func (d *Disk) Minutes() float64 {
  1023. diskMins := d.End.Sub(d.Start).Minutes()
  1024. windowMins := d.Window.Minutes()
  1025. if diskMins > windowMins {
  1026. log.Warnf("Asset ETL: Disk.Minutes exceeds window: %.2f > %.2f", diskMins, windowMins)
  1027. diskMins = windowMins
  1028. }
  1029. if diskMins < 0 {
  1030. diskMins = 0
  1031. }
  1032. return diskMins
  1033. }
  1034. // Window returns the window within which the Asset
  1035. func (d *Disk) GetWindow() Window {
  1036. return d.Window
  1037. }
  1038. func (d *Disk) SetWindow(window Window) {
  1039. d.Window = window
  1040. }
  1041. // ExpandWindow expands the Asset's window by the given window
  1042. func (d *Disk) ExpandWindow(window Window) {
  1043. d.Window = d.Window.Expand(window)
  1044. }
  1045. // SetStartEnd sets the Asset's Start and End fields
  1046. func (d *Disk) SetStartEnd(start, end time.Time) {
  1047. if d.Window.Contains(start) {
  1048. d.Start = start
  1049. } else {
  1050. log.Warnf("Disk.SetStartEnd: start %s not in %s", start, d.Window)
  1051. }
  1052. if d.Window.Contains(end) {
  1053. d.End = end
  1054. } else {
  1055. log.Warnf("Disk.SetStartEnd: end %s not in %s", end, d.Window)
  1056. }
  1057. }
  1058. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  1059. // as much relevant information as possible (i.e. type, Properties, labels).
  1060. func (d *Disk) Add(a Asset) Asset {
  1061. // Disk + Disk = Disk
  1062. if that, ok := a.(*Disk); ok {
  1063. this := d.Clone().(*Disk)
  1064. this.add(that)
  1065. return this
  1066. }
  1067. props := d.Properties.Merge(a.GetProperties())
  1068. labels := d.Labels.Merge(a.GetLabels())
  1069. start := d.Start
  1070. if a.GetStart().Before(start) {
  1071. start = a.GetStart()
  1072. }
  1073. end := d.End
  1074. if a.GetEnd().After(end) {
  1075. end = a.GetEnd()
  1076. }
  1077. window := d.Window.Expand(a.GetWindow())
  1078. // Disk + !Disk = Any
  1079. any := NewAsset(start, end, window)
  1080. any.SetProperties(props)
  1081. any.SetLabels(labels)
  1082. any.Adjustment = d.Adjustment + a.GetAdjustment()
  1083. any.Cost = (d.TotalCost() - d.Adjustment) + (a.TotalCost() - a.GetAdjustment())
  1084. return any
  1085. }
  1086. func (d *Disk) add(that *Disk) {
  1087. if d == nil {
  1088. d = that
  1089. return
  1090. }
  1091. props := d.Properties.Merge(that.Properties)
  1092. labels := d.Labels.Merge(that.Labels)
  1093. d.SetProperties(props)
  1094. d.SetLabels(labels)
  1095. start := d.Start
  1096. if that.Start.Before(start) {
  1097. start = that.Start
  1098. }
  1099. end := d.End
  1100. if that.End.After(end) {
  1101. end = that.End
  1102. }
  1103. window := d.Window.Expand(that.Window)
  1104. d.Start = start
  1105. d.End = end
  1106. d.Window = window
  1107. totalCost := d.Cost + that.Cost
  1108. if totalCost > 0.0 {
  1109. d.Breakdown.Idle = (d.Breakdown.Idle*d.Cost + that.Breakdown.Idle*that.Cost) / totalCost
  1110. d.Breakdown.Other = (d.Breakdown.Other*d.Cost + that.Breakdown.Other*that.Cost) / totalCost
  1111. d.Breakdown.System = (d.Breakdown.System*d.Cost + that.Breakdown.System*that.Cost) / totalCost
  1112. d.Breakdown.User = (d.Breakdown.User*d.Cost + that.Breakdown.User*that.Cost) / totalCost
  1113. d.Local = (d.TotalCost()*d.Local + that.TotalCost()*that.Local) / (d.TotalCost() + that.TotalCost())
  1114. } else {
  1115. d.Local = (d.Local + that.Local) / 2.0
  1116. }
  1117. d.Adjustment += that.Adjustment
  1118. d.Cost += that.Cost
  1119. d.ByteHours += that.ByteHours
  1120. if d.ByteHoursUsed == nil && that.ByteHoursUsed != nil {
  1121. copy := *that.ByteHoursUsed
  1122. d.ByteHoursUsed = &copy
  1123. } else if d.ByteHoursUsed != nil && that.ByteHoursUsed == nil {
  1124. // do nothing
  1125. } else if d.ByteHoursUsed != nil && that.ByteHoursUsed != nil {
  1126. sum := *d.ByteHoursUsed
  1127. sum += *that.ByteHoursUsed
  1128. d.ByteHoursUsed = &sum
  1129. }
  1130. // We have to nil out the max because we don't know if we're
  1131. // aggregating across time our properties. See RawAllocationOnly on
  1132. // Allocation for further reference.
  1133. d.ByteUsageMax = nil
  1134. // If storage class don't match default it to empty storage class
  1135. if d.StorageClass != that.StorageClass {
  1136. d.StorageClass = ""
  1137. }
  1138. if d.VolumeName != that.VolumeName {
  1139. d.VolumeName = ""
  1140. }
  1141. if d.ClaimName != that.ClaimName {
  1142. d.ClaimName = ""
  1143. }
  1144. if d.ClaimNamespace != that.ClaimNamespace {
  1145. d.ClaimNamespace = ""
  1146. }
  1147. }
  1148. // Clone returns a cloned instance of the Asset
  1149. func (d *Disk) Clone() Asset {
  1150. var max *float64
  1151. if d.ByteUsageMax != nil {
  1152. copied := *d.ByteUsageMax
  1153. max = &copied
  1154. }
  1155. var byteHoursUsed *float64
  1156. if d.ByteHoursUsed != nil {
  1157. copied := *d.ByteHoursUsed
  1158. byteHoursUsed = &copied
  1159. }
  1160. return &Disk{
  1161. Properties: d.Properties.Clone(),
  1162. Labels: d.Labels.Clone(),
  1163. Start: d.Start,
  1164. End: d.End,
  1165. Window: d.Window.Clone(),
  1166. Adjustment: d.Adjustment,
  1167. Cost: d.Cost,
  1168. ByteHours: d.ByteHours,
  1169. ByteHoursUsed: byteHoursUsed,
  1170. ByteUsageMax: max,
  1171. Local: d.Local,
  1172. Breakdown: d.Breakdown.Clone(),
  1173. StorageClass: d.StorageClass,
  1174. VolumeName: d.VolumeName,
  1175. ClaimName: d.ClaimName,
  1176. ClaimNamespace: d.ClaimNamespace,
  1177. }
  1178. }
  1179. // Equal returns true if the two Assets match exactly
  1180. func (d *Disk) Equal(a Asset) bool {
  1181. that, ok := a.(*Disk)
  1182. if !ok {
  1183. return false
  1184. }
  1185. if !d.Labels.Equal(that.Labels) {
  1186. return false
  1187. }
  1188. if !d.Properties.Equal(that.Properties) {
  1189. return false
  1190. }
  1191. if !d.Start.Equal(that.Start) {
  1192. return false
  1193. }
  1194. if !d.End.Equal(that.End) {
  1195. return false
  1196. }
  1197. if !d.Window.Equal(that.Window) {
  1198. return false
  1199. }
  1200. if d.Adjustment != that.Adjustment {
  1201. return false
  1202. }
  1203. if d.Cost != that.Cost {
  1204. return false
  1205. }
  1206. if d.ByteHours != that.ByteHours {
  1207. return false
  1208. }
  1209. if d.ByteHoursUsed != nil && that.ByteHoursUsed == nil {
  1210. return false
  1211. }
  1212. if d.ByteHoursUsed == nil && that.ByteHoursUsed != nil {
  1213. return false
  1214. }
  1215. if (d.ByteHoursUsed != nil && that.ByteHoursUsed != nil) && *d.ByteHoursUsed != *that.ByteHoursUsed {
  1216. return false
  1217. }
  1218. if d.ByteUsageMax != nil && that.ByteUsageMax == nil {
  1219. return false
  1220. }
  1221. if d.ByteUsageMax == nil && that.ByteUsageMax != nil {
  1222. return false
  1223. }
  1224. if (d.ByteUsageMax != nil && that.ByteUsageMax != nil) && *d.ByteUsageMax != *that.ByteUsageMax {
  1225. return false
  1226. }
  1227. if d.Local != that.Local {
  1228. return false
  1229. }
  1230. if !d.Breakdown.Equal(that.Breakdown) {
  1231. return false
  1232. }
  1233. if d.StorageClass != that.StorageClass {
  1234. return false
  1235. }
  1236. if d.VolumeName != that.VolumeName {
  1237. return false
  1238. }
  1239. if d.ClaimName != that.ClaimName {
  1240. return false
  1241. }
  1242. if d.ClaimNamespace != that.ClaimNamespace {
  1243. return false
  1244. }
  1245. return true
  1246. }
  1247. // String implements fmt.Stringer
  1248. func (d *Disk) String() string {
  1249. return toString(d)
  1250. }
  1251. // Bytes returns the number of bytes belonging to the disk. This could be
  1252. // fractional because it's the number of byte*hours divided by the number of
  1253. // hours running; e.g. the sum of a 100GiB disk running for the first 10 hours
  1254. // and a 30GiB disk running for the last 20 hours of the same 24-hour window
  1255. // would produce:
  1256. //
  1257. // (100*10 + 30*20) / 24 = 66.667GiB
  1258. //
  1259. // However, any number of disks running for the full span of a window will
  1260. // report the actual number of bytes of the static disk; e.g. the above
  1261. // scenario for one entire 24-hour window:
  1262. //
  1263. // (100*24 + 30*24) / 24 = (100 + 30) = 130GiB
  1264. func (d *Disk) Bytes() float64 {
  1265. // [b*hr]*([min/hr]*[1/min]) = [b*hr]/[hr] = b
  1266. return d.ByteHours * (60.0 / d.Minutes())
  1267. }
  1268. // Breakdown describes a resource's use as a percentage of various usage types
  1269. type Breakdown struct {
  1270. Idle float64 `json:"idle"`
  1271. Other float64 `json:"other"`
  1272. System float64 `json:"system"`
  1273. User float64 `json:"user"`
  1274. }
  1275. // Clone returns a cloned instance of the Breakdown
  1276. func (b *Breakdown) Clone() *Breakdown {
  1277. if b == nil {
  1278. return nil
  1279. }
  1280. return &Breakdown{
  1281. Idle: b.Idle,
  1282. Other: b.Other,
  1283. System: b.System,
  1284. User: b.User,
  1285. }
  1286. }
  1287. // Equal returns true if the two Breakdowns are exact matches
  1288. func (b *Breakdown) Equal(that *Breakdown) bool {
  1289. if b == nil || that == nil {
  1290. return false
  1291. }
  1292. if b.Idle != that.Idle {
  1293. return false
  1294. }
  1295. if b.Other != that.Other {
  1296. return false
  1297. }
  1298. if b.System != that.System {
  1299. return false
  1300. }
  1301. if b.User != that.User {
  1302. return false
  1303. }
  1304. return true
  1305. }
  1306. // Network is an Asset representing a single node's network costs
  1307. type Network struct {
  1308. Properties *AssetProperties
  1309. Labels AssetLabels
  1310. Start time.Time
  1311. End time.Time
  1312. Window Window
  1313. Adjustment float64
  1314. Cost float64
  1315. }
  1316. // NewNetwork creates and returns a new Network Asset
  1317. func NewNetwork(name, cluster, providerID string, start, end time.Time, window Window) *Network {
  1318. properties := &AssetProperties{
  1319. Category: NetworkCategory,
  1320. Name: name,
  1321. Cluster: cluster,
  1322. ProviderID: providerID,
  1323. Service: KubernetesService,
  1324. }
  1325. return &Network{
  1326. Properties: properties,
  1327. Labels: AssetLabels{},
  1328. Start: start,
  1329. End: end,
  1330. Window: window.Clone(),
  1331. }
  1332. }
  1333. // Type returns the AssetType of the Asset
  1334. func (n *Network) Type() AssetType {
  1335. return NetworkAssetType
  1336. }
  1337. // Properties returns the Asset's Properties
  1338. func (n *Network) GetProperties() *AssetProperties {
  1339. return n.Properties
  1340. }
  1341. // SetProperties sets the Asset's Properties
  1342. func (n *Network) SetProperties(props *AssetProperties) {
  1343. n.Properties = props
  1344. }
  1345. // Labels returns the Asset's labels
  1346. func (n *Network) GetLabels() AssetLabels {
  1347. return n.Labels
  1348. }
  1349. // SetLabels sets the Asset's labels
  1350. func (n *Network) SetLabels(labels AssetLabels) {
  1351. n.Labels = labels
  1352. }
  1353. // Adjustment returns the Asset's cost adjustment
  1354. func (n *Network) GetAdjustment() float64 {
  1355. return n.Adjustment
  1356. }
  1357. // SetAdjustment sets the Asset's cost adjustment
  1358. func (n *Network) SetAdjustment(adj float64) {
  1359. n.Adjustment = adj
  1360. }
  1361. // TotalCost returns the Asset's total cost
  1362. func (n *Network) TotalCost() float64 {
  1363. return n.Cost + n.Adjustment
  1364. }
  1365. // Start returns the precise start time of the Asset within the window
  1366. func (n *Network) GetStart() time.Time {
  1367. return n.Start
  1368. }
  1369. // End returns the precise end time of the Asset within the window
  1370. func (n *Network) GetEnd() time.Time {
  1371. return n.End
  1372. }
  1373. // Minutes returns the number of minutes the Asset ran within the window
  1374. func (n *Network) Minutes() float64 {
  1375. netMins := n.End.Sub(n.Start).Minutes()
  1376. windowMins := n.Window.Minutes()
  1377. if netMins > windowMins {
  1378. log.Warnf("Asset ETL: Network.Minutes exceeds window: %.2f > %.2f", netMins, windowMins)
  1379. netMins = windowMins
  1380. }
  1381. if netMins < 0 {
  1382. netMins = 0
  1383. }
  1384. return netMins
  1385. }
  1386. // Window returns the window within which the Asset ran
  1387. func (n *Network) GetWindow() Window {
  1388. return n.Window
  1389. }
  1390. func (n *Network) SetWindow(window Window) {
  1391. n.Window = window
  1392. }
  1393. // ExpandWindow expands the Asset's window by the given window
  1394. func (n *Network) ExpandWindow(window Window) {
  1395. n.Window = n.Window.Expand(window)
  1396. }
  1397. // SetStartEnd sets the Asset's Start and End fields
  1398. func (n *Network) SetStartEnd(start, end time.Time) {
  1399. if n.Window.Contains(start) {
  1400. n.Start = start
  1401. } else {
  1402. log.Warnf("Disk.SetStartEnd: start %s not in %s", start, n.Window)
  1403. }
  1404. if n.Window.Contains(end) {
  1405. n.End = end
  1406. } else {
  1407. log.Warnf("Disk.SetStartEnd: end %s not in %s", end, n.Window)
  1408. }
  1409. }
  1410. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  1411. // as much relevant information as possible (i.e. type, Properties, labels).
  1412. func (n *Network) Add(a Asset) Asset {
  1413. // Network + Network = Network
  1414. if that, ok := a.(*Network); ok {
  1415. this := n.Clone().(*Network)
  1416. this.add(that)
  1417. return this
  1418. }
  1419. props := n.Properties.Merge(a.GetProperties())
  1420. labels := n.Labels.Merge(a.GetLabels())
  1421. start := n.Start
  1422. if a.GetStart().Before(start) {
  1423. start = a.GetStart()
  1424. }
  1425. end := n.End
  1426. if a.GetEnd().After(end) {
  1427. end = a.GetEnd()
  1428. }
  1429. window := n.Window.Expand(a.GetWindow())
  1430. // Network + !Network = Any
  1431. any := NewAsset(start, end, window)
  1432. any.SetProperties(props)
  1433. any.SetLabels(labels)
  1434. any.Adjustment = n.Adjustment + a.GetAdjustment()
  1435. any.Cost = (n.TotalCost() - n.Adjustment) + (a.TotalCost() - a.GetAdjustment())
  1436. return any
  1437. }
  1438. func (n *Network) add(that *Network) {
  1439. if n == nil {
  1440. n = that
  1441. return
  1442. }
  1443. props := n.Properties.Merge(that.Properties)
  1444. labels := n.Labels.Merge(that.Labels)
  1445. n.SetProperties(props)
  1446. n.SetLabels(labels)
  1447. start := n.Start
  1448. if that.Start.Before(start) {
  1449. start = that.Start
  1450. }
  1451. end := n.End
  1452. if that.End.After(end) {
  1453. end = that.End
  1454. }
  1455. window := n.Window.Expand(that.Window)
  1456. n.Start = start
  1457. n.End = end
  1458. n.Window = window
  1459. n.Cost += that.Cost
  1460. n.Adjustment += that.Adjustment
  1461. }
  1462. // Clone returns a deep copy of the given Network
  1463. func (n *Network) Clone() Asset {
  1464. if n == nil {
  1465. return nil
  1466. }
  1467. return &Network{
  1468. Properties: n.Properties.Clone(),
  1469. Labels: n.Labels.Clone(),
  1470. Start: n.Start,
  1471. End: n.End,
  1472. Window: n.Window.Clone(),
  1473. Adjustment: n.Adjustment,
  1474. Cost: n.Cost,
  1475. }
  1476. }
  1477. // Equal returns true if the tow Assets match exactly
  1478. func (n *Network) Equal(a Asset) bool {
  1479. that, ok := a.(*Network)
  1480. if !ok {
  1481. return false
  1482. }
  1483. if !n.Labels.Equal(that.Labels) {
  1484. return false
  1485. }
  1486. if !n.Properties.Equal(that.Properties) {
  1487. return false
  1488. }
  1489. if !n.Start.Equal(that.Start) {
  1490. return false
  1491. }
  1492. if !n.End.Equal(that.End) {
  1493. return false
  1494. }
  1495. if !n.Window.Equal(that.Window) {
  1496. return false
  1497. }
  1498. if n.Adjustment != that.Adjustment {
  1499. return false
  1500. }
  1501. if n.Cost != that.Cost {
  1502. return false
  1503. }
  1504. return true
  1505. }
  1506. // String implements fmt.Stringer
  1507. func (n *Network) String() string {
  1508. return toString(n)
  1509. }
  1510. // Node is an Asset representing a single node in a cluster
  1511. type Node struct {
  1512. Properties *AssetProperties
  1513. Labels AssetLabels
  1514. Start time.Time
  1515. End time.Time
  1516. Window Window
  1517. Adjustment float64
  1518. NodeType string
  1519. CPUCoreHours float64
  1520. RAMByteHours float64
  1521. GPUHours float64
  1522. CPUBreakdown *Breakdown
  1523. RAMBreakdown *Breakdown
  1524. CPUCost float64
  1525. GPUCost float64
  1526. GPUCount float64
  1527. RAMCost float64
  1528. Discount float64
  1529. Preemptible float64
  1530. }
  1531. // NewNode creates and returns a new Node Asset
  1532. func NewNode(name, cluster, providerID string, start, end time.Time, window Window) *Node {
  1533. properties := &AssetProperties{
  1534. Category: ComputeCategory,
  1535. Name: name,
  1536. Cluster: cluster,
  1537. ProviderID: providerID,
  1538. Service: KubernetesService,
  1539. }
  1540. return &Node{
  1541. Properties: properties,
  1542. Labels: AssetLabels{},
  1543. Start: start,
  1544. End: end,
  1545. Window: window.Clone(),
  1546. CPUBreakdown: &Breakdown{},
  1547. RAMBreakdown: &Breakdown{},
  1548. }
  1549. }
  1550. // Type returns the AssetType of the Asset
  1551. func (n *Node) Type() AssetType {
  1552. return NodeAssetType
  1553. }
  1554. // Properties returns the Asset's Properties
  1555. func (n *Node) GetProperties() *AssetProperties {
  1556. return n.Properties
  1557. }
  1558. // SetProperties sets the Asset's Properties
  1559. func (n *Node) SetProperties(props *AssetProperties) {
  1560. n.Properties = props
  1561. }
  1562. // Labels returns the Asset's labels
  1563. func (n *Node) GetLabels() AssetLabels {
  1564. return n.Labels
  1565. }
  1566. // SetLabels sets the Asset's labels
  1567. func (n *Node) SetLabels(labels AssetLabels) {
  1568. n.Labels = labels
  1569. }
  1570. // Adjustment returns the Asset's cost adjustment
  1571. func (n *Node) GetAdjustment() float64 {
  1572. return n.Adjustment
  1573. }
  1574. // SetAdjustment sets the Asset's cost adjustment
  1575. func (n *Node) SetAdjustment(adj float64) {
  1576. n.Adjustment = adj
  1577. }
  1578. // TotalCost returns the Asset's total cost
  1579. func (n *Node) TotalCost() float64 {
  1580. return ((n.CPUCost + n.RAMCost) * (1.0 - n.Discount)) + n.GPUCost + n.Adjustment
  1581. }
  1582. // Start returns the precise start time of the Asset within the window
  1583. func (n *Node) GetStart() time.Time {
  1584. return n.Start
  1585. }
  1586. // End returns the precise end time of the Asset within the window
  1587. func (n *Node) GetEnd() time.Time {
  1588. return n.End
  1589. }
  1590. // Minutes returns the number of minutes the Asset ran within the window
  1591. func (n *Node) Minutes() float64 {
  1592. nodeMins := n.End.Sub(n.Start).Minutes()
  1593. windowMins := n.Window.Minutes()
  1594. if nodeMins > windowMins {
  1595. log.Warnf("Asset ETL: Node.Minutes exceeds window: %.2f > %.2f", nodeMins, windowMins)
  1596. nodeMins = windowMins
  1597. }
  1598. if nodeMins < 0 {
  1599. nodeMins = 0
  1600. }
  1601. return nodeMins
  1602. }
  1603. // Window returns the window within which the Asset ran
  1604. func (n *Node) GetWindow() Window {
  1605. return n.Window
  1606. }
  1607. func (n *Node) SetWindow(window Window) {
  1608. n.Window = window
  1609. }
  1610. // ExpandWindow expands the Asset's window by the given window
  1611. func (n *Node) ExpandWindow(window Window) {
  1612. n.Window = n.Window.Expand(window)
  1613. }
  1614. // SetStartEnd sets the Asset's Start and End fields
  1615. func (n *Node) SetStartEnd(start, end time.Time) {
  1616. if n.Window.Contains(start) {
  1617. n.Start = start
  1618. } else {
  1619. log.Warnf("Disk.SetStartEnd: start %s not in %s", start, n.Window)
  1620. }
  1621. if n.Window.Contains(end) {
  1622. n.End = end
  1623. } else {
  1624. log.Warnf("Disk.SetStartEnd: end %s not in %s", end, n.Window)
  1625. }
  1626. }
  1627. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  1628. // as much relevant information as possible (i.e. type, Properties, labels).
  1629. func (n *Node) Add(a Asset) Asset {
  1630. // Node + Node = Node
  1631. if that, ok := a.(*Node); ok {
  1632. this := n.Clone().(*Node)
  1633. this.add(that)
  1634. return this
  1635. }
  1636. props := n.Properties.Merge(a.GetProperties())
  1637. labels := n.Labels.Merge(a.GetLabels())
  1638. start := n.Start
  1639. if a.GetStart().Before(start) {
  1640. start = a.GetStart()
  1641. }
  1642. end := n.End
  1643. if a.GetEnd().After(end) {
  1644. end = a.GetEnd()
  1645. }
  1646. window := n.Window.Expand(a.GetWindow())
  1647. // Node + !Node = Any
  1648. any := NewAsset(start, end, window)
  1649. any.SetProperties(props)
  1650. any.SetLabels(labels)
  1651. any.Adjustment = n.Adjustment + a.GetAdjustment()
  1652. any.Cost = (n.TotalCost() - n.Adjustment) + (a.TotalCost() - a.GetAdjustment())
  1653. return any
  1654. }
  1655. func (n *Node) add(that *Node) {
  1656. if n == nil {
  1657. n = that
  1658. return
  1659. }
  1660. props := n.Properties.Merge(that.Properties)
  1661. labels := n.Labels.Merge(that.Labels)
  1662. n.SetProperties(props)
  1663. n.SetLabels(labels)
  1664. if n.NodeType != that.NodeType {
  1665. n.NodeType = ""
  1666. }
  1667. start := n.Start
  1668. if that.Start.Before(start) {
  1669. start = that.Start
  1670. }
  1671. end := n.End
  1672. if that.End.After(end) {
  1673. end = that.End
  1674. }
  1675. window := n.Window.Expand(that.Window)
  1676. n.Start = start
  1677. n.End = end
  1678. n.Window = window
  1679. // Order of operations for node costs is:
  1680. // Discount(CPU + RAM) + GPU + Adjustment
  1681. // Combining discounts, then involves weighting each discount by each
  1682. // respective (CPU + RAM) cost. Combining preemptible, on the other
  1683. // hand, is done with all three (but not Adjustment, which can change
  1684. // without triggering a re-computation of Preemtible).
  1685. disc := (n.CPUCost+n.RAMCost)*(1.0-n.Discount) + (that.CPUCost+that.RAMCost)*(1.0-that.Discount)
  1686. nonDisc := (n.CPUCost + n.RAMCost) + (that.CPUCost + that.RAMCost)
  1687. if nonDisc > 0 {
  1688. n.Discount = 1.0 - (disc / nonDisc)
  1689. } else {
  1690. n.Discount = (n.Discount + that.Discount) / 2.0
  1691. }
  1692. nNoAdj := n.TotalCost() - n.Adjustment
  1693. thatNoAdj := that.TotalCost() - that.Adjustment
  1694. if (nNoAdj + thatNoAdj) > 0 {
  1695. n.Preemptible = (nNoAdj*n.Preemptible + thatNoAdj*that.Preemptible) / (nNoAdj + thatNoAdj)
  1696. } else {
  1697. n.Preemptible = (n.Preemptible + that.Preemptible) / 2.0
  1698. }
  1699. totalCPUCost := n.CPUCost + that.CPUCost
  1700. if totalCPUCost > 0.0 {
  1701. n.CPUBreakdown.Idle = (n.CPUBreakdown.Idle*n.CPUCost + that.CPUBreakdown.Idle*that.CPUCost) / totalCPUCost
  1702. n.CPUBreakdown.Other = (n.CPUBreakdown.Other*n.CPUCost + that.CPUBreakdown.Other*that.CPUCost) / totalCPUCost
  1703. n.CPUBreakdown.System = (n.CPUBreakdown.System*n.CPUCost + that.CPUBreakdown.System*that.CPUCost) / totalCPUCost
  1704. n.CPUBreakdown.User = (n.CPUBreakdown.User*n.CPUCost + that.CPUBreakdown.User*that.CPUCost) / totalCPUCost
  1705. }
  1706. totalRAMCost := n.RAMCost + that.RAMCost
  1707. if totalRAMCost > 0.0 {
  1708. n.RAMBreakdown.Idle = (n.RAMBreakdown.Idle*n.RAMCost + that.RAMBreakdown.Idle*that.RAMCost) / totalRAMCost
  1709. n.RAMBreakdown.Other = (n.RAMBreakdown.Other*n.RAMCost + that.RAMBreakdown.Other*that.RAMCost) / totalRAMCost
  1710. n.RAMBreakdown.System = (n.RAMBreakdown.System*n.RAMCost + that.RAMBreakdown.System*that.RAMCost) / totalRAMCost
  1711. n.RAMBreakdown.User = (n.RAMBreakdown.User*n.RAMCost + that.RAMBreakdown.User*that.RAMCost) / totalRAMCost
  1712. }
  1713. n.CPUCoreHours += that.CPUCoreHours
  1714. n.RAMByteHours += that.RAMByteHours
  1715. n.GPUHours += that.GPUHours
  1716. n.CPUCost += that.CPUCost
  1717. n.GPUCost += that.GPUCost
  1718. n.RAMCost += that.RAMCost
  1719. n.Adjustment += that.Adjustment
  1720. }
  1721. // Clone returns a deep copy of the given Node
  1722. func (n *Node) Clone() Asset {
  1723. if n == nil {
  1724. return nil
  1725. }
  1726. return &Node{
  1727. Properties: n.Properties.Clone(),
  1728. Labels: n.Labels.Clone(),
  1729. Start: n.Start,
  1730. End: n.End,
  1731. Window: n.Window.Clone(),
  1732. Adjustment: n.Adjustment,
  1733. NodeType: n.NodeType,
  1734. CPUCoreHours: n.CPUCoreHours,
  1735. RAMByteHours: n.RAMByteHours,
  1736. GPUHours: n.GPUHours,
  1737. CPUBreakdown: n.CPUBreakdown.Clone(),
  1738. RAMBreakdown: n.RAMBreakdown.Clone(),
  1739. CPUCost: n.CPUCost,
  1740. GPUCost: n.GPUCost,
  1741. GPUCount: n.GPUCount,
  1742. RAMCost: n.RAMCost,
  1743. Preemptible: n.Preemptible,
  1744. Discount: n.Discount,
  1745. }
  1746. }
  1747. // Equal returns true if the tow Assets match exactly
  1748. func (n *Node) Equal(a Asset) bool {
  1749. that, ok := a.(*Node)
  1750. if !ok {
  1751. return false
  1752. }
  1753. if !n.Labels.Equal(that.Labels) {
  1754. return false
  1755. }
  1756. if !n.Properties.Equal(that.Properties) {
  1757. return false
  1758. }
  1759. if !n.Start.Equal(that.Start) {
  1760. return false
  1761. }
  1762. if !n.End.Equal(that.End) {
  1763. return false
  1764. }
  1765. if !n.Window.Equal(that.Window) {
  1766. return false
  1767. }
  1768. if n.Adjustment != that.Adjustment {
  1769. return false
  1770. }
  1771. if n.NodeType != that.NodeType {
  1772. return false
  1773. }
  1774. if n.CPUCoreHours != that.CPUCoreHours {
  1775. return false
  1776. }
  1777. if n.RAMByteHours != that.RAMByteHours {
  1778. return false
  1779. }
  1780. if n.GPUHours != that.GPUHours {
  1781. return false
  1782. }
  1783. if !n.CPUBreakdown.Equal(that.CPUBreakdown) {
  1784. return false
  1785. }
  1786. if !n.RAMBreakdown.Equal(that.RAMBreakdown) {
  1787. return false
  1788. }
  1789. if n.CPUCost != that.CPUCost {
  1790. return false
  1791. }
  1792. if n.GPUCost != that.GPUCost {
  1793. return false
  1794. }
  1795. if n.RAMCost != that.RAMCost {
  1796. return false
  1797. }
  1798. if n.Discount != that.Discount {
  1799. return false
  1800. }
  1801. if n.Preemptible != that.Preemptible {
  1802. return false
  1803. }
  1804. return true
  1805. }
  1806. // String implements fmt.Stringer
  1807. func (n *Node) String() string {
  1808. return toString(n)
  1809. }
  1810. // IsPreemptible returns true if the node is 100% preemptible. It's possible
  1811. // to be "partially preemptible" by adding a preemptible node with a
  1812. // non-preemptible node.
  1813. func (n *Node) IsPreemptible() bool {
  1814. return n.Preemptible == 1.0
  1815. }
  1816. // CPUCores returns the number of cores belonging to the node. This could be
  1817. // fractional because it's the number of core*hours divided by the number of
  1818. // hours running; e.g. the sum of a 4-core node running for the first 10 hours
  1819. // and a 3-core node running for the last 20 hours of the same 24-hour window
  1820. // would produce:
  1821. //
  1822. // (4*10 + 3*20) / 24 = 4.167 cores
  1823. //
  1824. // However, any number of cores running for the full span of a window will
  1825. // report the actual number of cores of the static node; e.g. the above
  1826. // scenario for one entire 24-hour window:
  1827. //
  1828. // (4*24 + 3*24) / 24 = (4 + 3) = 7 cores
  1829. func (n *Node) CPUCores() float64 {
  1830. // [core*hr]*([min/hr]*[1/min]) = [core*hr]/[hr] = core
  1831. return n.CPUCoreHours * (60.0 / n.Minutes())
  1832. }
  1833. // RAMBytes returns the amount of RAM belonging to the node. This could be
  1834. // fractional because it's the number of byte*hours divided by the number of
  1835. // hours running; e.g. the sum of a 12GiB-RAM node running for the first 10 hours
  1836. // and a 16GiB-RAM node running for the last 20 hours of the same 24-hour window
  1837. // would produce:
  1838. //
  1839. // (12*10 + 16*20) / 24 = 18.333GiB RAM
  1840. //
  1841. // However, any number of bytes running for the full span of a window will
  1842. // report the actual number of bytes of the static node; e.g. the above
  1843. // scenario for one entire 24-hour window:
  1844. //
  1845. // (12*24 + 16*24) / 24 = (12 + 16) = 28GiB RAM
  1846. func (n *Node) RAMBytes() float64 {
  1847. // [b*hr]*([min/hr]*[1/min]) = [b*hr]/[hr] = b
  1848. return n.RAMByteHours * (60.0 / n.Minutes())
  1849. }
  1850. // GPUs returns the amount of GPUs belonging to the node. This could be
  1851. // fractional because it's the number of gpu*hours divided by the number of
  1852. // hours running; e.g. the sum of a 2 gpu node running for the first 10 hours
  1853. // and a 1 gpu node running for the last 20 hours of the same 24-hour window
  1854. // would produce:
  1855. //
  1856. // (2*10 + 1*20) / 24 = 1.667 GPUs
  1857. //
  1858. // However, any number of GPUs running for the full span of a window will
  1859. // report the actual number of GPUs of the static node; e.g. the above
  1860. // scenario for one entire 24-hour window:
  1861. //
  1862. // (2*24 + 1*24) / 24 = (2 + 1) = 3 GPUs
  1863. func (n *Node) GPUs() float64 {
  1864. // [b*hr]*([min/hr]*[1/min]) = [b*hr]/[hr] = b
  1865. return n.GPUHours * (60.0 / n.Minutes())
  1866. }
  1867. // LoadBalancer is an Asset representing a single load balancer in a cluster
  1868. // TODO: add GB of ingress processed, numForwardingRules once we start recording those to prometheus metric
  1869. type LoadBalancer struct {
  1870. Properties *AssetProperties
  1871. Labels AssetLabels
  1872. Start time.Time
  1873. End time.Time
  1874. Window Window
  1875. Adjustment float64
  1876. Cost float64
  1877. }
  1878. // NewLoadBalancer instantiates and returns a new LoadBalancer
  1879. func NewLoadBalancer(name, cluster, providerID string, start, end time.Time, window Window) *LoadBalancer {
  1880. properties := &AssetProperties{
  1881. Category: NetworkCategory,
  1882. Name: name,
  1883. Cluster: cluster,
  1884. ProviderID: providerID,
  1885. Service: KubernetesService,
  1886. }
  1887. return &LoadBalancer{
  1888. Properties: properties,
  1889. Labels: AssetLabels{},
  1890. Start: start,
  1891. End: end,
  1892. Window: window,
  1893. }
  1894. }
  1895. // Type returns the AssetType of the Asset
  1896. func (lb *LoadBalancer) Type() AssetType {
  1897. return LoadBalancerAssetType
  1898. }
  1899. // Properties returns the Asset's Properties
  1900. func (lb *LoadBalancer) GetProperties() *AssetProperties {
  1901. return lb.Properties
  1902. }
  1903. // SetProperties sets the Asset's Properties
  1904. func (lb *LoadBalancer) SetProperties(props *AssetProperties) {
  1905. lb.Properties = props
  1906. }
  1907. // Labels returns the Asset's labels
  1908. func (lb *LoadBalancer) GetLabels() AssetLabels {
  1909. return lb.Labels
  1910. }
  1911. // SetLabels sets the Asset's labels
  1912. func (lb *LoadBalancer) SetLabels(labels AssetLabels) {
  1913. lb.Labels = labels
  1914. }
  1915. // Adjustment returns the Asset's cost adjustment
  1916. func (lb *LoadBalancer) GetAdjustment() float64 {
  1917. return lb.Adjustment
  1918. }
  1919. // SetAdjustment sets the Asset's cost adjustment
  1920. func (lb *LoadBalancer) SetAdjustment(adj float64) {
  1921. lb.Adjustment = adj
  1922. }
  1923. // TotalCost returns the total cost of the Asset
  1924. func (lb *LoadBalancer) TotalCost() float64 {
  1925. return lb.Cost + lb.Adjustment
  1926. }
  1927. // Start returns the preceise start point of the Asset within the window
  1928. func (lb *LoadBalancer) GetStart() time.Time {
  1929. return lb.Start
  1930. }
  1931. // End returns the preceise end point of the Asset within the window
  1932. func (lb *LoadBalancer) GetEnd() time.Time {
  1933. return lb.End
  1934. }
  1935. // Minutes returns the number of minutes the Asset ran within the window
  1936. func (lb *LoadBalancer) Minutes() float64 {
  1937. return lb.End.Sub(lb.Start).Minutes()
  1938. }
  1939. // Window returns the window within which the Asset ran
  1940. func (lb *LoadBalancer) GetWindow() Window {
  1941. return lb.Window
  1942. }
  1943. func (lb *LoadBalancer) SetWindow(window Window) {
  1944. lb.Window = window
  1945. }
  1946. // ExpandWindow expands the Asset's window by the given window
  1947. func (lb *LoadBalancer) ExpandWindow(w Window) {
  1948. lb.Window = lb.Window.Expand(w)
  1949. }
  1950. // SetStartEnd sets the Asset's Start and End fields
  1951. func (lb *LoadBalancer) SetStartEnd(start, end time.Time) {
  1952. if lb.Window.Contains(start) {
  1953. lb.Start = start
  1954. } else {
  1955. log.Warnf("Disk.SetStartEnd: start %s not in %s", start, lb.Window)
  1956. }
  1957. if lb.Window.Contains(end) {
  1958. lb.End = end
  1959. } else {
  1960. log.Warnf("Disk.SetStartEnd: end %s not in %s", end, lb.Window)
  1961. }
  1962. }
  1963. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  1964. // as much relevant information as possible (i.e. type, Properties, labels).
  1965. func (lb *LoadBalancer) Add(a Asset) Asset {
  1966. // LoadBalancer + LoadBalancer = LoadBalancer
  1967. if that, ok := a.(*LoadBalancer); ok {
  1968. this := lb.Clone().(*LoadBalancer)
  1969. this.add(that)
  1970. return this
  1971. }
  1972. props := lb.GetProperties().Merge(a.GetProperties())
  1973. labels := lb.Labels.Merge(a.GetLabels())
  1974. start := lb.Start
  1975. if a.GetStart().Before(start) {
  1976. start = a.GetStart()
  1977. }
  1978. end := lb.End
  1979. if a.GetEnd().After(end) {
  1980. end = a.GetEnd()
  1981. }
  1982. window := lb.Window.Expand(a.GetWindow())
  1983. // LoadBalancer + !LoadBalancer = Any
  1984. any := NewAsset(start, end, window)
  1985. any.SetProperties(props)
  1986. any.SetLabels(labels)
  1987. any.Adjustment = lb.Adjustment + a.GetAdjustment()
  1988. any.Cost = (lb.TotalCost() - lb.Adjustment) + (a.TotalCost() - a.GetAdjustment())
  1989. return any
  1990. }
  1991. func (lb *LoadBalancer) add(that *LoadBalancer) {
  1992. if lb == nil {
  1993. lb = that
  1994. return
  1995. }
  1996. props := lb.Properties.Merge(that.GetProperties())
  1997. labels := lb.Labels.Merge(that.GetLabels())
  1998. lb.SetProperties(props)
  1999. lb.SetLabels(labels)
  2000. start := lb.Start
  2001. if that.Start.Before(start) {
  2002. start = that.Start
  2003. }
  2004. end := lb.End
  2005. if that.End.After(end) {
  2006. end = that.End
  2007. }
  2008. window := lb.Window.Expand(that.Window)
  2009. lb.Start = start
  2010. lb.End = end
  2011. lb.Window = window
  2012. lb.Cost += that.Cost
  2013. lb.Adjustment += that.Adjustment
  2014. }
  2015. // Clone returns a cloned instance of the given Asset
  2016. func (lb *LoadBalancer) Clone() Asset {
  2017. return &LoadBalancer{
  2018. Properties: lb.Properties.Clone(),
  2019. Labels: lb.Labels.Clone(),
  2020. Start: lb.Start,
  2021. End: lb.End,
  2022. Window: lb.Window.Clone(),
  2023. Adjustment: lb.Adjustment,
  2024. Cost: lb.Cost,
  2025. }
  2026. }
  2027. // Equal returns true if the tow Assets match precisely
  2028. func (lb *LoadBalancer) Equal(a Asset) bool {
  2029. that, ok := a.(*LoadBalancer)
  2030. if !ok {
  2031. return false
  2032. }
  2033. if !lb.Labels.Equal(that.Labels) {
  2034. return false
  2035. }
  2036. if !lb.Properties.Equal(that.Properties) {
  2037. return false
  2038. }
  2039. if !lb.Start.Equal(that.Start) {
  2040. return false
  2041. }
  2042. if !lb.End.Equal(that.End) {
  2043. return false
  2044. }
  2045. if !lb.Window.Equal(that.Window) {
  2046. return false
  2047. }
  2048. if lb.Adjustment != that.Adjustment {
  2049. return false
  2050. }
  2051. if lb.Cost != that.Cost {
  2052. return false
  2053. }
  2054. return true
  2055. }
  2056. // String implements fmt.Stringer
  2057. func (lb *LoadBalancer) String() string {
  2058. return toString(lb)
  2059. }
  2060. // SharedAsset is an Asset representing a shared cost
  2061. type SharedAsset struct {
  2062. Properties *AssetProperties
  2063. Labels AssetLabels
  2064. Window Window
  2065. Cost float64
  2066. }
  2067. // NewSharedAsset creates and returns a new SharedAsset
  2068. func NewSharedAsset(name string, window Window) *SharedAsset {
  2069. properties := &AssetProperties{
  2070. Name: name,
  2071. Category: SharedCategory,
  2072. Service: OtherCategory,
  2073. }
  2074. return &SharedAsset{
  2075. Properties: properties,
  2076. Labels: AssetLabels{},
  2077. Window: window.Clone(),
  2078. }
  2079. }
  2080. // Type returns the AssetType of the Asset
  2081. func (sa *SharedAsset) Type() AssetType {
  2082. return SharedAssetType
  2083. }
  2084. // Properties returns the Asset's Properties
  2085. func (sa *SharedAsset) GetProperties() *AssetProperties {
  2086. return sa.Properties
  2087. }
  2088. // SetProperties sets the Asset's Properties
  2089. func (sa *SharedAsset) SetProperties(props *AssetProperties) {
  2090. sa.Properties = props
  2091. }
  2092. // Labels returns the Asset's labels
  2093. func (sa *SharedAsset) GetLabels() AssetLabels {
  2094. return sa.Labels
  2095. }
  2096. // SetLabels sets the Asset's labels
  2097. func (sa *SharedAsset) SetLabels(labels AssetLabels) {
  2098. sa.Labels = labels
  2099. }
  2100. // Adjustment is not relevant to SharedAsset, but required to implement Asset
  2101. func (sa *SharedAsset) GetAdjustment() float64 {
  2102. return 0.0
  2103. }
  2104. // SetAdjustment is not relevant to SharedAsset, but required to implement Asset
  2105. func (sa *SharedAsset) SetAdjustment(float64) {
  2106. return
  2107. }
  2108. // TotalCost returns the Asset's total cost
  2109. func (sa *SharedAsset) TotalCost() float64 {
  2110. return sa.Cost
  2111. }
  2112. // Start returns the start time of the Asset
  2113. func (sa *SharedAsset) GetStart() time.Time {
  2114. return *sa.Window.start
  2115. }
  2116. // End returns the end time of the Asset
  2117. func (sa *SharedAsset) GetEnd() time.Time {
  2118. return *sa.Window.end
  2119. }
  2120. // Minutes returns the number of minutes the SharedAsset ran within the window
  2121. func (sa *SharedAsset) Minutes() float64 {
  2122. return sa.Window.Minutes()
  2123. }
  2124. // Window returns the window within the SharedAsset ran
  2125. func (sa *SharedAsset) GetWindow() Window {
  2126. return sa.Window
  2127. }
  2128. func (sa *SharedAsset) SetWindow(window Window) {
  2129. sa.Window = window
  2130. }
  2131. // ExpandWindow expands the Asset's window
  2132. func (sa *SharedAsset) ExpandWindow(w Window) {
  2133. sa.Window = sa.Window.Expand(w)
  2134. }
  2135. // SetStartEnd sets the Asset's Start and End fields (not applicable here)
  2136. func (sa *SharedAsset) SetStartEnd(start, end time.Time) {
  2137. return
  2138. }
  2139. // Add sums the Asset with the given Asset to produce a new Asset, maintaining
  2140. // as much relevant information as possible (i.e. type, Properties, labels).
  2141. func (sa *SharedAsset) Add(a Asset) Asset {
  2142. // SharedAsset + SharedAsset = SharedAsset
  2143. if that, ok := a.(*SharedAsset); ok {
  2144. this := sa.Clone().(*SharedAsset)
  2145. this.add(that)
  2146. return this
  2147. }
  2148. props := sa.Properties.Merge(a.GetProperties())
  2149. labels := sa.Labels.Merge(a.GetLabels())
  2150. start := sa.GetStart()
  2151. if a.GetStart().Before(start) {
  2152. start = a.GetStart()
  2153. }
  2154. end := sa.GetEnd()
  2155. if a.GetEnd().After(end) {
  2156. end = a.GetEnd()
  2157. }
  2158. window := sa.Window.Expand(a.GetWindow())
  2159. // SharedAsset + !SharedAsset = Any
  2160. any := NewAsset(start, end, window)
  2161. any.SetProperties(props)
  2162. any.SetLabels(labels)
  2163. any.Adjustment = sa.GetAdjustment() + a.GetAdjustment()
  2164. any.Cost = (sa.TotalCost() - sa.GetAdjustment()) + (a.TotalCost() - a.GetAdjustment())
  2165. return any
  2166. }
  2167. func (sa *SharedAsset) add(that *SharedAsset) {
  2168. if sa == nil {
  2169. sa = that
  2170. return
  2171. }
  2172. props := sa.Properties.Merge(that.GetProperties())
  2173. labels := sa.Labels.Merge(that.GetLabels())
  2174. sa.SetProperties(props)
  2175. sa.SetLabels(labels)
  2176. window := sa.Window.Expand(that.Window)
  2177. sa.Window = window
  2178. sa.Cost += that.Cost
  2179. }
  2180. // Clone returns a deep copy of the given SharedAsset
  2181. func (sa *SharedAsset) Clone() Asset {
  2182. if sa == nil {
  2183. return nil
  2184. }
  2185. return &SharedAsset{
  2186. Properties: sa.Properties.Clone(),
  2187. Labels: sa.Labels.Clone(),
  2188. Window: sa.Window.Clone(),
  2189. Cost: sa.Cost,
  2190. }
  2191. }
  2192. // Equal returns true if the two Assets are exact matches
  2193. func (sa *SharedAsset) Equal(a Asset) bool {
  2194. that, ok := a.(*SharedAsset)
  2195. if !ok {
  2196. return false
  2197. }
  2198. if !sa.Labels.Equal(that.Labels) {
  2199. return false
  2200. }
  2201. if !sa.Properties.Equal(that.Properties) {
  2202. return false
  2203. }
  2204. if !sa.Window.Equal(that.Window) {
  2205. return false
  2206. }
  2207. if sa.Cost != that.Cost {
  2208. return false
  2209. }
  2210. return true
  2211. }
  2212. // String implements fmt.Stringer
  2213. func (sa *SharedAsset) String() string {
  2214. return toString(sa)
  2215. }
  2216. // This type exists because only the assets map of AssetSet is marshaled to
  2217. // json, which makes it impossible to recreate an AssetSet struct. Thus,
  2218. // the type when unmarshaling a marshaled AssetSet,is AssetSetResponse
  2219. type AssetSetResponse struct {
  2220. Assets map[string]Asset
  2221. }
  2222. // AssetSet stores a set of Assets, each with a unique name, that share
  2223. // a window. An AssetSet is mutable, so treat it like a threadsafe map.
  2224. type AssetSet struct {
  2225. AggregationKeys []string
  2226. Assets map[string]Asset
  2227. Any map[string]*Any //@bingen:field[ignore]
  2228. Cloud map[string]*Cloud //@bingen:field[ignore]
  2229. ClusterManagement map[string]*ClusterManagement //@bingen:field[ignore]
  2230. Disks map[string]*Disk //@bingen:field[ignore]
  2231. Network map[string]*Network //@bingen:field[ignore]
  2232. Nodes map[string]*Node //@bingen:field[ignore]
  2233. LoadBalancers map[string]*LoadBalancer //@bingen:field[ignore]
  2234. SharedAssets map[string]*SharedAsset //@bingen:field[ignore]
  2235. FromSource string // stores the name of the source used to compute the data
  2236. Window Window
  2237. Warnings []string
  2238. Errors []string
  2239. }
  2240. // This methid is executed before marshalling the AssetSet binary.
  2241. func preProcessAssetSet(assetSet *AssetSet) {
  2242. length := len(assetSet.Any) + len(assetSet.Cloud) + len(assetSet.ClusterManagement) + len(assetSet.Disks) +
  2243. len(assetSet.Network) + len(assetSet.Nodes) + len(assetSet.LoadBalancers) + len(assetSet.SharedAssets)
  2244. if length != len(assetSet.Assets) {
  2245. log.Warnf("AssetSet concrete Asset maps are out of sync with AssetSet.Assets map.")
  2246. }
  2247. }
  2248. // This method is executed after unmarshalling the AssetSet binary.
  2249. func postProcessAssetSet(assetSet *AssetSet) {
  2250. for key, as := range assetSet.Assets {
  2251. addToConcreteMap(assetSet, key, as)
  2252. }
  2253. }
  2254. // addToConcreteMap adds the Asset to the correct concrete map in the AssetSet. This is used
  2255. // in the postProcessAssetSet method as well as AssetSet.Insert().
  2256. func addToConcreteMap(assetSet *AssetSet, key string, as Asset) {
  2257. switch asset := as.(type) {
  2258. case *Any:
  2259. if assetSet.Any == nil {
  2260. assetSet.Any = make(map[string]*Any)
  2261. }
  2262. assetSet.Any[key] = asset
  2263. case *Cloud:
  2264. if assetSet.Cloud == nil {
  2265. assetSet.Cloud = make(map[string]*Cloud)
  2266. }
  2267. assetSet.Cloud[key] = asset
  2268. case *ClusterManagement:
  2269. if assetSet.ClusterManagement == nil {
  2270. assetSet.ClusterManagement = make(map[string]*ClusterManagement)
  2271. }
  2272. assetSet.ClusterManagement[key] = asset
  2273. case *Disk:
  2274. if assetSet.Disks == nil {
  2275. assetSet.Disks = make(map[string]*Disk)
  2276. }
  2277. assetSet.Disks[key] = asset
  2278. case *Network:
  2279. if assetSet.Network == nil {
  2280. assetSet.Network = make(map[string]*Network)
  2281. }
  2282. assetSet.Network[key] = asset
  2283. case *Node:
  2284. if assetSet.Nodes == nil {
  2285. assetSet.Nodes = make(map[string]*Node)
  2286. }
  2287. assetSet.Nodes[key] = asset
  2288. case *LoadBalancer:
  2289. if assetSet.LoadBalancers == nil {
  2290. assetSet.LoadBalancers = make(map[string]*LoadBalancer)
  2291. }
  2292. assetSet.LoadBalancers[key] = asset
  2293. case *SharedAsset:
  2294. if assetSet.SharedAssets == nil {
  2295. assetSet.SharedAssets = make(map[string]*SharedAsset)
  2296. }
  2297. assetSet.SharedAssets[key] = asset
  2298. }
  2299. }
  2300. // removeFromConcreteMap will remove an Asset from the AssetSet's concrete type mapping for the Asset and key.
  2301. func removeFromConcreteMap(assetSet *AssetSet, key string, as Asset) {
  2302. switch as.(type) {
  2303. case *Any:
  2304. delete(assetSet.Any, key)
  2305. case *Cloud:
  2306. delete(assetSet.Cloud, key)
  2307. case *ClusterManagement:
  2308. delete(assetSet.ClusterManagement, key)
  2309. case *Disk:
  2310. delete(assetSet.Disks, key)
  2311. case *Network:
  2312. delete(assetSet.Network, key)
  2313. case *Node:
  2314. delete(assetSet.Nodes, key)
  2315. case *LoadBalancer:
  2316. delete(assetSet.LoadBalancers, key)
  2317. case *SharedAsset:
  2318. delete(assetSet.SharedAssets, key)
  2319. }
  2320. }
  2321. // NewAssetSet instantiates a new AssetSet and, optionally, inserts
  2322. // the given list of Assets
  2323. func NewAssetSet(start, end time.Time, assets ...Asset) *AssetSet {
  2324. as := &AssetSet{
  2325. Assets: map[string]Asset{},
  2326. Window: NewWindow(&start, &end),
  2327. }
  2328. for _, a := range assets {
  2329. as.Insert(a, nil)
  2330. }
  2331. return as
  2332. }
  2333. // AggregateBy aggregates the Assets in the AssetSet by the given list of
  2334. // AssetProperties, such that each asset is binned by a key determined by its
  2335. // relevant property values.
  2336. func (as *AssetSet) AggregateBy(aggregateBy []string, opts *AssetAggregationOptions) error {
  2337. if opts == nil {
  2338. opts = &AssetAggregationOptions{}
  2339. }
  2340. if as.IsEmpty() && len(opts.SharedHourlyCosts) == 0 {
  2341. return nil
  2342. }
  2343. aggSet := NewAssetSet(as.Start(), as.End())
  2344. aggSet.AggregationKeys = aggregateBy
  2345. // Compute hours of the given AssetSet, and if it ends in the future,
  2346. // adjust the hours accordingly
  2347. hours := as.Window.Minutes() / 60.0
  2348. diff := time.Since(as.End())
  2349. if diff < 0.0 {
  2350. hours += diff.Hours()
  2351. }
  2352. // Insert a shared asset for each shared cost
  2353. for name, hourlyCost := range opts.SharedHourlyCosts {
  2354. sa := NewSharedAsset(name, as.Window.Clone())
  2355. sa.Cost = hourlyCost * hours
  2356. // Insert shared asset if it passes all filters
  2357. insert := true
  2358. for _, ff := range opts.FilterFuncs {
  2359. if !ff(sa) {
  2360. insert = false
  2361. break
  2362. }
  2363. }
  2364. if insert {
  2365. err := aggSet.Insert(sa, opts.LabelConfig)
  2366. if err != nil {
  2367. return err
  2368. }
  2369. }
  2370. }
  2371. // Delete the Assets that don't pass each filter
  2372. for _, ff := range opts.FilterFuncs {
  2373. for key, asset := range as.Assets {
  2374. if !ff(asset) {
  2375. delete(as.Assets, key)
  2376. }
  2377. }
  2378. }
  2379. // Insert each asset into the new set, which will be keyed by the `aggregateBy`
  2380. // on aggSet, resulting in aggregation.
  2381. for _, asset := range as.Assets {
  2382. err := aggSet.Insert(asset, opts.LabelConfig)
  2383. if err != nil {
  2384. return err
  2385. }
  2386. }
  2387. // Assign the aggregated values back to the original set
  2388. as.Assets = aggSet.Assets
  2389. as.AggregationKeys = aggregateBy
  2390. return nil
  2391. }
  2392. // Clone returns a new AssetSet with a deep copy of the given
  2393. // AssetSet's assets.
  2394. func (as *AssetSet) Clone() *AssetSet {
  2395. if as == nil {
  2396. return nil
  2397. }
  2398. var aggregateBy []string
  2399. if as.AggregationKeys != nil {
  2400. aggregateBy = append(aggregateBy, as.AggregationKeys...)
  2401. }
  2402. s := as.Start()
  2403. e := as.End()
  2404. var errors []string
  2405. var warnings []string
  2406. if as.Errors != nil {
  2407. errors = make([]string, len(as.Errors))
  2408. copy(errors, as.Errors)
  2409. } else {
  2410. errors = nil
  2411. }
  2412. if as.Warnings != nil {
  2413. warnings := make([]string, len(as.Warnings))
  2414. copy(warnings, as.Warnings)
  2415. } else {
  2416. warnings = nil
  2417. }
  2418. var anyMap map[string]*Any
  2419. if as.Any != nil {
  2420. anyMap = make(map[string]*Any, len(as.Any))
  2421. }
  2422. var cloudMap map[string]*Cloud
  2423. if as.Cloud != nil {
  2424. cloudMap = make(map[string]*Cloud, len(as.Cloud))
  2425. }
  2426. var clusterManagementMap map[string]*ClusterManagement
  2427. if as.ClusterManagement != nil {
  2428. clusterManagementMap = make(map[string]*ClusterManagement, len(as.ClusterManagement))
  2429. }
  2430. var disksMap map[string]*Disk
  2431. if as.Disks != nil {
  2432. disksMap = make(map[string]*Disk, len(as.Disks))
  2433. }
  2434. var networkMap map[string]*Network
  2435. if as.Network != nil {
  2436. networkMap = make(map[string]*Network, len(as.Network))
  2437. }
  2438. var nodesMap map[string]*Node
  2439. if as.Nodes != nil {
  2440. nodesMap = make(map[string]*Node, len(as.Nodes))
  2441. }
  2442. var loadBalancersMap map[string]*LoadBalancer
  2443. if as.LoadBalancers != nil {
  2444. loadBalancersMap = make(map[string]*LoadBalancer, len(as.LoadBalancers))
  2445. }
  2446. var sharedAssetsMap map[string]*SharedAsset
  2447. if as.SharedAssets != nil {
  2448. sharedAssetsMap = make(map[string]*SharedAsset, len(as.SharedAssets))
  2449. }
  2450. assetSet := &AssetSet{
  2451. Window: NewWindow(&s, &e),
  2452. AggregationKeys: aggregateBy,
  2453. Assets: make(map[string]Asset, len(as.Assets)),
  2454. Any: anyMap,
  2455. Cloud: cloudMap,
  2456. ClusterManagement: clusterManagementMap,
  2457. Disks: disksMap,
  2458. Network: networkMap,
  2459. Nodes: nodesMap,
  2460. LoadBalancers: loadBalancersMap,
  2461. SharedAssets: sharedAssetsMap,
  2462. Errors: errors,
  2463. Warnings: warnings,
  2464. }
  2465. for k, v := range as.Assets {
  2466. newAsset := v.Clone()
  2467. assetSet.Assets[k] = newAsset
  2468. addToConcreteMap(assetSet, k, newAsset)
  2469. }
  2470. return assetSet
  2471. }
  2472. // End returns the end time of the AssetSet's window
  2473. func (as *AssetSet) End() time.Time {
  2474. return *as.Window.End()
  2475. }
  2476. // FindMatch attempts to find a match in the AssetSet for the given Asset on
  2477. // the provided Properties and labels. If a match is not found, FindMatch
  2478. // returns nil and a Not Found error.
  2479. func (as *AssetSet) FindMatch(query Asset, aggregateBy []string, labelConfig *LabelConfig) (Asset, error) {
  2480. matchKey, err := key(query, aggregateBy, labelConfig)
  2481. if err != nil {
  2482. return nil, err
  2483. }
  2484. for _, asset := range as.Assets {
  2485. if k, err := key(asset, aggregateBy, labelConfig); err != nil {
  2486. return nil, err
  2487. } else if k == matchKey {
  2488. return asset, nil
  2489. }
  2490. }
  2491. return nil, fmt.Errorf("Asset not found to match %s on %v", query, aggregateBy)
  2492. }
  2493. // ReconciliationMatch attempts to find an exact match in the AssetSet on
  2494. // (Category, ProviderID). If a match is found, it returns the Asset with the
  2495. // intent to adjust it. If no match exists, it attempts to find one on only
  2496. // (ProviderID). If that match is found, it returns the Asset with the intent
  2497. // to insert the associated Cloud cost.
  2498. func (as *AssetSet) ReconciliationMatch(query Asset) (Asset, bool, error) {
  2499. // Full match means matching on (Category, ProviderID)
  2500. fullMatchProps := []string{string(AssetCategoryProp), string(AssetProviderIDProp)}
  2501. fullMatchKey, err := key(query, fullMatchProps, nil)
  2502. // This should never happen because we are using enumerated Properties,
  2503. // but the check is here in case that changes
  2504. if err != nil {
  2505. return nil, false, err
  2506. }
  2507. // Partial match means matching only on (ProviderID)
  2508. providerIDMatchProps := []string{string(AssetProviderIDProp)}
  2509. providerIDMatchKey, err := key(query, providerIDMatchProps, nil)
  2510. // This should never happen because we are using enumerated Properties,
  2511. // but the check is here in case that changes
  2512. if err != nil {
  2513. return nil, false, err
  2514. }
  2515. var providerIDMatch Asset
  2516. for _, asset := range as.Assets {
  2517. // Ignore cloud assets when looking for reconciliation matches
  2518. if asset.Type() == CloudAssetType {
  2519. continue
  2520. }
  2521. if k, err := key(asset, fullMatchProps, nil); err != nil {
  2522. return nil, false, err
  2523. } else if k == fullMatchKey {
  2524. log.DedupedInfof(10, "Asset ETL: Reconciliation[rcnw]: ReconcileRange Match: %s", fullMatchKey)
  2525. return asset, true, nil
  2526. }
  2527. if k, err := key(asset, providerIDMatchProps, nil); err != nil {
  2528. return nil, false, err
  2529. } else if k == providerIDMatchKey {
  2530. // Found a partial match. Save it until after all other options
  2531. // have been checked for full matches.
  2532. providerIDMatch = asset
  2533. }
  2534. }
  2535. // No full match was found, so return partial match, if found.
  2536. if providerIDMatch != nil {
  2537. return providerIDMatch, false, nil
  2538. }
  2539. return nil, false, fmt.Errorf("Asset not found to match %s", query)
  2540. }
  2541. // ReconciliationMatchMap returns a map of the calling AssetSet's Assets, by provider id and category. This data structure
  2542. // allows for reconciliation matching to be done in constant time and prevents duplicate reconciliation.
  2543. func (as *AssetSet) ReconciliationMatchMap() map[string]map[string]Asset {
  2544. matchMap := make(map[string]map[string]Asset)
  2545. if as == nil {
  2546. return matchMap
  2547. }
  2548. for _, asset := range as.Assets {
  2549. if asset == nil {
  2550. continue
  2551. }
  2552. props := asset.GetProperties()
  2553. // Ignore assets that cannot be matched when looking for reconciliation matches
  2554. if props == nil || props.ProviderID == "" {
  2555. continue
  2556. }
  2557. if _, ok := matchMap[props.ProviderID]; !ok {
  2558. matchMap[props.ProviderID] = make(map[string]Asset)
  2559. }
  2560. // Check if a match is already in the map
  2561. if duplicateAsset, ok := matchMap[props.ProviderID][props.Category]; ok {
  2562. log.DedupedWarningf(5, "duplicate asset found when reconciling for %s", props.ProviderID)
  2563. // if one asset already has adjustment use that one
  2564. if duplicateAsset.GetAdjustment() == 0 && asset.GetAdjustment() != 0 {
  2565. matchMap[props.ProviderID][props.Category] = asset
  2566. } else if duplicateAsset.GetAdjustment() != 0 && asset.GetAdjustment() == 0 {
  2567. matchMap[props.ProviderID][props.Category] = duplicateAsset
  2568. // otherwise use the one with the higher cost
  2569. } else if duplicateAsset.TotalCost() < asset.TotalCost() {
  2570. matchMap[props.ProviderID][props.Category] = asset
  2571. }
  2572. } else {
  2573. matchMap[props.ProviderID][props.Category] = asset
  2574. }
  2575. }
  2576. return matchMap
  2577. }
  2578. // Get returns the Asset in the AssetSet at the given key, or nil and false
  2579. // if no Asset exists for the given key
  2580. func (as *AssetSet) Get(key string) (Asset, bool) {
  2581. if a, ok := as.Assets[key]; ok {
  2582. return a, true
  2583. }
  2584. return nil, false
  2585. }
  2586. // Insert inserts the given Asset into the AssetSet, using the AssetSet's
  2587. // configured Properties to determine the key under which the Asset will
  2588. // be inserted.
  2589. func (as *AssetSet) Insert(asset Asset, labelConfig *LabelConfig) error {
  2590. if as == nil {
  2591. return fmt.Errorf("cannot Insert into nil AssetSet")
  2592. }
  2593. if as.Assets == nil {
  2594. as.Assets = map[string]Asset{}
  2595. }
  2596. // need a label config
  2597. // Determine key into which to Insert the Asset.
  2598. k, err := key(asset, as.AggregationKeys, labelConfig)
  2599. if err != nil {
  2600. return err
  2601. }
  2602. // Add the given Asset to the existing entry, if there is one;
  2603. // otherwise just set directly into assets
  2604. if _, ok := as.Assets[k]; !ok {
  2605. as.Assets[k] = asset
  2606. // insert the asset into it's type specific map as well
  2607. addToConcreteMap(as, k, asset)
  2608. } else {
  2609. // possibly creates a new asset type, so we need to update the
  2610. // concrete type mappings
  2611. newAsset := as.Assets[k].Add(asset)
  2612. removeFromConcreteMap(as, k, as.Assets[k])
  2613. // overwrite the existing asset with the new one, and re-add the new
  2614. // asset to the concrete type mappings
  2615. as.Assets[k] = newAsset
  2616. addToConcreteMap(as, k, newAsset)
  2617. }
  2618. // Expand the window, just to be safe. It's possible that the asset will
  2619. // be set into the map without expanding it to the AssetSet's window.
  2620. as.Assets[k].ExpandWindow(as.Window)
  2621. return nil
  2622. }
  2623. // IsEmpty returns true if the AssetSet is nil, or if it contains
  2624. // zero assets.
  2625. func (as *AssetSet) IsEmpty() bool {
  2626. return as == nil || len(as.Assets) == 0
  2627. }
  2628. func (as *AssetSet) Length() int {
  2629. if as == nil {
  2630. return 0
  2631. }
  2632. return len(as.Assets)
  2633. }
  2634. func (as *AssetSet) GetWindow() Window {
  2635. return as.Window
  2636. }
  2637. // Resolution returns the AssetSet's window duration
  2638. func (as *AssetSet) Resolution() time.Duration {
  2639. return as.Window.Duration()
  2640. }
  2641. func (as *AssetSet) Set(asset Asset, aggregateBy []string, labelConfig *LabelConfig) error {
  2642. if as.IsEmpty() {
  2643. as.Assets = map[string]Asset{}
  2644. }
  2645. // Expand the window to match the AssetSet, then set it
  2646. asset.ExpandWindow(as.Window)
  2647. k, err := key(asset, aggregateBy, labelConfig)
  2648. if err != nil {
  2649. return err
  2650. }
  2651. as.Assets[k] = asset
  2652. addToConcreteMap(as, k, asset)
  2653. return nil
  2654. }
  2655. func (as *AssetSet) Start() time.Time {
  2656. return *as.Window.Start()
  2657. }
  2658. func (as *AssetSet) TotalCost() float64 {
  2659. tc := 0.0
  2660. for _, a := range as.Assets {
  2661. tc += a.TotalCost()
  2662. }
  2663. return tc
  2664. }
  2665. func (as *AssetSet) UTCOffset() time.Duration {
  2666. _, zone := as.Start().Zone()
  2667. return time.Duration(zone) * time.Second
  2668. }
  2669. func (as *AssetSet) accumulate(that *AssetSet) (*AssetSet, error) {
  2670. if as == nil {
  2671. return that, nil
  2672. }
  2673. if that == nil {
  2674. return as, nil
  2675. }
  2676. // In the case of an AssetSetRange with empty entries, we may end up with
  2677. // an incoming `as` without an `aggregateBy`, even though we are tring to
  2678. // aggregate here. This handles that case by assigning the correct `aggregateBy`.
  2679. if !sameContents(as.AggregationKeys, that.AggregationKeys) {
  2680. if len(as.AggregationKeys) == 0 {
  2681. as.AggregationKeys = that.AggregationKeys
  2682. }
  2683. }
  2684. // Set start, end to min(start), max(end)
  2685. start := as.Start()
  2686. end := as.End()
  2687. if that.Start().Before(start) {
  2688. start = that.Start()
  2689. }
  2690. if that.End().After(end) {
  2691. end = that.End()
  2692. }
  2693. if as.IsEmpty() && that.IsEmpty() {
  2694. return NewAssetSet(start, end), nil
  2695. }
  2696. acc := NewAssetSet(start, end)
  2697. acc.AggregationKeys = as.AggregationKeys
  2698. for _, asset := range as.Assets {
  2699. err := acc.Insert(asset, nil)
  2700. if err != nil {
  2701. return nil, err
  2702. }
  2703. }
  2704. for _, asset := range that.Assets {
  2705. err := acc.Insert(asset, nil)
  2706. if err != nil {
  2707. return nil, err
  2708. }
  2709. }
  2710. return acc, nil
  2711. }
  2712. type DiffKind string
  2713. const (
  2714. DiffAdded DiffKind = "added"
  2715. DiffRemoved = "removed"
  2716. DiffChanged = "changed"
  2717. )
  2718. // Diff stores an object and a string that denotes whether that object was
  2719. // added or removed from a set of those objects
  2720. type Diff[T any] struct {
  2721. Before T
  2722. After T
  2723. Kind DiffKind
  2724. }
  2725. // DiffAsset takes two AssetSets and returns a map of keys to Diffs by checking
  2726. // the keys of each AssetSet. If a key is not found or is found with a different total cost,
  2727. // a Diff is generated and added to the map. A found asset will only be added to the map if the new
  2728. // total cost is greater than ratioCostChange * the old total cost
  2729. func DiffAsset(before, after *AssetSet, ratioCostChange float64) (map[string]Diff[Asset], error) {
  2730. if ratioCostChange < 0.0 {
  2731. return nil, fmt.Errorf("Percent cost change cannot be less than 0")
  2732. }
  2733. changedItems := map[string]Diff[Asset]{}
  2734. for assetKey1, asset1 := range before.Assets {
  2735. if asset2, ok := after.Assets[assetKey1]; !ok {
  2736. d := Diff[Asset]{asset1, nil, DiffRemoved}
  2737. changedItems[assetKey1] = d
  2738. } else if math.Abs(asset1.TotalCost()-asset2.TotalCost()) > ratioCostChange*asset1.TotalCost() { //check if either value exceeds the other by more than pctCostChange
  2739. d := Diff[Asset]{asset1, asset2, DiffChanged}
  2740. changedItems[assetKey1] = d
  2741. }
  2742. }
  2743. for assetKey2, asset2 := range after.Assets {
  2744. if _, ok := before.Assets[assetKey2]; !ok {
  2745. d := Diff[Asset]{nil, asset2, DiffAdded}
  2746. changedItems[assetKey2] = d
  2747. }
  2748. }
  2749. return changedItems, nil
  2750. }
  2751. // AssetSetRange is a thread-safe slice of AssetSets. It is meant to
  2752. // be used such that the AssetSets held are consecutive and coherent with
  2753. // respect to using the same aggregation Properties, UTC offset, and
  2754. // resolution. However these rules are not necessarily enforced, so use wisely.
  2755. type AssetSetRange struct {
  2756. Assets []*AssetSet
  2757. FromStore string // stores the name of the store used to retrieve the data
  2758. }
  2759. // NewAssetSetRange instantiates a new range composed of the given
  2760. // AssetSets in the order provided.
  2761. func NewAssetSetRange(assets ...*AssetSet) *AssetSetRange {
  2762. return &AssetSetRange{
  2763. Assets: assets,
  2764. }
  2765. }
  2766. // Accumulate sums each AssetSet in the given range, returning a single cumulative
  2767. // AssetSet for the entire range.
  2768. func (asr *AssetSetRange) Accumulate() (*AssetSet, error) {
  2769. var assetSet *AssetSet
  2770. var err error
  2771. for _, as := range asr.Assets {
  2772. assetSet, err = assetSet.accumulate(as)
  2773. if err != nil {
  2774. return nil, err
  2775. }
  2776. }
  2777. return assetSet, nil
  2778. }
  2779. // NewAccumulation clones the first available AssetSet to use as the data structure to
  2780. // accumulate the remaining data. This leaves the original AssetSetRange intact.
  2781. func (asr *AssetSetRange) NewAccumulation() (*AssetSet, error) {
  2782. var assetSet *AssetSet
  2783. var err error
  2784. for _, as := range asr.Assets {
  2785. if assetSet == nil {
  2786. assetSet = as.Clone()
  2787. continue
  2788. }
  2789. // copy if non-nil
  2790. var assetSetCopy *AssetSet = nil
  2791. if as != nil {
  2792. assetSetCopy = as.Clone()
  2793. }
  2794. // nil is acceptable to pass to accumulate
  2795. assetSet, err = assetSet.accumulate(assetSetCopy)
  2796. if err != nil {
  2797. return nil, err
  2798. }
  2799. }
  2800. return assetSet, nil
  2801. }
  2802. type AssetAggregationOptions struct {
  2803. SharedHourlyCosts map[string]float64
  2804. FilterFuncs []AssetMatchFunc
  2805. LabelConfig *LabelConfig
  2806. }
  2807. func (asr *AssetSetRange) AggregateBy(aggregateBy []string, opts *AssetAggregationOptions) error {
  2808. aggRange := &AssetSetRange{Assets: []*AssetSet{}}
  2809. for _, as := range asr.Assets {
  2810. err := as.AggregateBy(aggregateBy, opts)
  2811. if err != nil {
  2812. return err
  2813. }
  2814. aggRange.Assets = append(aggRange.Assets, as)
  2815. }
  2816. asr.Assets = aggRange.Assets
  2817. return nil
  2818. }
  2819. func (asr *AssetSetRange) Append(that *AssetSet) {
  2820. asr.Assets = append(asr.Assets, that)
  2821. }
  2822. // Get provides bounds checked access into the AssetSetRange's AssetSets.
  2823. func (asr *AssetSetRange) Get(i int) (*AssetSet, error) {
  2824. if i < 0 || i >= len(asr.Assets) {
  2825. return nil, fmt.Errorf("AssetSetRange: index out of range: %d", i)
  2826. }
  2827. return asr.Assets[i], nil
  2828. }
  2829. // Length returns the total number of AssetSets in the range.
  2830. func (asr *AssetSetRange) Length() int {
  2831. if asr == nil {
  2832. return 0
  2833. }
  2834. return len(asr.Assets)
  2835. }
  2836. // InsertRange merges the given AssetSetRange into the receiving one by
  2837. // lining up sets with matching windows, then inserting each asset from
  2838. // the given ASR into the respective set in the receiving ASR. If the given
  2839. // ASR contains an AssetSetRange from a window that does not exist in the
  2840. // receiving ASR, then an error is returned. However, the given ASR does not
  2841. // need to cover the full range of the receiver.
  2842. func (asr *AssetSetRange) InsertRange(that *AssetSetRange) error {
  2843. if asr == nil {
  2844. return fmt.Errorf("cannot insert range into nil AssetSetRange")
  2845. }
  2846. // keys maps window to index in asr
  2847. keys := map[string]int{}
  2848. for i, as := range asr.Assets {
  2849. if as == nil {
  2850. continue
  2851. }
  2852. keys[as.Window.String()] = i
  2853. }
  2854. // Nothing to merge, so simply return
  2855. if len(keys) == 0 {
  2856. return nil
  2857. }
  2858. var err error
  2859. for _, thatAS := range that.Assets {
  2860. if thatAS == nil || err != nil {
  2861. continue
  2862. }
  2863. // Find matching AssetSet in asr
  2864. i, ok := keys[thatAS.Window.String()]
  2865. if !ok {
  2866. err = fmt.Errorf("cannot merge AssetSet into window that does not exist: %s", thatAS.Window.String())
  2867. continue
  2868. }
  2869. as, err := asr.Get(i)
  2870. if err != nil {
  2871. err = fmt.Errorf("AssetSetRange index does not exist: %d", i)
  2872. continue
  2873. }
  2874. // Insert each Asset from the given set
  2875. for _, asset := range thatAS.Assets {
  2876. err = as.Insert(asset, nil)
  2877. if err != nil {
  2878. err = fmt.Errorf("error inserting asset: %s", err)
  2879. continue
  2880. }
  2881. }
  2882. }
  2883. // err might be nil
  2884. return err
  2885. }
  2886. // IsEmpty returns false if AssetSetRange contains a single AssetSet that is not empty
  2887. func (asr *AssetSetRange) IsEmpty() bool {
  2888. if asr == nil || asr.Length() == 0 {
  2889. return true
  2890. }
  2891. for _, asset := range asr.Assets {
  2892. if !asset.IsEmpty() {
  2893. return false
  2894. }
  2895. }
  2896. return true
  2897. }
  2898. func (asr *AssetSetRange) MarshalJSON() ([]byte, error) {
  2899. if asr == nil {
  2900. return json.Marshal([]*AssetSet{})
  2901. }
  2902. return json.Marshal(asr.Assets)
  2903. }
  2904. // As with AssetSet, AssetSetRange does not serialize all its fields,
  2905. // making it impossible to reconstruct the AssetSetRange from its json.
  2906. // Therefore, the type a marshaled AssetSetRange unmarshals to is
  2907. // AssetSetRangeResponse
  2908. type AssetSetRangeResponse struct {
  2909. Assets []*AssetSetResponse
  2910. }
  2911. func (asr *AssetSetRange) UTCOffset() time.Duration {
  2912. if asr.Length() == 0 {
  2913. return 0
  2914. }
  2915. as, err := asr.Get(0)
  2916. if err != nil {
  2917. return 0
  2918. }
  2919. return as.UTCOffset()
  2920. }
  2921. // Window returns the full window that the AssetSetRange spans, from the
  2922. // start of the first AssetSet to the end of the last one.
  2923. func (asr *AssetSetRange) Window() Window {
  2924. if asr == nil || asr.Length() == 0 {
  2925. return NewWindow(nil, nil)
  2926. }
  2927. start := asr.Assets[0].Start()
  2928. end := asr.Assets[asr.Length()-1].End()
  2929. return NewWindow(&start, &end)
  2930. }
  2931. // Start returns the earliest start of all Assets in the AssetSetRange.
  2932. // It returns an error if there are no assets
  2933. func (asr *AssetSetRange) Start() (time.Time, error) {
  2934. start := time.Time{}
  2935. if asr == nil {
  2936. return start, fmt.Errorf("had no data to compute a start from")
  2937. }
  2938. firstStartNotSet := true
  2939. for _, as := range asr.Assets {
  2940. for _, a := range as.Assets {
  2941. if firstStartNotSet {
  2942. start = a.GetStart()
  2943. firstStartNotSet = false
  2944. }
  2945. if a.GetStart().Before(start) {
  2946. start = a.GetStart()
  2947. }
  2948. }
  2949. }
  2950. if firstStartNotSet {
  2951. return start, fmt.Errorf("had no data to compute a start from")
  2952. }
  2953. return start, nil
  2954. }
  2955. // End returns the latest end of all Assets in the AssetSetRange.
  2956. // It returns an error if there are no assets.
  2957. func (asr *AssetSetRange) End() (time.Time, error) {
  2958. end := time.Time{}
  2959. if asr == nil {
  2960. return end, fmt.Errorf("had no data to compute an end from")
  2961. }
  2962. firstEndNotSet := true
  2963. for _, as := range asr.Assets {
  2964. for _, a := range as.Assets {
  2965. if firstEndNotSet {
  2966. end = a.GetEnd()
  2967. firstEndNotSet = false
  2968. }
  2969. if a.GetEnd().After(end) {
  2970. end = a.GetEnd()
  2971. }
  2972. }
  2973. }
  2974. if firstEndNotSet {
  2975. return end, fmt.Errorf("had no data to compute an end from")
  2976. }
  2977. return end, nil
  2978. }
  2979. // Each iterates over all AssetSets in the AssetSetRange and returns the start and end over
  2980. // the entire range
  2981. func (asr *AssetSetRange) StartAndEnd() (time.Time, time.Time, error) {
  2982. start := time.Time{}
  2983. end := time.Time{}
  2984. if asr == nil {
  2985. return start, end, fmt.Errorf("had no data to compute a start and end from")
  2986. }
  2987. firstStartNotSet := true
  2988. firstEndNotSet := true
  2989. for _, as := range asr.Assets {
  2990. for _, a := range as.Assets {
  2991. if firstStartNotSet {
  2992. start = a.GetStart()
  2993. firstStartNotSet = false
  2994. }
  2995. if a.GetStart().Before(start) {
  2996. start = a.GetStart()
  2997. }
  2998. if firstEndNotSet {
  2999. end = a.GetEnd()
  3000. firstEndNotSet = false
  3001. }
  3002. if a.GetEnd().After(end) {
  3003. end = a.GetEnd()
  3004. }
  3005. }
  3006. }
  3007. if firstStartNotSet {
  3008. return start, end, fmt.Errorf("had no data to compute a start from")
  3009. }
  3010. if firstEndNotSet {
  3011. return start, end, fmt.Errorf("had no data to compute an end from")
  3012. }
  3013. return start, end, nil
  3014. }
  3015. // Minutes returns the duration, in minutes, between the earliest start
  3016. // and the latest end of all assets in the AssetSetRange.
  3017. func (asr *AssetSetRange) Minutes() float64 {
  3018. if asr == nil {
  3019. return 0
  3020. }
  3021. start, end, err := asr.StartAndEnd()
  3022. if err != nil {
  3023. return 0
  3024. }
  3025. duration := end.Sub(start)
  3026. return duration.Minutes()
  3027. }
  3028. // TotalCost returns the AssetSetRange's total cost
  3029. func (asr *AssetSetRange) TotalCost() float64 {
  3030. if asr == nil {
  3031. return 0.0
  3032. }
  3033. tc := 0.0
  3034. for _, as := range asr.Assets {
  3035. tc += as.TotalCost()
  3036. }
  3037. return tc
  3038. }
  3039. // This is a helper type. The Asset API returns a json which cannot be natively
  3040. // unmarshaled into any Asset struct. Therefore, this struct IN COMBINATION WITH
  3041. // DESERIALIZATION LOGIC DEFINED IN asset_json.go can unmarshal a json directly
  3042. // from an Assets API query
  3043. type AssetAPIResponse struct {
  3044. Code int `json:"code"`
  3045. Data AssetSetRangeResponse `json:"data"`
  3046. }
  3047. // Returns true if string slices a and b contain all of the same strings, in any order.
  3048. func sameContents(a, b []string) bool {
  3049. if len(a) != len(b) {
  3050. return false
  3051. }
  3052. for i := range a {
  3053. if !contains(b, a[i]) {
  3054. return false
  3055. }
  3056. }
  3057. return true
  3058. }
  3059. func contains(slice []string, item string) bool {
  3060. for _, element := range slice {
  3061. if element == item {
  3062. return true
  3063. }
  3064. }
  3065. return false
  3066. }