asset.go 97 KB

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