asset.go 89 KB

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