asset.go 107 KB

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