asset.go 90 KB

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