asset.go 76 KB

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