asset.go 75 KB

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