asset.go 107 KB

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