asset.go 107 KB

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