asset.go 78 KB

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