costmodel.go 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610
  1. package costmodel
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/opencost/opencost/core/pkg/clusters"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/core/pkg/opencost"
  13. "github.com/opencost/opencost/core/pkg/source"
  14. "github.com/opencost/opencost/core/pkg/util"
  15. "github.com/opencost/opencost/core/pkg/util/promutil"
  16. costAnalyzerCloud "github.com/opencost/opencost/pkg/cloud/models"
  17. "github.com/opencost/opencost/pkg/clustercache"
  18. "github.com/opencost/opencost/pkg/env"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/labels"
  22. "golang.org/x/sync/singleflight"
  23. )
  24. const (
  25. statusAPIError = 422
  26. profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
  27. unmountedPVsContainer = "unmounted-pvs"
  28. )
  29. // isCron matches a CronJob name and captures the non-timestamp name
  30. //
  31. // We support either a 10 character timestamp OR an 8 character timestamp
  32. // because batch/v1beta1 CronJobs creates Jobs with 10 character timestamps
  33. // and batch/v1 CronJobs create Jobs with 8 character timestamps.
  34. var isCron = regexp.MustCompile(`^(.+)-(\d{10}|\d{8})$`)
  35. type CostModel struct {
  36. Cache clustercache.ClusterCache
  37. ClusterMap clusters.ClusterMap
  38. BatchDuration time.Duration
  39. RequestGroup *singleflight.Group
  40. DataSource source.OpenCostDataSource
  41. Provider costAnalyzerCloud.Provider
  42. pricingMetadata *costAnalyzerCloud.PricingMatchMetadata
  43. }
  44. func NewCostModel(
  45. dataSource source.OpenCostDataSource,
  46. provider costAnalyzerCloud.Provider,
  47. cache clustercache.ClusterCache,
  48. clusterMap clusters.ClusterMap,
  49. batchDuration time.Duration,
  50. ) *CostModel {
  51. // request grouping to prevent over-requesting the same data prior to caching
  52. requestGroup := new(singleflight.Group)
  53. return &CostModel{
  54. Cache: cache,
  55. ClusterMap: clusterMap,
  56. BatchDuration: batchDuration,
  57. DataSource: dataSource,
  58. Provider: provider,
  59. RequestGroup: requestGroup,
  60. }
  61. }
  62. type CostData struct {
  63. Name string `json:"name,omitempty"`
  64. PodName string `json:"podName,omitempty"`
  65. NodeName string `json:"nodeName,omitempty"`
  66. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  67. Namespace string `json:"namespace,omitempty"`
  68. Deployments []string `json:"deployments,omitempty"`
  69. Services []string `json:"services,omitempty"`
  70. Daemonsets []string `json:"daemonsets,omitempty"`
  71. Statefulsets []string `json:"statefulsets,omitempty"`
  72. Jobs []string `json:"jobs,omitempty"`
  73. RAMReq []*util.Vector `json:"ramreq,omitempty"`
  74. RAMUsed []*util.Vector `json:"ramused,omitempty"`
  75. RAMAllocation []*util.Vector `json:"ramallocated,omitempty"`
  76. CPUReq []*util.Vector `json:"cpureq,omitempty"`
  77. CPUUsed []*util.Vector `json:"cpuused,omitempty"`
  78. CPUAllocation []*util.Vector `json:"cpuallocated,omitempty"`
  79. GPUReq []*util.Vector `json:"gpureq,omitempty"`
  80. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  81. NetworkData []*util.Vector `json:"network,omitempty"`
  82. Annotations map[string]string `json:"annotations,omitempty"`
  83. Labels map[string]string `json:"labels,omitempty"`
  84. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  85. ClusterID string `json:"clusterId"`
  86. ClusterName string `json:"clusterName"`
  87. }
  88. func (cd *CostData) String() string {
  89. return fmt.Sprintf("\n\tName: %s; PodName: %s, NodeName: %s\n\tNamespace: %s\n\tDeployments: %s\n\tServices: %s\n\tCPU (req, used, alloc): %d, %d, %d\n\tRAM (req, used, alloc): %d, %d, %d",
  90. cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
  91. len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
  92. len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
  93. }
  94. func (cd *CostData) GetController() (name string, kind string, hasController bool) {
  95. hasController = false
  96. if len(cd.Deployments) > 0 {
  97. name = cd.Deployments[0]
  98. kind = "deployment"
  99. hasController = true
  100. } else if len(cd.Statefulsets) > 0 {
  101. name = cd.Statefulsets[0]
  102. kind = "statefulset"
  103. hasController = true
  104. } else if len(cd.Daemonsets) > 0 {
  105. name = cd.Daemonsets[0]
  106. kind = "daemonset"
  107. hasController = true
  108. } else if len(cd.Jobs) > 0 {
  109. name = cd.Jobs[0]
  110. kind = "job"
  111. hasController = true
  112. match := isCron.FindStringSubmatch(name)
  113. if match != nil {
  114. name = match[1]
  115. }
  116. }
  117. return name, kind, hasController
  118. }
  119. func (cm *CostModel) ComputeCostData(window string, offset string, filterNamespace string) (map[string]*CostData, error) {
  120. // Cluster ID is specific to the source cluster
  121. clusterID := env.GetClusterID()
  122. cp := cm.Provider
  123. grp := source.NewQueryGroup()
  124. resChRAMUsage := grp.With(cm.DataSource.QueryRAMUsage(window, offset))
  125. resChCPUUsage := grp.With(cm.DataSource.QueryCPUUsage(window, offset))
  126. resChNetZoneRequests := grp.With(cm.DataSource.QueryNetworkInZoneRequests(window, offset))
  127. resChNetRegionRequests := grp.With(cm.DataSource.QueryNetworkInRegionRequests(window, offset))
  128. resChNetInternetRequests := grp.With(cm.DataSource.QueryNetworkInternetRequests(window, offset))
  129. resChNormalization := grp.With(cm.DataSource.QueryNormalization(window, offset))
  130. // Pull pod information from k8s API
  131. podlist := cm.Cache.GetAllPods()
  132. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  133. if err != nil {
  134. return nil, err
  135. }
  136. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  137. if err != nil {
  138. return nil, err
  139. }
  140. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  141. if err != nil {
  142. return nil, err
  143. }
  144. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  145. if err != nil {
  146. return nil, err
  147. }
  148. // Process Prometheus query results. Handle errors using ctx.Errors.
  149. resRAMUsage, _ := resChRAMUsage.Await()
  150. resCPUUsage, _ := resChCPUUsage.Await()
  151. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  152. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  153. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  154. resNormalization, _ := resChNormalization.Await()
  155. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  156. // NOTE: will not propagate unless coupled with errors.
  157. if grp.HasErrors() {
  158. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  159. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  160. for _, queryErr := range grp.Errors() {
  161. if queryErr.Error != nil {
  162. log.Errorf("ComputeCostData: Request Error: %s", queryErr.Error)
  163. }
  164. if queryErr.ParseError != nil {
  165. log.Errorf("ComputeCostData: Parsing Error: %s", queryErr.ParseError)
  166. }
  167. }
  168. // ErrorCollection is an collection of errors wrapped in a single error implementation
  169. // We opt to not return an error for the sake of running as a pure exporter.
  170. log.Warnf("ComputeCostData: continuing despite prometheus errors: %s", grp.Error())
  171. }
  172. defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
  173. normalizationValue, err := getNormalization(resNormalization)
  174. if err != nil {
  175. // We opt to not return an error for the sake of running as a pure exporter.
  176. log.Warnf("ComputeCostData: continuing despite error parsing normalization values: %s", err.Error())
  177. }
  178. nodes, err := cm.GetNodeCost(cp)
  179. if err != nil {
  180. log.Warnf("GetNodeCost: no node cost model available: " + err.Error())
  181. return nil, err
  182. }
  183. // Unmounted PVs represent the PVs that are not mounted or tied to a volume on a container
  184. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  185. pvClaimMapping, err := GetPVInfoLocal(cm.Cache, clusterID)
  186. if err != nil {
  187. log.Warnf("GetPVInfo: unable to get PV data: %s", err.Error())
  188. }
  189. if pvClaimMapping != nil {
  190. err = addPVData(cm.Cache, pvClaimMapping, cp)
  191. if err != nil {
  192. return nil, err
  193. }
  194. // copy claim mappings into zombies, then remove as they're discovered
  195. for k, v := range pvClaimMapping {
  196. unmountedPVs[k] = []*PersistentVolumeClaimData{v}
  197. }
  198. }
  199. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  200. if err != nil {
  201. log.Warnf("Unable to get Network Cost Data: %s", err.Error())
  202. networkUsageMap = make(map[string]*NetworkUsageData)
  203. }
  204. containerNameCost := make(map[string]*CostData)
  205. containers := make(map[string]bool)
  206. RAMUsedMap, err := GetContainerMetricVector(resRAMUsage, true, normalizationValue, clusterID)
  207. if err != nil {
  208. return nil, err
  209. }
  210. for key := range RAMUsedMap {
  211. containers[key] = true
  212. }
  213. CPUUsedMap, err := GetContainerMetricVector(resCPUUsage, false, 0, clusterID) // No need to normalize here, as this comes from a counter
  214. if err != nil {
  215. return nil, err
  216. }
  217. for key := range CPUUsedMap {
  218. containers[key] = true
  219. }
  220. currentContainers := make(map[string]clustercache.Pod)
  221. for _, pod := range podlist {
  222. if pod.Status.Phase != v1.PodRunning {
  223. continue
  224. }
  225. cs, err := NewContainerMetricsFromPod(pod, clusterID)
  226. if err != nil {
  227. return nil, err
  228. }
  229. for _, c := range cs {
  230. containers[c.Key()] = true // captures any containers that existed for a time < a prometheus scrape interval. We currently charge 0 for this but should charge something.
  231. currentContainers[c.Key()] = *pod
  232. }
  233. }
  234. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  235. missingContainers := make(map[string]*CostData)
  236. for key := range containers {
  237. if _, ok := containerNameCost[key]; ok {
  238. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  239. }
  240. // The _else_ case for this statement is the case in which the container has been
  241. // deleted so we have usage information but not request information. In that case,
  242. // we return partial data for CPU and RAM: only usage and not requests.
  243. if pod, ok := currentContainers[key]; ok {
  244. podName := pod.Name
  245. ns := pod.Namespace
  246. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  247. podLabels := pod.Labels
  248. if podLabels == nil {
  249. podLabels = make(map[string]string)
  250. }
  251. for k, v := range nsLabels {
  252. if _, ok := podLabels[k]; !ok {
  253. podLabels[k] = v
  254. }
  255. }
  256. nsAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
  257. podAnnotations := pod.Annotations
  258. if podAnnotations == nil {
  259. podAnnotations = make(map[string]string)
  260. }
  261. for k, v := range nsAnnotations {
  262. if _, ok := podAnnotations[k]; !ok {
  263. podAnnotations[k] = v
  264. }
  265. }
  266. nodeName := pod.Spec.NodeName
  267. var nodeData *costAnalyzerCloud.Node
  268. if _, ok := nodes[nodeName]; ok {
  269. nodeData = nodes[nodeName]
  270. }
  271. nsKey := ns + "," + clusterID
  272. var podDeployments []string
  273. if _, ok := podDeploymentsMapping[nsKey]; ok {
  274. if ds, ok := podDeploymentsMapping[nsKey][pod.Name]; ok {
  275. podDeployments = ds
  276. } else {
  277. podDeployments = []string{}
  278. }
  279. }
  280. var podPVs []*PersistentVolumeClaimData
  281. podClaims := pod.Spec.Volumes
  282. for _, vol := range podClaims {
  283. if vol.PersistentVolumeClaim != nil {
  284. name := vol.PersistentVolumeClaim.ClaimName
  285. key := ns + "," + name + "," + clusterID
  286. if pvClaim, ok := pvClaimMapping[key]; ok {
  287. pvClaim.TimesClaimed++
  288. podPVs = append(podPVs, pvClaim)
  289. // Remove entry from potential unmounted pvs
  290. delete(unmountedPVs, key)
  291. }
  292. }
  293. }
  294. var podNetCosts []*util.Vector
  295. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  296. netCosts, err := GetNetworkCost(usage, cp)
  297. if err != nil {
  298. log.Debugf("Error pulling network costs: %s", err.Error())
  299. } else {
  300. podNetCosts = netCosts
  301. }
  302. }
  303. var podServices []string
  304. if _, ok := podServicesMapping[nsKey]; ok {
  305. if svcs, ok := podServicesMapping[nsKey][pod.Name]; ok {
  306. podServices = svcs
  307. } else {
  308. podServices = []string{}
  309. }
  310. }
  311. for i, container := range pod.Spec.Containers {
  312. containerName := container.Name
  313. // recreate the key and look up data for this container
  314. newKey := NewContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  315. // k8s.io/apimachinery/pkg/api/resource/amount.go and
  316. // k8s.io/apimachinery/pkg/api/resource/quantity.go for
  317. // details on the "amount" API. See
  318. // https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-types
  319. // for the units of memory and CPU.
  320. ramRequestBytes := container.Resources.Requests.Memory().Value()
  321. // Because information on container RAM & CPU requests isn't
  322. // coming from Prometheus, it won't have a timestamp associated
  323. // with it. We need to provide a timestamp.
  324. RAMReqV := []*util.Vector{
  325. {
  326. Value: float64(ramRequestBytes),
  327. Timestamp: float64(time.Now().UTC().Unix()),
  328. },
  329. }
  330. // use millicores so we can convert to cores in a float64 format
  331. cpuRequestMilliCores := container.Resources.Requests.Cpu().MilliValue()
  332. CPUReqV := []*util.Vector{
  333. {
  334. Value: float64(cpuRequestMilliCores) / 1000,
  335. Timestamp: float64(time.Now().UTC().Unix()),
  336. },
  337. }
  338. gpuReqCount := 0.0
  339. if g, ok := container.Resources.Requests["nvidia.com/gpu"]; ok {
  340. gpuReqCount = g.AsApproximateFloat64()
  341. } else if g, ok := container.Resources.Limits["nvidia.com/gpu"]; ok {
  342. gpuReqCount = g.AsApproximateFloat64()
  343. } else if g, ok := container.Resources.Requests["k8s.amazonaws.com/vgpu"]; ok {
  344. gpuReqCount = g.AsApproximateFloat64()
  345. } else if g, ok := container.Resources.Limits["k8s.amazonaws.com/vgpu"]; ok {
  346. gpuReqCount = g.AsApproximateFloat64()
  347. }
  348. GPUReqV := []*util.Vector{
  349. {
  350. Value: float64(gpuReqCount),
  351. Timestamp: float64(time.Now().UTC().Unix()),
  352. },
  353. }
  354. RAMUsedV, ok := RAMUsedMap[newKey]
  355. if !ok {
  356. log.Debug("no RAM usage for " + newKey)
  357. RAMUsedV = []*util.Vector{{}}
  358. }
  359. CPUUsedV, ok := CPUUsedMap[newKey]
  360. if !ok {
  361. log.Debug("no CPU usage for " + newKey)
  362. CPUUsedV = []*util.Vector{{}}
  363. }
  364. var pvReq []*PersistentVolumeClaimData
  365. var netReq []*util.Vector
  366. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  367. pvReq = podPVs
  368. netReq = podNetCosts
  369. }
  370. costs := &CostData{
  371. Name: containerName,
  372. PodName: podName,
  373. NodeName: nodeName,
  374. Namespace: ns,
  375. Deployments: podDeployments,
  376. Services: podServices,
  377. Daemonsets: getDaemonsetsOfPod(pod),
  378. Jobs: getJobsOfPod(pod),
  379. Statefulsets: getStatefulSetsOfPod(pod),
  380. NodeData: nodeData,
  381. RAMReq: RAMReqV,
  382. RAMUsed: RAMUsedV,
  383. CPUReq: CPUReqV,
  384. CPUUsed: CPUUsedV,
  385. GPUReq: GPUReqV,
  386. PVCData: pvReq,
  387. NetworkData: netReq,
  388. Annotations: podAnnotations,
  389. Labels: podLabels,
  390. NamespaceLabels: nsLabels,
  391. ClusterID: clusterID,
  392. ClusterName: cm.ClusterMap.NameFor(clusterID),
  393. }
  394. var cpuReq, cpuUse *util.Vector
  395. if len(costs.CPUReq) > 0 {
  396. cpuReq = costs.CPUReq[0]
  397. }
  398. if len(costs.CPUUsed) > 0 {
  399. cpuUse = costs.CPUUsed[0]
  400. }
  401. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  402. var ramReq, ramUse *util.Vector
  403. if len(costs.RAMReq) > 0 {
  404. ramReq = costs.RAMReq[0]
  405. }
  406. if len(costs.RAMUsed) > 0 {
  407. ramUse = costs.RAMUsed[0]
  408. }
  409. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  410. if filterNamespace == "" {
  411. containerNameCost[newKey] = costs
  412. } else if costs.Namespace == filterNamespace {
  413. containerNameCost[newKey] = costs
  414. }
  415. }
  416. } else {
  417. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  418. log.Debug("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  419. c, err := NewContainerMetricFromKey(key)
  420. if err != nil {
  421. return nil, err
  422. }
  423. // CPU and RAM requests are obtained from the Kubernetes API.
  424. // If this case has been reached, the Kubernetes API will not
  425. // have information about the pod because it no longer exists.
  426. //
  427. // The case where this matters is minimal, mainly in environments
  428. // with very short-lived pods that over-request resources.
  429. RAMReqV := []*util.Vector{{}}
  430. CPUReqV := []*util.Vector{{}}
  431. GPUReqV := []*util.Vector{{}}
  432. RAMUsedV, ok := RAMUsedMap[key]
  433. if !ok {
  434. log.Debug("no RAM usage for " + key)
  435. RAMUsedV = []*util.Vector{{}}
  436. }
  437. CPUUsedV, ok := CPUUsedMap[key]
  438. if !ok {
  439. log.Debug("no CPU usage for " + key)
  440. CPUUsedV = []*util.Vector{{}}
  441. }
  442. node, ok := nodes[c.NodeName]
  443. if !ok {
  444. log.Debugf("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  445. if n, ok := missingNodes[c.NodeName]; ok {
  446. node = n
  447. } else {
  448. node = &costAnalyzerCloud.Node{}
  449. missingNodes[c.NodeName] = node
  450. }
  451. }
  452. namespacelabels, _ := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
  453. namespaceAnnotations, _ := namespaceAnnotationsMapping[c.Namespace+","+c.ClusterID]
  454. costs := &CostData{
  455. Name: c.ContainerName,
  456. PodName: c.PodName,
  457. NodeName: c.NodeName,
  458. NodeData: node,
  459. Namespace: c.Namespace,
  460. RAMReq: RAMReqV,
  461. RAMUsed: RAMUsedV,
  462. CPUReq: CPUReqV,
  463. CPUUsed: CPUUsedV,
  464. GPUReq: GPUReqV,
  465. Annotations: namespaceAnnotations,
  466. NamespaceLabels: namespacelabels,
  467. ClusterID: c.ClusterID,
  468. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  469. }
  470. var cpuReq, cpuUse *util.Vector
  471. if len(costs.CPUReq) > 0 {
  472. cpuReq = costs.CPUReq[0]
  473. }
  474. if len(costs.CPUUsed) > 0 {
  475. cpuUse = costs.CPUUsed[0]
  476. }
  477. costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
  478. var ramReq, ramUse *util.Vector
  479. if len(costs.RAMReq) > 0 {
  480. ramReq = costs.RAMReq[0]
  481. }
  482. if len(costs.RAMUsed) > 0 {
  483. ramUse = costs.RAMUsed[0]
  484. }
  485. costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
  486. if filterNamespace == "" {
  487. containerNameCost[key] = costs
  488. missingContainers[key] = costs
  489. } else if costs.Namespace == filterNamespace {
  490. containerNameCost[key] = costs
  491. missingContainers[key] = costs
  492. }
  493. }
  494. }
  495. // Use unmounted pvs to create a mapping of "Unmounted-<Namespace>" containers
  496. // to pass along the cost data
  497. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  498. for k, costs := range unmounted {
  499. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  500. if filterNamespace == "" {
  501. containerNameCost[k] = costs
  502. } else if costs.Namespace == filterNamespace {
  503. containerNameCost[k] = costs
  504. }
  505. }
  506. err = findDeletedNodeInfo(cm.DataSource, missingNodes, window, "")
  507. if err != nil {
  508. log.Errorf("Error fetching historical node data: %s", err.Error())
  509. }
  510. err = findDeletedPodInfo(cm.DataSource, missingContainers, window)
  511. if err != nil {
  512. log.Errorf("Error fetching historical pod data: %s", err.Error())
  513. }
  514. return containerNameCost, err
  515. }
  516. func findUnmountedPVCostData(clusterMap clusters.ClusterMap, unmountedPVs map[string][]*PersistentVolumeClaimData, namespaceLabelsMapping map[string]map[string]string, namespaceAnnotationsMapping map[string]map[string]string) map[string]*CostData {
  517. costs := make(map[string]*CostData)
  518. if len(unmountedPVs) == 0 {
  519. return costs
  520. }
  521. for k, pv := range unmountedPVs {
  522. keyParts := strings.Split(k, ",")
  523. if len(keyParts) != 3 {
  524. log.Warnf("Unmounted PV used key with incorrect parts: %s", k)
  525. continue
  526. }
  527. ns, _, clusterID := keyParts[0], keyParts[1], keyParts[2]
  528. namespacelabels, _ := namespaceLabelsMapping[ns+","+clusterID]
  529. namespaceAnnotations, _ := namespaceAnnotationsMapping[ns+","+clusterID]
  530. metric := NewContainerMetricFromValues(ns, unmountedPVsContainer, unmountedPVsContainer, "", clusterID)
  531. key := metric.Key()
  532. if costData, ok := costs[key]; !ok {
  533. costs[key] = &CostData{
  534. Name: unmountedPVsContainer,
  535. PodName: unmountedPVsContainer,
  536. NodeName: "",
  537. Annotations: namespaceAnnotations,
  538. Namespace: ns,
  539. NamespaceLabels: namespacelabels,
  540. Labels: namespacelabels,
  541. ClusterID: clusterID,
  542. ClusterName: clusterMap.NameFor(clusterID),
  543. PVCData: pv,
  544. }
  545. } else {
  546. costData.PVCData = append(costData.PVCData, pv...)
  547. }
  548. }
  549. return costs
  550. }
  551. func findDeletedPodInfo(dataSource source.OpenCostDataSource, missingContainers map[string]*CostData, window string) error {
  552. if len(missingContainers) > 0 {
  553. podLabelsResCh := dataSource.QueryHistoricalPodLabels(window, "")
  554. podLabelsResult, err := podLabelsResCh.Await()
  555. if err != nil {
  556. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  557. }
  558. podLabels := make(map[string]map[string]string)
  559. if podLabelsResult != nil {
  560. podLabels, err = parsePodLabels(podLabelsResult)
  561. if err != nil {
  562. log.Errorf("failed to parse historical pod labels: %s", err.Error())
  563. }
  564. }
  565. for key, costData := range missingContainers {
  566. cm, _ := NewContainerMetricFromKey(key)
  567. labels, ok := podLabels[cm.PodName]
  568. if !ok {
  569. labels = make(map[string]string)
  570. }
  571. for k, v := range costData.NamespaceLabels {
  572. labels[k] = v
  573. }
  574. costData.Labels = labels
  575. }
  576. }
  577. return nil
  578. }
  579. func findDeletedNodeInfo(dataSource source.OpenCostDataSource, missingNodes map[string]*costAnalyzerCloud.Node, window, offset string) error {
  580. if len(missingNodes) > 0 {
  581. defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
  582. grp := source.NewQueryGroup()
  583. cpuCostResCh := grp.With(dataSource.QueryHistoricalCPUCost(window, offset))
  584. ramCostResCh := grp.With(dataSource.QueryHistoricalRAMCost(window, offset))
  585. gpuCostResCh := grp.With(dataSource.QueryHistoricalGPUCost(window, offset))
  586. cpuCostRes, _ := cpuCostResCh.Await()
  587. ramCostRes, _ := ramCostResCh.Await()
  588. gpuCostRes, _ := gpuCostResCh.Await()
  589. if grp.HasErrors() {
  590. return grp.Error()
  591. }
  592. cpuCosts, err := getCost(cpuCostRes)
  593. if err != nil {
  594. return err
  595. }
  596. ramCosts, err := getCost(ramCostRes)
  597. if err != nil {
  598. return err
  599. }
  600. gpuCosts, err := getCost(gpuCostRes)
  601. if err != nil {
  602. return err
  603. }
  604. if len(cpuCosts) == 0 {
  605. log.Infof("Kubecost prometheus metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
  606. }
  607. for node, costv := range cpuCosts {
  608. if _, ok := missingNodes[node]; ok {
  609. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  610. } else {
  611. log.DedupedWarningf(5, "Node `%s` in prometheus but not k8s api", node)
  612. }
  613. }
  614. for node, costv := range ramCosts {
  615. if _, ok := missingNodes[node]; ok {
  616. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  617. }
  618. }
  619. for node, costv := range gpuCosts {
  620. if _, ok := missingNodes[node]; ok {
  621. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  622. }
  623. }
  624. }
  625. return nil
  626. }
  627. // getContainerAllocation takes the max between request and usage. This function
  628. // returns a slice containing a single element describing the container's
  629. // allocation.
  630. //
  631. // Additionally, the timestamp of the allocation will be the highest value
  632. // timestamp between the two vectors. This mitigates situations where
  633. // Timestamp=0. This should have no effect on the metrics emitted by the
  634. // CostModelMetricsEmitter
  635. func getContainerAllocation(req *util.Vector, used *util.Vector, allocationType string) []*util.Vector {
  636. var result []*util.Vector
  637. if req != nil && used != nil {
  638. x1 := req.Value
  639. if math.IsNaN(x1) {
  640. log.Debugf("NaN value found during %s allocation calculation for requests.", allocationType)
  641. x1 = 0.0
  642. }
  643. y1 := used.Value
  644. if math.IsNaN(y1) {
  645. log.Debugf("NaN value found during %s allocation calculation for used.", allocationType)
  646. y1 = 0.0
  647. }
  648. result = []*util.Vector{
  649. {
  650. Value: math.Max(x1, y1),
  651. Timestamp: math.Max(req.Timestamp, used.Timestamp),
  652. },
  653. }
  654. if result[0].Value == 0 && result[0].Timestamp == 0 {
  655. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  656. }
  657. } else if req != nil {
  658. result = []*util.Vector{
  659. {
  660. Value: req.Value,
  661. Timestamp: req.Timestamp,
  662. },
  663. }
  664. } else if used != nil {
  665. result = []*util.Vector{
  666. {
  667. Value: used.Value,
  668. Timestamp: used.Timestamp,
  669. },
  670. }
  671. } else {
  672. log.Debugf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
  673. result = []*util.Vector{
  674. {
  675. Value: 0,
  676. Timestamp: float64(time.Now().UTC().Unix()),
  677. },
  678. }
  679. }
  680. return result
  681. }
  682. func addPVData(cache clustercache.ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  683. cfg, err := cloud.GetConfig()
  684. if err != nil {
  685. return err
  686. }
  687. // Pull a region from the first node
  688. var defaultRegion string
  689. nodeList := cache.GetAllNodes()
  690. if len(nodeList) > 0 {
  691. defaultRegion, _ = util.GetRegion(nodeList[0].Labels)
  692. }
  693. storageClasses := cache.GetAllStorageClasses()
  694. storageClassMap := make(map[string]map[string]string)
  695. for _, storageClass := range storageClasses {
  696. params := storageClass.Parameters
  697. storageClassMap[storageClass.Name] = params
  698. if storageClass.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  699. storageClassMap["default"] = params
  700. storageClassMap[""] = params
  701. }
  702. }
  703. pvs := cache.GetAllPersistentVolumes()
  704. pvMap := make(map[string]*costAnalyzerCloud.PV)
  705. for _, pv := range pvs {
  706. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  707. if !ok {
  708. log.Debugf("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  709. }
  710. var region string
  711. if r, ok := util.GetRegion(pv.Labels); ok {
  712. region = r
  713. } else {
  714. region = defaultRegion
  715. }
  716. cacPv := &costAnalyzerCloud.PV{
  717. Class: pv.Spec.StorageClassName,
  718. Region: region,
  719. Parameters: parameters,
  720. }
  721. err := GetPVCost(cacPv, pv, cloud, region)
  722. if err != nil {
  723. return err
  724. }
  725. pvMap[pv.Name] = cacPv
  726. }
  727. for _, pvc := range pvClaimMapping {
  728. if vol, ok := pvMap[pvc.VolumeName]; ok {
  729. pvc.Volume = vol
  730. } else {
  731. log.Debugf("PV not found, using default")
  732. pvc.Volume = &costAnalyzerCloud.PV{
  733. Cost: cfg.Storage,
  734. }
  735. }
  736. }
  737. return nil
  738. }
  739. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *clustercache.PersistentVolume, cp costAnalyzerCloud.Provider, defaultRegion string) error {
  740. cfg, err := cp.GetConfig()
  741. if err != nil {
  742. return err
  743. }
  744. key := cp.GetPVKey(kpv, pv.Parameters, defaultRegion)
  745. pv.ProviderID = key.ID()
  746. pvWithCost, err := cp.PVPricing(key)
  747. if err != nil {
  748. pv.Cost = cfg.Storage
  749. return err
  750. }
  751. if pvWithCost == nil || pvWithCost.Cost == "" {
  752. pv.Cost = cfg.Storage
  753. return nil // set default cost
  754. }
  755. pv.Cost = pvWithCost.Cost
  756. return nil
  757. }
  758. func (cm *CostModel) GetPricingSourceCounts() (*costAnalyzerCloud.PricingMatchMetadata, error) {
  759. if cm.pricingMetadata != nil {
  760. return cm.pricingMetadata, nil
  761. } else {
  762. return nil, fmt.Errorf("Node costs not yet calculated")
  763. }
  764. }
  765. func (cm *CostModel) GetNodeCost(cp costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  766. cfg, err := cp.GetConfig()
  767. if err != nil {
  768. return nil, err
  769. }
  770. nodeList := cm.Cache.GetAllNodes()
  771. nodes := make(map[string]*costAnalyzerCloud.Node)
  772. pmd := &costAnalyzerCloud.PricingMatchMetadata{
  773. TotalNodes: 0,
  774. PricingTypeCounts: make(map[costAnalyzerCloud.PricingType]int),
  775. }
  776. for _, n := range nodeList {
  777. name := n.Name
  778. nodeLabels := n.Labels
  779. nodeLabels["providerID"] = n.SpecProviderID
  780. pmd.TotalNodes++
  781. cnode, _, err := cp.NodePricing(cp.GetKey(nodeLabels, n))
  782. if err != nil {
  783. log.Infof("Error getting node pricing. Error: %s", err.Error())
  784. if cnode != nil {
  785. nodes[name] = cnode
  786. continue
  787. } else {
  788. cnode = &costAnalyzerCloud.Node{
  789. VCPUCost: cfg.CPU,
  790. RAMCost: cfg.RAM,
  791. }
  792. }
  793. }
  794. if _, ok := pmd.PricingTypeCounts[cnode.PricingType]; ok {
  795. pmd.PricingTypeCounts[cnode.PricingType]++
  796. } else {
  797. pmd.PricingTypeCounts[cnode.PricingType] = 1
  798. }
  799. // newCnode builds upon cnode but populates/overrides certain fields.
  800. // cnode was populated leveraging cloud provider public pricing APIs.
  801. newCnode := *cnode
  802. if newCnode.InstanceType == "" {
  803. it, _ := util.GetInstanceType(n.Labels)
  804. newCnode.InstanceType = it
  805. }
  806. if newCnode.Region == "" {
  807. region, _ := util.GetRegion(n.Labels)
  808. newCnode.Region = region
  809. }
  810. if newCnode.ArchType == "" {
  811. arch, _ := util.GetArchType(n.Labels)
  812. newCnode.ArchType = arch
  813. }
  814. newCnode.ProviderID = n.SpecProviderID
  815. var cpu float64
  816. if newCnode.VCPU == "" {
  817. cpu = float64(n.Status.Capacity.Cpu().Value())
  818. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  819. } else {
  820. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  821. if err != nil {
  822. log.Warnf("parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  823. }
  824. }
  825. if math.IsNaN(cpu) {
  826. log.Warnf("cpu parsed as NaN. Setting to 0.")
  827. cpu = 0
  828. }
  829. var ram float64
  830. if newCnode.RAM == "" {
  831. newCnode.RAM = n.Status.Capacity.Memory().String()
  832. }
  833. ram = float64(n.Status.Capacity.Memory().Value())
  834. if math.IsNaN(ram) {
  835. log.Warnf("ram parsed as NaN. Setting to 0.")
  836. ram = 0
  837. }
  838. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  839. gpuc, err := strconv.ParseFloat(newCnode.GPU, 64)
  840. if err != nil {
  841. gpuc = 0.0
  842. }
  843. // The k8s API will often report more accurate results for GPU count
  844. // than cloud provider public pricing APIs. If found, override the
  845. // original value.
  846. gpuOverride, vgpuOverride, err := getGPUCount(cm.Cache, n)
  847. if err != nil {
  848. log.Warnf("Unable to get GPUCount for node %s: %s", n.Name, err.Error())
  849. }
  850. if gpuOverride > 0 {
  851. newCnode.GPU = fmt.Sprintf("%f", gpuOverride)
  852. gpuc = gpuOverride
  853. }
  854. if vgpuOverride > 0 {
  855. newCnode.VGPU = fmt.Sprintf("%f", vgpuOverride)
  856. }
  857. // Special case for SUSE rancher, since it won't behave with normal
  858. // calculations, courtesy of the instance type not being "real" (a
  859. // recognizable AWS instance type.)
  860. if newCnode.InstanceType == "rke2" {
  861. log.Infof(
  862. "Found a SUSE Rancher node %s, defaulting and skipping math",
  863. cp.GetKey(nodeLabels, n).Features(),
  864. )
  865. defaultCPUCorePrice, err := strconv.ParseFloat(cfg.CPU, 64)
  866. if err != nil {
  867. log.Errorf("Could not parse default cpu price")
  868. defaultCPUCorePrice = 0
  869. }
  870. if math.IsNaN(defaultCPUCorePrice) {
  871. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  872. defaultCPUCorePrice = 0
  873. }
  874. defaultRAMPrice, err := strconv.ParseFloat(cfg.RAM, 64)
  875. if err != nil {
  876. log.Errorf("Could not parse default ram price")
  877. defaultRAMPrice = 0
  878. }
  879. if math.IsNaN(defaultRAMPrice) {
  880. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  881. defaultRAMPrice = 0
  882. }
  883. defaultGPUPrice, err := strconv.ParseFloat(cfg.GPU, 64)
  884. if err != nil {
  885. log.Errorf("Could not parse default gpu price")
  886. defaultGPUPrice = 0
  887. }
  888. if math.IsNaN(defaultGPUPrice) {
  889. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  890. defaultGPUPrice = 0
  891. }
  892. // Just say no to doing the ratios!
  893. cpuCost := defaultCPUCorePrice * cpu
  894. gpuCost := defaultGPUPrice * gpuc
  895. ramCost := defaultRAMPrice * ram
  896. nodeCost := cpuCost + gpuCost + ramCost
  897. newCnode.Cost = fmt.Sprintf("%f", nodeCost)
  898. newCnode.VCPUCost = fmt.Sprintf("%f", defaultCPUCorePrice)
  899. newCnode.GPUCost = fmt.Sprintf("%f", defaultGPUPrice)
  900. newCnode.RAMCost = fmt.Sprintf("%f", defaultRAMPrice)
  901. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  902. } else if newCnode.GPU != "" && newCnode.GPUCost == "" {
  903. // was the big thing to investigate. All the funky ratio math
  904. // we were doing was messing with their default pricing. for SUSE Rancher.
  905. // We reach this when a GPU is detected on a node, but no cost for
  906. // the GPU is defined in the OnDemand pricing. Calculate ratios of
  907. // CPU to RAM and GPU to RAM costs, then distribute the total node
  908. // cost among the CPU, RAM, and GPU.
  909. log.Tracef("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  910. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  911. if err != nil {
  912. log.Errorf("Could not parse default cpu price")
  913. defaultCPU = 0
  914. }
  915. if math.IsNaN(defaultCPU) {
  916. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  917. defaultCPU = 0
  918. }
  919. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  920. if err != nil {
  921. log.Errorf("Could not parse default ram price")
  922. defaultRAM = 0
  923. }
  924. if math.IsNaN(defaultRAM) {
  925. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  926. defaultRAM = 0
  927. }
  928. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  929. if err != nil {
  930. log.Errorf("Could not parse default gpu price")
  931. defaultGPU = 0
  932. }
  933. if math.IsNaN(defaultGPU) {
  934. log.Warnf("defaultGPU parsed as NaN. Setting to 0.")
  935. defaultGPU = 0
  936. }
  937. cpuToRAMRatio := defaultCPU / defaultRAM
  938. if math.IsNaN(cpuToRAMRatio) {
  939. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  940. cpuToRAMRatio = 10
  941. }
  942. gpuToRAMRatio := defaultGPU / defaultRAM
  943. if math.IsNaN(gpuToRAMRatio) {
  944. log.Warnf("gpuToRAMRatio is NaN. Setting to 100.")
  945. gpuToRAMRatio = 100
  946. }
  947. ramGB := ram / 1024 / 1024 / 1024
  948. if math.IsNaN(ramGB) {
  949. log.Warnf("ramGB is NaN. Setting to 0.")
  950. ramGB = 0
  951. }
  952. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  953. if math.IsNaN(ramMultiple) {
  954. log.Warnf("ramMultiple is NaN. Setting to 0.")
  955. ramMultiple = 0
  956. }
  957. var nodePrice float64
  958. if newCnode.Cost != "" {
  959. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  960. if err != nil {
  961. log.Errorf("Could not parse total node price")
  962. return nil, err
  963. }
  964. } else if newCnode.VCPUCost != "" {
  965. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  966. if err != nil {
  967. log.Errorf("Could not parse node vcpu price")
  968. return nil, err
  969. }
  970. } else { // add case to use default pricing model when API data fails.
  971. log.Debugf("No node price or CPUprice found, falling back to default")
  972. nodePrice = defaultCPU*cpu + defaultRAM*ram + gpuc*defaultGPU
  973. }
  974. if math.IsNaN(nodePrice) {
  975. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  976. nodePrice = 0
  977. }
  978. ramPrice := (nodePrice / ramMultiple)
  979. if math.IsNaN(ramPrice) {
  980. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  981. ramPrice = 0
  982. }
  983. cpuPrice := ramPrice * cpuToRAMRatio
  984. gpuPrice := ramPrice * gpuToRAMRatio
  985. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  986. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  987. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  988. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  989. } else if newCnode.RAMCost == "" {
  990. // We reach this when no RAM cost is defined in the OnDemand
  991. // pricing. It calculates a cpuToRAMRatio and ramMultiple to
  992. // distrubte the total node cost among CPU and RAM costs.
  993. log.Tracef("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels, n).Features())
  994. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  995. if err != nil {
  996. log.Warnf("Could not parse default cpu price")
  997. defaultCPU = 0
  998. }
  999. if math.IsNaN(defaultCPU) {
  1000. log.Warnf("defaultCPU parsed as NaN. Setting to 0.")
  1001. defaultCPU = 0
  1002. }
  1003. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1004. if err != nil {
  1005. log.Warnf("Could not parse default ram price")
  1006. defaultRAM = 0
  1007. }
  1008. if math.IsNaN(defaultRAM) {
  1009. log.Warnf("defaultRAM parsed as NaN. Setting to 0.")
  1010. defaultRAM = 0
  1011. }
  1012. cpuToRAMRatio := defaultCPU / defaultRAM
  1013. if math.IsNaN(cpuToRAMRatio) {
  1014. log.Warnf("cpuToRAMRatio[defaultCPU: %f / defaultRAM: %f] is NaN. Setting to 10.", defaultCPU, defaultRAM)
  1015. cpuToRAMRatio = 10
  1016. }
  1017. ramGB := ram / 1024 / 1024 / 1024
  1018. if math.IsNaN(ramGB) {
  1019. log.Warnf("ramGB is NaN. Setting to 0.")
  1020. ramGB = 0
  1021. }
  1022. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1023. if math.IsNaN(ramMultiple) {
  1024. log.Warnf("ramMultiple is NaN. Setting to 0.")
  1025. ramMultiple = 0
  1026. }
  1027. var nodePrice float64
  1028. if newCnode.Cost != "" {
  1029. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1030. if err != nil {
  1031. log.Warnf("Could not parse total node price")
  1032. return nil, err
  1033. }
  1034. if newCnode.GPUCost != "" {
  1035. gpuPrice, err := strconv.ParseFloat(newCnode.GPUCost, 64)
  1036. if err != nil {
  1037. log.Warnf("Could not parse node gpu price")
  1038. return nil, err
  1039. }
  1040. nodePrice = nodePrice - gpuPrice // remove the gpuPrice from the total, we're just costing out RAM and CPU.
  1041. }
  1042. } else if newCnode.VCPUCost != "" {
  1043. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated to the CPU
  1044. if err != nil {
  1045. log.Warnf("Could not parse node vcpu price")
  1046. return nil, err
  1047. }
  1048. } else { // add case to use default pricing model when API data fails.
  1049. log.Debugf("No node price or CPUprice found, falling back to default")
  1050. nodePrice = defaultCPU*cpu + defaultRAM*ramGB
  1051. }
  1052. if math.IsNaN(nodePrice) {
  1053. log.Warnf("nodePrice parsed as NaN. Setting to 0.")
  1054. nodePrice = 0
  1055. }
  1056. ramPrice := (nodePrice / ramMultiple)
  1057. if math.IsNaN(ramPrice) {
  1058. log.Warnf("ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1059. ramPrice = 0
  1060. }
  1061. cpuPrice := ramPrice * cpuToRAMRatio
  1062. if defaultRAM != 0 {
  1063. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1064. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1065. } else { // just assign the full price to CPU
  1066. if cpu != 0 {
  1067. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1068. } else {
  1069. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1070. }
  1071. }
  1072. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1073. log.Tracef("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1074. }
  1075. nodes[name] = &newCnode
  1076. }
  1077. cm.pricingMetadata = pmd
  1078. cp.ApplyReservedInstancePricing(nodes)
  1079. return nodes, nil
  1080. }
  1081. // TODO: drop some logs
  1082. func (cm *CostModel) GetLBCost(cp costAnalyzerCloud.Provider) (map[serviceKey]*costAnalyzerCloud.LoadBalancer, error) {
  1083. // for fetching prices from cloud provider
  1084. // cfg, err := cp.GetConfig()
  1085. // if err != nil {
  1086. // return nil, err
  1087. // }
  1088. servicesList := cm.Cache.GetAllServices()
  1089. loadBalancerMap := make(map[serviceKey]*costAnalyzerCloud.LoadBalancer)
  1090. for _, service := range servicesList {
  1091. namespace := service.Namespace
  1092. name := service.Name
  1093. key := serviceKey{
  1094. Cluster: env.GetClusterID(),
  1095. Namespace: namespace,
  1096. Service: name,
  1097. }
  1098. if service.Type == "LoadBalancer" {
  1099. loadBalancer, err := cp.LoadBalancerPricing()
  1100. if err != nil {
  1101. return nil, err
  1102. }
  1103. newLoadBalancer := *loadBalancer
  1104. for _, loadBalancerIngress := range service.Status.LoadBalancer.Ingress {
  1105. address := loadBalancerIngress.IP
  1106. // Some cloud providers use hostname rather than IP
  1107. if address == "" {
  1108. address = loadBalancerIngress.Hostname
  1109. }
  1110. newLoadBalancer.IngressIPAddresses = append(newLoadBalancer.IngressIPAddresses, address)
  1111. }
  1112. loadBalancerMap[key] = &newLoadBalancer
  1113. }
  1114. }
  1115. return loadBalancerMap, nil
  1116. }
  1117. func getPodServices(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1118. servicesList := cache.GetAllServices()
  1119. podServicesMapping := make(map[string]map[string][]string)
  1120. for _, service := range servicesList {
  1121. namespace := service.Namespace
  1122. name := service.Name
  1123. key := namespace + "," + clusterID
  1124. if _, ok := podServicesMapping[key]; !ok {
  1125. podServicesMapping[key] = make(map[string][]string)
  1126. }
  1127. s := labels.Nothing()
  1128. if service.SpecSelector != nil && len(service.SpecSelector) > 0 {
  1129. s = labels.Set(service.SpecSelector).AsSelectorPreValidated()
  1130. }
  1131. for _, pod := range podList {
  1132. labelSet := labels.Set(pod.Labels)
  1133. if s.Matches(labelSet) && pod.Namespace == namespace {
  1134. services, ok := podServicesMapping[key][pod.Name]
  1135. if ok {
  1136. podServicesMapping[key][pod.Name] = append(services, name)
  1137. } else {
  1138. podServicesMapping[key][pod.Name] = []string{name}
  1139. }
  1140. }
  1141. }
  1142. }
  1143. return podServicesMapping, nil
  1144. }
  1145. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1146. ssList := cache.GetAllStatefulSets()
  1147. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1148. for _, ss := range ssList {
  1149. namespace := ss.Namespace
  1150. name := ss.Name
  1151. key := namespace + "," + clusterID
  1152. if _, ok := podSSMapping[key]; !ok {
  1153. podSSMapping[key] = make(map[string][]string)
  1154. }
  1155. s, err := metav1.LabelSelectorAsSelector(ss.SpecSelector)
  1156. if err != nil {
  1157. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1158. }
  1159. for _, pod := range podList {
  1160. labelSet := labels.Set(pod.Labels)
  1161. if s.Matches(labelSet) && pod.Namespace == namespace {
  1162. sss, ok := podSSMapping[key][pod.Name]
  1163. if ok {
  1164. podSSMapping[key][pod.Name] = append(sss, name)
  1165. } else {
  1166. podSSMapping[key][pod.Name] = []string{name}
  1167. }
  1168. }
  1169. }
  1170. }
  1171. return podSSMapping, nil
  1172. }
  1173. func getPodDeployments(cache clustercache.ClusterCache, podList []*clustercache.Pod, clusterID string) (map[string]map[string][]string, error) {
  1174. deploymentsList := cache.GetAllDeployments()
  1175. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1176. for _, deployment := range deploymentsList {
  1177. namespace := deployment.Namespace
  1178. name := deployment.Name
  1179. key := namespace + "," + clusterID
  1180. if _, ok := podDeploymentsMapping[key]; !ok {
  1181. podDeploymentsMapping[key] = make(map[string][]string)
  1182. }
  1183. s, err := metav1.LabelSelectorAsSelector(deployment.SpecSelector)
  1184. if err != nil {
  1185. log.Errorf("Error doing deployment label conversion: " + err.Error())
  1186. }
  1187. for _, pod := range podList {
  1188. labelSet := labels.Set(pod.Labels)
  1189. if s.Matches(labelSet) && pod.Namespace == namespace {
  1190. deployments, ok := podDeploymentsMapping[key][pod.Name]
  1191. if ok {
  1192. podDeploymentsMapping[key][pod.Name] = append(deployments, name)
  1193. } else {
  1194. podDeploymentsMapping[key][pod.Name] = []string{name}
  1195. }
  1196. }
  1197. }
  1198. }
  1199. return podDeploymentsMapping, nil
  1200. }
  1201. func getPodDeploymentsWithMetrics(deploymentLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1202. podDeploymentsMapping := make(map[string]map[string][]string)
  1203. for depKey, depLabels := range deploymentLabels {
  1204. kt, err := NewKeyTuple(depKey)
  1205. if err != nil {
  1206. continue
  1207. }
  1208. namespace := kt.Namespace()
  1209. name := kt.Key()
  1210. clusterID := kt.ClusterID()
  1211. key := namespace + "," + clusterID
  1212. if _, ok := podDeploymentsMapping[key]; !ok {
  1213. podDeploymentsMapping[key] = make(map[string][]string)
  1214. }
  1215. s := labels.Set(depLabels).AsSelectorPreValidated()
  1216. for podKey, pLabels := range podLabels {
  1217. pkey, err := NewKeyTuple(podKey)
  1218. if err != nil {
  1219. continue
  1220. }
  1221. podNamespace := pkey.Namespace()
  1222. podName := pkey.Key()
  1223. podClusterID := pkey.ClusterID()
  1224. labelSet := labels.Set(pLabels)
  1225. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1226. deployments, ok := podDeploymentsMapping[key][podName]
  1227. if ok {
  1228. podDeploymentsMapping[key][podName] = append(deployments, name)
  1229. } else {
  1230. podDeploymentsMapping[key][podName] = []string{name}
  1231. }
  1232. }
  1233. }
  1234. }
  1235. // Remove any duplicate data created by metric names
  1236. pruneDuplicateData(podDeploymentsMapping)
  1237. return podDeploymentsMapping, nil
  1238. }
  1239. func getPodServicesWithMetrics(serviceLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1240. podServicesMapping := make(map[string]map[string][]string)
  1241. for servKey, servLabels := range serviceLabels {
  1242. kt, err := NewKeyTuple(servKey)
  1243. if err != nil {
  1244. continue
  1245. }
  1246. namespace := kt.Namespace()
  1247. name := kt.Key()
  1248. clusterID := kt.ClusterID()
  1249. key := namespace + "," + clusterID
  1250. if _, ok := podServicesMapping[key]; !ok {
  1251. podServicesMapping[key] = make(map[string][]string)
  1252. }
  1253. s := labels.Nothing()
  1254. if servLabels != nil && len(servLabels) > 0 {
  1255. s = labels.Set(servLabels).AsSelectorPreValidated()
  1256. }
  1257. for podKey, pLabels := range podLabels {
  1258. pkey, err := NewKeyTuple(podKey)
  1259. if err != nil {
  1260. continue
  1261. }
  1262. podNamespace := pkey.Namespace()
  1263. podName := pkey.Key()
  1264. podClusterID := pkey.ClusterID()
  1265. labelSet := labels.Set(pLabels)
  1266. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1267. services, ok := podServicesMapping[key][podName]
  1268. if ok {
  1269. podServicesMapping[key][podName] = append(services, name)
  1270. } else {
  1271. podServicesMapping[key][podName] = []string{name}
  1272. }
  1273. }
  1274. }
  1275. }
  1276. // Remove any duplicate data created by metric names
  1277. pruneDuplicateData(podServicesMapping)
  1278. return podServicesMapping, nil
  1279. }
  1280. // This method alleviates an issue with metrics that used a '_' to replace '-' in deployment
  1281. // and service names. To avoid counting these as multiple deployments/services, we'll remove
  1282. // the '_' version. Not optimal, but takes care of the issue
  1283. func pruneDuplicateData(data map[string]map[string][]string) {
  1284. for _, podMap := range data {
  1285. for podName, values := range podMap {
  1286. podMap[podName] = pruneDuplicates(values)
  1287. }
  1288. }
  1289. }
  1290. // Determine if there is an underscore in the value of a slice. If so, replace _ with -, and then
  1291. // check to see if the result exists in the slice. If both are true, then we DO NOT include that
  1292. // original value in the new slice.
  1293. func pruneDuplicates(s []string) []string {
  1294. m := sliceToSet(s)
  1295. for _, v := range s {
  1296. if strings.Contains(v, "_") {
  1297. name := strings.Replace(v, "_", "-", -1)
  1298. if !m[name] {
  1299. m[name] = true
  1300. }
  1301. delete(m, v)
  1302. }
  1303. }
  1304. return setToSlice(m)
  1305. }
  1306. // Creates a map[string]bool containing the slice values as keys
  1307. func sliceToSet(s []string) map[string]bool {
  1308. m := make(map[string]bool)
  1309. for _, v := range s {
  1310. m[v] = true
  1311. }
  1312. return m
  1313. }
  1314. func setToSlice(m map[string]bool) []string {
  1315. var result []string
  1316. for k := range m {
  1317. result = append(result, k)
  1318. }
  1319. return result
  1320. }
  1321. func costDataPassesFilters(cm clusters.ClusterMap, costs *CostData, namespace string, cluster string) bool {
  1322. passesNamespace := namespace == "" || costs.Namespace == namespace
  1323. passesCluster := cluster == "" || costs.ClusterID == cluster || costs.ClusterName == cluster
  1324. return passesNamespace && passesCluster
  1325. }
  1326. // Finds the a closest multiple less than value
  1327. func floorMultiple(value int64, multiple int64) int64 {
  1328. return (value / multiple) * multiple
  1329. }
  1330. // Attempt to create a key for the request. Reduce the times to minutes in order to more easily group requests based on
  1331. // real time ranges. If for any reason, the key generation fails, return a uuid to ensure uniqueness.
  1332. func requestKeyFor(window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string) string {
  1333. keyLayout := "2006-01-02T15:04Z"
  1334. // We "snap" start time and duration to their closest 5 min multiple less than itself, by
  1335. // applying a snapped duration to a snapped start time.
  1336. durMins := int64(window.Minutes())
  1337. durMins = floorMultiple(durMins, 5)
  1338. sMins := int64(window.Start().Minute())
  1339. sOffset := sMins - floorMultiple(sMins, 5)
  1340. sTime := window.Start().Add(-time.Duration(sOffset) * time.Minute)
  1341. eTime := window.Start().Add(time.Duration(durMins) * time.Minute)
  1342. startKey := sTime.Format(keyLayout)
  1343. endKey := eTime.Format(keyLayout)
  1344. return fmt.Sprintf("%s,%s,%s,%s,%s", startKey, endKey, resolution.String(), filterNamespace, filterCluster)
  1345. }
  1346. // ComputeCostDataRange executes a range query for cost data.
  1347. // Note that "offset" represents the time between the function call and "endString", and is also passed for convenience
  1348. func (cm *CostModel) ComputeCostDataRange(window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string) (map[string]*CostData, error) {
  1349. // Create a request key for request grouping. This key will be used to represent the cost-model result
  1350. // for the specific inputs to prevent multiple queries for identical data.
  1351. key := requestKeyFor(window, resolution, filterNamespace, filterCluster)
  1352. log.Debugf("ComputeCostDataRange with Key: %s", key)
  1353. // If there is already a request out that uses the same data, wait for it to return to share the results.
  1354. // Otherwise, start executing.
  1355. result, err, _ := cm.RequestGroup.Do(key, func() (interface{}, error) {
  1356. return cm.costDataRange(window, resolution, filterNamespace, filterCluster)
  1357. })
  1358. data, ok := result.(map[string]*CostData)
  1359. if !ok {
  1360. return nil, fmt.Errorf("Failed to cast result as map[string]*CostData")
  1361. }
  1362. return data, err
  1363. }
  1364. func (cm *CostModel) costDataRange(window opencost.Window, resolution time.Duration, filterNamespace string, filterCluster string) (map[string]*CostData, error) {
  1365. clusterID := env.GetClusterID()
  1366. dataSource := cm.DataSource
  1367. cp := cm.Provider
  1368. // durHrs := end.Sub(start).Hours() + 1
  1369. if window.IsOpen() {
  1370. return nil, fmt.Errorf("illegal window: %s", window)
  1371. }
  1372. start := *window.Start()
  1373. end := *window.End()
  1374. // Snap resolution to the nearest minute
  1375. resMins := int64(math.Trunc(resolution.Minutes()))
  1376. if resMins == 0 {
  1377. return nil, fmt.Errorf("resolution must be greater than 0.0")
  1378. }
  1379. resolution = time.Duration(resMins) * time.Minute
  1380. // Warn if resolution does not evenly divide window
  1381. if int64(window.Minutes())%int64(resolution.Minutes()) != 0 {
  1382. log.Warnf("CostDataRange: window should be divisible by resolution or else samples may be missed: %s %% %s = %dm", window, resolution, int64(window.Minutes())%int64(resolution.Minutes()))
  1383. }
  1384. /*
  1385. // Convert to Prometheus-style duration string in terms of m or h
  1386. resStr := fmt.Sprintf("%dm", resMins)
  1387. if resMins%60 == 0 {
  1388. resStr = fmt.Sprintf("%dh", resMins/60)
  1389. }
  1390. scrapeIntervalSeconds := cm.RefreshInterval.Seconds()
  1391. */
  1392. grp := source.NewQueryGroup()
  1393. resChRAMRequests := grp.With(dataSource.QueryRAMRequestsOverTime(start, end, resolution))
  1394. resChRAMUsage := grp.With(dataSource.QueryRAMUsageOverTime(start, end, resolution))
  1395. resChRAMAlloc := grp.With(dataSource.QueryRAMAllocationOverTime(start, end, resolution))
  1396. resChCPURequests := grp.With(dataSource.QueryCPURequestsOverTime(start, end, resolution))
  1397. resChCPUUsage := grp.With(dataSource.QueryCPUUsageOverTime(start, end, resolution))
  1398. resChCPUAlloc := grp.With(dataSource.QueryCPUAllocationOverTime(start, end, resolution))
  1399. resChGPURequests := grp.With(dataSource.QueryGPURequestsOverTime(start, end, resolution))
  1400. resChPVRequests := grp.With(dataSource.QueryPVRequestsOverTime(start, end, resolution))
  1401. resChPVCAlloc := grp.With(dataSource.QueryPVCAllocationOverTime(start, end, resolution))
  1402. resChPVHourlyCost := grp.With(dataSource.QueryPVHourlyCostOverTime(start, end, resolution))
  1403. resChNetZoneRequests := grp.With(dataSource.QueryNetworkInZoneOverTime(start, end, resolution))
  1404. resChNetRegionRequests := grp.With(dataSource.QueryNetworkInRegionOverTime(start, end, resolution))
  1405. resChNetInternetRequests := grp.With(dataSource.QueryNetworkInternetOverTime(start, end, resolution))
  1406. resChNSLabels := grp.With(dataSource.QueryNamespaceLabelsOverTime(start, end, resolution))
  1407. resChPodLabels := grp.With(dataSource.QueryPodLabelsOverTime(start, end, resolution))
  1408. resChNSAnnotations := grp.With(dataSource.QueryNamespaceAnnotationsOverTime(start, end, resolution))
  1409. resChPodAnnotations := grp.With(dataSource.QueryPodAnnotationsOverTime(start, end, resolution))
  1410. resChServiceLabels := grp.With(dataSource.QueryServiceLabelsOverTime(start, end, resolution))
  1411. resChDeploymentLabels := grp.With(dataSource.QueryDeploymentLabelsOverTime(start, end, resolution))
  1412. resChStatefulsetLabels := grp.With(dataSource.QueryStatefulsetLabelsOverTime(start, end, resolution))
  1413. resChJobs := grp.With(dataSource.QueryPodJobsOverTime(start, end, resolution))
  1414. resChDaemonsets := grp.With(dataSource.QueryPodDaemonsetsOverTime(start, end, resolution))
  1415. resChNormalization := grp.With(dataSource.QueryNormalizationOverTime(start, end, resolution))
  1416. /*
  1417. ctx := prom.NewNamedContext(cli, prom.ComputeCostDataRangeContextName)
  1418. queryRAMAlloc := fmt.Sprintf(queryRAMAllocationByteHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1419. queryCPUAlloc := fmt.Sprintf(queryCPUAllocationVCPUHours, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1420. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1421. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1422. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1423. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1424. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1425. queryPVRequests := fmt.Sprintf(queryPVRequestsStr, env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1426. queryPVCAllocation := fmt.Sprintf(queryPVCAllocationFmt, env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  1427. queryPVHourlyCost := fmt.Sprintf(queryPVHourlyCostFmt, env.GetPromClusterFilter(), resStr)
  1428. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1429. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1430. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  1431. queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), resStr, "")
  1432. // Submit all queries for concurrent evaluation
  1433. resChRAMRequests := ctx.QueryRange(queryRAMRequests, start, end, resolution)
  1434. resChRAMUsage := ctx.QueryRange(queryRAMUsage, start, end, resolution)
  1435. resChRAMAlloc := ctx.QueryRange(queryRAMAlloc, start, end, resolution)
  1436. resChCPURequests := ctx.QueryRange(queryCPURequests, start, end, resolution)
  1437. resChCPUUsage := ctx.QueryRange(queryCPUUsage, start, end, resolution)
  1438. resChCPUAlloc := ctx.QueryRange(queryCPUAlloc, start, end, resolution)
  1439. resChGPURequests := ctx.QueryRange(queryGPURequests, start, end, resolution)
  1440. resChPVRequests := ctx.QueryRange(queryPVRequests, start, end, resolution)
  1441. resChPVCAlloc := ctx.QueryRange(queryPVCAllocation, start, end, resolution)
  1442. resChPVHourlyCost := ctx.QueryRange(queryPVHourlyCost, start, end, resolution)
  1443. resChNetZoneRequests := ctx.QueryRange(queryNetZoneRequests, start, end, resolution)
  1444. resChNetRegionRequests := ctx.QueryRange(queryNetRegionRequests, start, end, resolution)
  1445. resChNetInternetRequests := ctx.QueryRange(queryNetInternetRequests, start, end, resolution)
  1446. resChNSLabels := ctx.QueryRange(fmt.Sprintf(queryNSLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1447. resChPodLabels := ctx.QueryRange(fmt.Sprintf(queryPodLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1448. resChNSAnnotations := ctx.QueryRange(fmt.Sprintf(queryNSAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1449. resChPodAnnotations := ctx.QueryRange(fmt.Sprintf(queryPodAnnotations, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1450. resChServiceLabels := ctx.QueryRange(fmt.Sprintf(queryServiceLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1451. resChDeploymentLabels := ctx.QueryRange(fmt.Sprintf(queryDeploymentLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1452. resChStatefulsetLabels := ctx.QueryRange(fmt.Sprintf(queryStatefulsetLabels, env.GetPromClusterFilter(), resStr), start, end, resolution)
  1453. resChJobs := ctx.QueryRange(fmt.Sprintf(queryPodJobs, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1454. resChDaemonsets := ctx.QueryRange(fmt.Sprintf(queryPodDaemonsets, env.GetPromClusterFilter(), env.GetPromClusterLabel()), start, end, resolution)
  1455. resChNormalization := ctx.QueryRange(queryNormalization, start, end, resolution)
  1456. */
  1457. // Pull k8s pod, controller, service, and namespace details
  1458. podlist := cm.Cache.GetAllPods()
  1459. podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
  1460. if err != nil {
  1461. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1462. }
  1463. podStatefulsetsMapping, err := getPodStatefulsets(cm.Cache, podlist, clusterID)
  1464. if err != nil {
  1465. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1466. }
  1467. podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
  1468. if err != nil {
  1469. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1470. }
  1471. namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
  1472. if err != nil {
  1473. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1474. }
  1475. namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
  1476. if err != nil {
  1477. return nil, fmt.Errorf("error querying the kubernetes API: %s", err)
  1478. }
  1479. // Process query results. Handle errors afterwards using ctx.Errors.
  1480. resRAMRequests, _ := resChRAMRequests.Await()
  1481. resRAMUsage, _ := resChRAMUsage.Await()
  1482. resRAMAlloc, _ := resChRAMAlloc.Await()
  1483. resCPURequests, _ := resChCPURequests.Await()
  1484. resCPUUsage, _ := resChCPUUsage.Await()
  1485. resCPUAlloc, _ := resChCPUAlloc.Await()
  1486. resGPURequests, _ := resChGPURequests.Await()
  1487. resPVRequests, _ := resChPVRequests.Await()
  1488. resPVCAlloc, _ := resChPVCAlloc.Await()
  1489. resPVHourlyCost, _ := resChPVHourlyCost.Await()
  1490. resNetZoneRequests, _ := resChNetZoneRequests.Await()
  1491. resNetRegionRequests, _ := resChNetRegionRequests.Await()
  1492. resNetInternetRequests, _ := resChNetInternetRequests.Await()
  1493. resNSLabels, _ := resChNSLabels.Await()
  1494. resPodLabels, _ := resChPodLabels.Await()
  1495. resNSAnnotations, _ := resChNSAnnotations.Await()
  1496. resPodAnnotations, _ := resChPodAnnotations.Await()
  1497. resServiceLabels, _ := resChServiceLabels.Await()
  1498. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  1499. resStatefulsetLabels, _ := resChStatefulsetLabels.Await()
  1500. resDaemonsets, _ := resChDaemonsets.Await()
  1501. resJobs, _ := resChJobs.Await()
  1502. resNormalization, _ := resChNormalization.Await()
  1503. // NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
  1504. // NOTE: will not propagate unless coupled with errors.
  1505. if grp.HasErrors() {
  1506. // To keep the context of where the errors are occurring, we log the errors here and pass them the error
  1507. // back to the caller. The caller should handle the specific case where error is an ErrorCollection
  1508. for _, queryErr := range grp.Errors() {
  1509. if queryErr.Error != nil {
  1510. log.Errorf("CostDataRange: Request Error: %s", queryErr.Error)
  1511. }
  1512. if queryErr.ParseError != nil {
  1513. log.Errorf("CostDataRange: Parsing Error: %s", queryErr.ParseError)
  1514. }
  1515. }
  1516. // ErrorCollection is an collection of errors wrapped in a single error implementation
  1517. return nil, grp.Error()
  1518. }
  1519. normalizationValue, err := getNormalizations(resNormalization)
  1520. if err != nil {
  1521. msg := fmt.Sprintf("error computing normalization for start=%s, end=%s, res=%s", start, end, resolution)
  1522. return nil, source.WrapError(err, msg)
  1523. }
  1524. pvClaimMapping, err := GetPVInfo(resPVRequests, clusterID)
  1525. if err != nil {
  1526. // Just log for compatibility with KSM less than 1.6
  1527. log.Infof("Unable to get PV Data: %s", err.Error())
  1528. }
  1529. if pvClaimMapping != nil {
  1530. err = addPVData(cm.Cache, pvClaimMapping, cp)
  1531. if err != nil {
  1532. return nil, fmt.Errorf("pvClaimMapping: %s", err)
  1533. }
  1534. }
  1535. pvCostMapping, err := GetPVCostMetrics(resPVHourlyCost, clusterID)
  1536. if err != nil {
  1537. log.Errorf("Unable to get PV Hourly Cost Data: %s", err.Error())
  1538. }
  1539. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  1540. pvAllocationMapping, err := GetPVAllocationMetrics(resPVCAlloc, clusterID)
  1541. if err != nil {
  1542. log.Errorf("Unable to get PV Allocation Cost Data: %s", err.Error())
  1543. }
  1544. if pvAllocationMapping != nil {
  1545. addMetricPVData(pvAllocationMapping, pvCostMapping, cp)
  1546. for k, v := range pvAllocationMapping {
  1547. unmountedPVs[k] = v
  1548. }
  1549. }
  1550. nsLabels, err := GetNamespaceLabelsMetrics(resNSLabels, clusterID)
  1551. if err != nil {
  1552. log.Errorf("Unable to get Namespace Labels for Metrics: %s", err.Error())
  1553. }
  1554. if nsLabels != nil {
  1555. mergeStringMap(namespaceLabelsMapping, nsLabels)
  1556. }
  1557. podLabels, err := GetPodLabelsMetrics(resPodLabels, clusterID)
  1558. if err != nil {
  1559. log.Errorf("Unable to get Pod Labels for Metrics: %s", err.Error())
  1560. }
  1561. nsAnnotations, err := GetNamespaceAnnotationsMetrics(resNSAnnotations, clusterID)
  1562. if err != nil {
  1563. log.Errorf("Unable to get Namespace Annotations for Metrics: %s", err.Error())
  1564. }
  1565. if nsAnnotations != nil {
  1566. mergeStringMap(namespaceAnnotationsMapping, nsAnnotations)
  1567. }
  1568. podAnnotations, err := GetPodAnnotationsMetrics(resPodAnnotations, clusterID)
  1569. if err != nil {
  1570. log.Errorf("Unable to get Pod Annotations for Metrics: %s", err.Error())
  1571. }
  1572. serviceLabels, err := GetServiceSelectorLabelsMetrics(resServiceLabels, clusterID)
  1573. if err != nil {
  1574. log.Errorf("Unable to get Service Selector Labels for Metrics: %s", err.Error())
  1575. }
  1576. deploymentLabels, err := GetDeploymentMatchLabelsMetrics(resDeploymentLabels, clusterID)
  1577. if err != nil {
  1578. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1579. }
  1580. statefulsetLabels, err := GetStatefulsetMatchLabelsMetrics(resStatefulsetLabels, clusterID)
  1581. if err != nil {
  1582. log.Errorf("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1583. }
  1584. podStatefulsetMetricsMapping, err := getPodDeploymentsWithMetrics(statefulsetLabels, podLabels)
  1585. if err != nil {
  1586. log.Errorf("Unable to get match Statefulset Labels Metrics to Pods: %s", err.Error())
  1587. }
  1588. appendLabelsList(podStatefulsetsMapping, podStatefulsetMetricsMapping)
  1589. podDeploymentsMetricsMapping, err := getPodDeploymentsWithMetrics(deploymentLabels, podLabels)
  1590. if err != nil {
  1591. log.Errorf("Unable to get match Deployment Labels Metrics to Pods: %s", err.Error())
  1592. }
  1593. appendLabelsList(podDeploymentsMapping, podDeploymentsMetricsMapping)
  1594. podDaemonsets, err := GetPodDaemonsetsWithMetrics(resDaemonsets, clusterID)
  1595. if err != nil {
  1596. log.Errorf("Unable to get Pod Daemonsets for Metrics: %s", err.Error())
  1597. }
  1598. podJobs, err := GetPodJobsWithMetrics(resJobs, clusterID)
  1599. if err != nil {
  1600. log.Errorf("Unable to get Pod Jobs for Metrics: %s", err.Error())
  1601. }
  1602. podServicesMetricsMapping, err := getPodServicesWithMetrics(serviceLabels, podLabels)
  1603. if err != nil {
  1604. log.Errorf("Unable to get match Service Labels Metrics to Pods: %s", err.Error())
  1605. }
  1606. appendLabelsList(podServicesMapping, podServicesMetricsMapping)
  1607. networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
  1608. if err != nil {
  1609. log.Errorf("Unable to get Network Cost Data: %s", err.Error())
  1610. networkUsageMap = make(map[string]*NetworkUsageData)
  1611. }
  1612. containerNameCost := make(map[string]*CostData)
  1613. containers := make(map[string]bool)
  1614. otherClusterPVRecorded := make(map[string]bool)
  1615. RAMReqMap, err := GetNormalizedContainerMetricVectors(resRAMRequests, normalizationValue, clusterID)
  1616. if err != nil {
  1617. return nil, source.WrapError(err, "GetNormalizedContainerMetricVectors(RAMRequests)")
  1618. }
  1619. for key := range RAMReqMap {
  1620. containers[key] = true
  1621. }
  1622. RAMUsedMap, err := GetNormalizedContainerMetricVectors(resRAMUsage, normalizationValue, clusterID)
  1623. if err != nil {
  1624. return nil, source.WrapError(err, "GetNormalizedContainerMetricVectors(RAMUsage)")
  1625. }
  1626. for key := range RAMUsedMap {
  1627. containers[key] = true
  1628. }
  1629. CPUReqMap, err := GetNormalizedContainerMetricVectors(resCPURequests, normalizationValue, clusterID)
  1630. if err != nil {
  1631. return nil, source.WrapError(err, "GetNormalizedContainerMetricVectors(CPURequests)")
  1632. }
  1633. for key := range CPUReqMap {
  1634. containers[key] = true
  1635. }
  1636. // No need to normalize here, as this comes from a counter, namely:
  1637. // rate(container_cpu_usage_seconds_total) which properly accounts for normalized rates
  1638. CPUUsedMap, err := GetContainerMetricVectors(resCPUUsage, clusterID)
  1639. if err != nil {
  1640. return nil, source.WrapError(err, "GetContainerMetricVectors(CPUUsage)")
  1641. }
  1642. for key := range CPUUsedMap {
  1643. containers[key] = true
  1644. }
  1645. RAMAllocMap, err := GetContainerMetricVectors(resRAMAlloc, clusterID)
  1646. if err != nil {
  1647. return nil, source.WrapError(err, "GetContainerMetricVectors(RAMAllocations)")
  1648. }
  1649. for key := range RAMAllocMap {
  1650. containers[key] = true
  1651. }
  1652. CPUAllocMap, err := GetContainerMetricVectors(resCPUAlloc, clusterID)
  1653. if err != nil {
  1654. return nil, source.WrapError(err, "GetContainerMetricVectors(CPUAllocations)")
  1655. }
  1656. for key := range CPUAllocMap {
  1657. containers[key] = true
  1658. }
  1659. GPUReqMap, err := GetNormalizedContainerMetricVectors(resGPURequests, normalizationValue, clusterID)
  1660. if err != nil {
  1661. return nil, source.WrapError(err, "GetContainerMetricVectors(GPURequests)")
  1662. }
  1663. for key := range GPUReqMap {
  1664. containers[key] = true
  1665. }
  1666. // Request metrics can show up after pod eviction and completion.
  1667. // This method synchronizes requests to allocations such that when
  1668. // allocation is 0, so are requests
  1669. applyAllocationToRequests(RAMAllocMap, RAMReqMap)
  1670. applyAllocationToRequests(CPUAllocMap, CPUReqMap)
  1671. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1672. missingContainers := make(map[string]*CostData)
  1673. for key := range containers {
  1674. if _, ok := containerNameCost[key]; ok {
  1675. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1676. }
  1677. c, _ := NewContainerMetricFromKey(key)
  1678. RAMReqV, ok := RAMReqMap[key]
  1679. if !ok {
  1680. log.Debug("no RAM requests for " + key)
  1681. RAMReqV = []*util.Vector{}
  1682. }
  1683. RAMUsedV, ok := RAMUsedMap[key]
  1684. if !ok {
  1685. log.Debug("no RAM usage for " + key)
  1686. RAMUsedV = []*util.Vector{}
  1687. }
  1688. CPUReqV, ok := CPUReqMap[key]
  1689. if !ok {
  1690. log.Debug("no CPU requests for " + key)
  1691. CPUReqV = []*util.Vector{}
  1692. }
  1693. CPUUsedV, ok := CPUUsedMap[key]
  1694. if !ok {
  1695. log.Debug("no CPU usage for " + key)
  1696. CPUUsedV = []*util.Vector{}
  1697. }
  1698. RAMAllocsV, ok := RAMAllocMap[key]
  1699. if !ok {
  1700. log.Debug("no RAM allocation for " + key)
  1701. RAMAllocsV = []*util.Vector{}
  1702. }
  1703. CPUAllocsV, ok := CPUAllocMap[key]
  1704. if !ok {
  1705. log.Debug("no CPU allocation for " + key)
  1706. CPUAllocsV = []*util.Vector{}
  1707. }
  1708. GPUReqV, ok := GPUReqMap[key]
  1709. if !ok {
  1710. log.Debug("no GPU requests for " + key)
  1711. GPUReqV = []*util.Vector{}
  1712. }
  1713. var node *costAnalyzerCloud.Node
  1714. if n, ok := missingNodes[c.NodeName]; ok {
  1715. node = n
  1716. } else {
  1717. node = &costAnalyzerCloud.Node{}
  1718. missingNodes[c.NodeName] = node
  1719. }
  1720. nsKey := c.Namespace + "," + c.ClusterID
  1721. podKey := c.Namespace + "," + c.PodName + "," + c.ClusterID
  1722. namespaceLabels, _ := namespaceLabelsMapping[nsKey]
  1723. pLabels := podLabels[podKey]
  1724. if pLabels == nil {
  1725. pLabels = make(map[string]string)
  1726. }
  1727. for k, v := range namespaceLabels {
  1728. if _, ok := pLabels[k]; !ok {
  1729. pLabels[k] = v
  1730. }
  1731. }
  1732. namespaceAnnotations, _ := namespaceAnnotationsMapping[nsKey]
  1733. pAnnotations := podAnnotations[podKey]
  1734. if pAnnotations == nil {
  1735. pAnnotations = make(map[string]string)
  1736. }
  1737. for k, v := range namespaceAnnotations {
  1738. if _, ok := pAnnotations[k]; !ok {
  1739. pAnnotations[k] = v
  1740. }
  1741. }
  1742. var podDeployments []string
  1743. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1744. if ds, ok := podDeploymentsMapping[nsKey][c.PodName]; ok {
  1745. podDeployments = ds
  1746. } else {
  1747. podDeployments = []string{}
  1748. }
  1749. }
  1750. var podStatefulSets []string
  1751. if _, ok := podStatefulsetsMapping[nsKey]; ok {
  1752. if ss, ok := podStatefulsetsMapping[nsKey][c.PodName]; ok {
  1753. podStatefulSets = ss
  1754. } else {
  1755. podStatefulSets = []string{}
  1756. }
  1757. }
  1758. var podServices []string
  1759. if _, ok := podServicesMapping[nsKey]; ok {
  1760. if svcs, ok := podServicesMapping[nsKey][c.PodName]; ok {
  1761. podServices = svcs
  1762. } else {
  1763. podServices = []string{}
  1764. }
  1765. }
  1766. var podPVs []*PersistentVolumeClaimData
  1767. var podNetCosts []*util.Vector
  1768. // For PVC data, we'll need to find the claim mapping and cost data. Will need to append
  1769. // cost data since that was populated by cluster data previously. We do this with
  1770. // the pod_pvc_allocation metric
  1771. podPVData, ok := pvAllocationMapping[podKey]
  1772. if !ok {
  1773. log.Debugf("Failed to locate pv allocation mapping for missing pod.")
  1774. }
  1775. // Delete the current pod key from potentially unmounted pvs
  1776. delete(unmountedPVs, podKey)
  1777. // For network costs, we'll use existing map since it should still contain the
  1778. // correct data.
  1779. var podNetworkCosts []*util.Vector
  1780. if usage, ok := networkUsageMap[podKey]; ok {
  1781. netCosts, err := GetNetworkCost(usage, cp)
  1782. if err != nil {
  1783. log.Errorf("Error pulling network costs: %s", err.Error())
  1784. } else {
  1785. podNetworkCosts = netCosts
  1786. }
  1787. }
  1788. // Check to see if any other data has been recorded for this namespace, pod, clusterId
  1789. // Follow the pattern of only allowing claims data per pod
  1790. if !otherClusterPVRecorded[podKey] {
  1791. otherClusterPVRecorded[podKey] = true
  1792. podPVs = podPVData
  1793. podNetCosts = podNetworkCosts
  1794. }
  1795. pds := []string{}
  1796. if ds, ok := podDaemonsets[podKey]; ok {
  1797. pds = []string{ds}
  1798. }
  1799. jobs := []string{}
  1800. if job, ok := podJobs[podKey]; ok {
  1801. jobs = []string{job}
  1802. }
  1803. costs := &CostData{
  1804. Name: c.ContainerName,
  1805. PodName: c.PodName,
  1806. NodeName: c.NodeName,
  1807. NodeData: node,
  1808. Namespace: c.Namespace,
  1809. Services: podServices,
  1810. Deployments: podDeployments,
  1811. Daemonsets: pds,
  1812. Statefulsets: podStatefulSets,
  1813. Jobs: jobs,
  1814. RAMReq: RAMReqV,
  1815. RAMUsed: RAMUsedV,
  1816. CPUReq: CPUReqV,
  1817. CPUUsed: CPUUsedV,
  1818. RAMAllocation: RAMAllocsV,
  1819. CPUAllocation: CPUAllocsV,
  1820. GPUReq: GPUReqV,
  1821. Annotations: pAnnotations,
  1822. Labels: pLabels,
  1823. NamespaceLabels: namespaceLabels,
  1824. PVCData: podPVs,
  1825. NetworkData: podNetCosts,
  1826. ClusterID: c.ClusterID,
  1827. ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
  1828. }
  1829. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1830. containerNameCost[key] = costs
  1831. missingContainers[key] = costs
  1832. }
  1833. }
  1834. unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
  1835. for k, costs := range unmounted {
  1836. log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  1837. if costDataPassesFilters(cm.ClusterMap, costs, filterNamespace, filterCluster) {
  1838. containerNameCost[k] = costs
  1839. }
  1840. }
  1841. if window.Minutes() > 0 {
  1842. dur, off := window.DurationOffsetStrings()
  1843. err = findDeletedNodeInfo(dataSource, missingNodes, dur, off)
  1844. if err != nil {
  1845. log.Errorf("Error fetching historical node data: %s", err.Error())
  1846. }
  1847. }
  1848. return containerNameCost, nil
  1849. }
  1850. func applyAllocationToRequests(allocationMap map[string][]*util.Vector, requestMap map[string][]*util.Vector) {
  1851. // The result of the normalize operation will be a new []*util.Vector to replace the requests
  1852. normalizeOp := func(r *util.Vector, x *float64, y *float64) bool {
  1853. // Omit data (return false) if both x and y inputs don't exist
  1854. if x == nil || y == nil {
  1855. return false
  1856. }
  1857. // If the allocation value is 0, 0 out request value
  1858. if *x == 0 {
  1859. r.Value = 0
  1860. } else {
  1861. r.Value = *y
  1862. }
  1863. return true
  1864. }
  1865. // Run normalization on all request vectors in the mapping
  1866. for k, requests := range requestMap {
  1867. // Only run normalization where there are valid allocations
  1868. allocations, ok := allocationMap[k]
  1869. if !ok {
  1870. delete(requestMap, k)
  1871. continue
  1872. }
  1873. // Replace request map with normalized
  1874. requestMap[k] = util.ApplyVectorOp(allocations, requests, normalizeOp)
  1875. }
  1876. }
  1877. func addMetricPVData(pvAllocationMap map[string][]*PersistentVolumeClaimData, pvCostMap map[string]*costAnalyzerCloud.PV, cp costAnalyzerCloud.Provider) {
  1878. cfg, err := cp.GetConfig()
  1879. if err != nil {
  1880. log.Errorf("Failed to get provider config while adding pv metrics data.")
  1881. return
  1882. }
  1883. for _, pvcDataArray := range pvAllocationMap {
  1884. for _, pvcData := range pvcDataArray {
  1885. costKey := fmt.Sprintf("%s,%s", pvcData.VolumeName, pvcData.ClusterID)
  1886. pvCost, ok := pvCostMap[costKey]
  1887. if !ok {
  1888. pvcData.Volume = &costAnalyzerCloud.PV{
  1889. Cost: cfg.Storage,
  1890. }
  1891. continue
  1892. }
  1893. pvcData.Volume = pvCost
  1894. }
  1895. }
  1896. }
  1897. // Add values that don't already exist in origMap from mergeMap into origMap
  1898. func mergeStringMap(origMap map[string]map[string]string, mergeMap map[string]map[string]string) {
  1899. for k, v := range mergeMap {
  1900. if _, ok := origMap[k]; !ok {
  1901. origMap[k] = v
  1902. }
  1903. }
  1904. }
  1905. func appendLabelsList(mainLabels map[string]map[string][]string, labels map[string]map[string][]string) {
  1906. for k, v := range labels {
  1907. mainLabels[k] = v
  1908. }
  1909. }
  1910. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1911. nsToLabels := make(map[string]map[string]string)
  1912. nss := cache.GetAllNamespaces()
  1913. for _, ns := range nss {
  1914. labels := make(map[string]string)
  1915. for k, v := range ns.Labels {
  1916. labels[promutil.SanitizeLabelName(k)] = v
  1917. }
  1918. nsToLabels[ns.Name+","+clusterID] = labels
  1919. }
  1920. return nsToLabels, nil
  1921. }
  1922. func getNamespaceAnnotations(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  1923. nsToAnnotations := make(map[string]map[string]string)
  1924. nss := cache.GetAllNamespaces()
  1925. for _, ns := range nss {
  1926. annotations := make(map[string]string)
  1927. for k, v := range ns.Annotations {
  1928. annotations[promutil.SanitizeLabelName(k)] = v
  1929. }
  1930. nsToAnnotations[ns.Name+","+clusterID] = annotations
  1931. }
  1932. return nsToAnnotations, nil
  1933. }
  1934. func getDaemonsetsOfPod(pod clustercache.Pod) []string {
  1935. for _, ownerReference := range pod.OwnerReferences {
  1936. if ownerReference.Kind == "DaemonSet" {
  1937. return []string{ownerReference.Name}
  1938. }
  1939. }
  1940. return []string{}
  1941. }
  1942. func getJobsOfPod(pod clustercache.Pod) []string {
  1943. for _, ownerReference := range pod.OwnerReferences {
  1944. if ownerReference.Kind == "Job" {
  1945. return []string{ownerReference.Name}
  1946. }
  1947. }
  1948. return []string{}
  1949. }
  1950. func getStatefulSetsOfPod(pod clustercache.Pod) []string {
  1951. for _, ownerReference := range pod.OwnerReferences {
  1952. if ownerReference.Kind == "StatefulSet" {
  1953. return []string{ownerReference.Name}
  1954. }
  1955. }
  1956. return []string{}
  1957. }
  1958. // getGPUCount reads the node's Status and Labels (via the k8s API) to identify
  1959. // the number of GPUs and vGPUs are equipped on the node. If unable to identify
  1960. // a GPU count, it will return -1.
  1961. func getGPUCount(cache clustercache.ClusterCache, n *clustercache.Node) (float64, float64, error) {
  1962. g, hasGpu := n.Status.Capacity["nvidia.com/gpu"]
  1963. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  1964. // Case 1: Standard NVIDIA GPU
  1965. if hasGpu && g.Value() != 0 && !hasReplicas {
  1966. return float64(g.Value()), float64(g.Value()), nil
  1967. }
  1968. // Case 2: NVIDIA GPU with GPU Feature Discovery (GFD) Pod enabled.
  1969. // Ref: https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html#verifying-the-gpu-time-slicing-configuration
  1970. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L44-L45
  1971. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L103-L118
  1972. if hasReplicas {
  1973. resultGPU := 0.0
  1974. resultVGPU := 0.0
  1975. if c, ok := n.Labels["nvidia.com/gpu.count"]; ok {
  1976. var err error
  1977. resultGPU, err = strconv.ParseFloat(c, 64)
  1978. if err != nil {
  1979. return -1, -1, fmt.Errorf("could not parse label \"nvidia.com/gpu.count\": %v", err)
  1980. }
  1981. }
  1982. if s, ok := n.Status.Capacity["nvidia.com/gpu.shared"]; ok { // GFD configured `renameByDefault=true`
  1983. resultVGPU = float64(s.Value())
  1984. } else if g, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // GFD configured `renameByDefault=false`
  1985. resultVGPU = float64(g.Value())
  1986. } else {
  1987. resultVGPU = resultGPU
  1988. }
  1989. return resultGPU, resultVGPU, nil
  1990. }
  1991. // Case 3: AWS vGPU
  1992. if vgpu, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  1993. vgpuCount, err := getAllocatableVGPUs(cache)
  1994. if err != nil {
  1995. return -1, -1, err
  1996. }
  1997. vgpuCoeff := 10.0
  1998. if vgpuCount > 0.0 {
  1999. vgpuCoeff = vgpuCount
  2000. }
  2001. if vgpu.Value() != 0 {
  2002. resultGPU := float64(vgpu.Value()) / vgpuCoeff
  2003. resultVGPU := float64(vgpu.Value())
  2004. return resultGPU, resultVGPU, nil
  2005. }
  2006. }
  2007. // No GPU found
  2008. return -1, -1, nil
  2009. }
  2010. func getAllocatableVGPUs(cache clustercache.ClusterCache) (float64, error) {
  2011. daemonsets := cache.GetAllDaemonSets()
  2012. vgpuCount := 0.0
  2013. for _, ds := range daemonsets {
  2014. dsContainerList := &ds.SpecContainers
  2015. for _, ctnr := range *dsContainerList {
  2016. if ctnr.Args != nil {
  2017. for _, arg := range ctnr.Args {
  2018. if strings.Contains(arg, "--vgpu=") {
  2019. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  2020. if err != nil {
  2021. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  2022. continue
  2023. }
  2024. vgpuCount = vgpus
  2025. return vgpuCount, nil
  2026. }
  2027. }
  2028. }
  2029. }
  2030. }
  2031. return vgpuCount, nil
  2032. }
  2033. type PersistentVolumeClaimData struct {
  2034. Class string `json:"class"`
  2035. Claim string `json:"claim"`
  2036. Namespace string `json:"namespace"`
  2037. ClusterID string `json:"clusterId"`
  2038. TimesClaimed int `json:"timesClaimed"`
  2039. VolumeName string `json:"volumeName"`
  2040. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  2041. Values []*util.Vector `json:"values"`
  2042. }
  2043. func measureTime(start time.Time, threshold time.Duration, name string) {
  2044. elapsed := time.Since(start)
  2045. if elapsed > threshold {
  2046. log.Infof("[Profiler] %s: %s", elapsed, name)
  2047. }
  2048. }
  2049. func measureTimeAsync(start time.Time, threshold time.Duration, name string, ch chan string) {
  2050. elapsed := time.Since(start)
  2051. if elapsed > threshold {
  2052. ch <- fmt.Sprintf("%s took %s", name, time.Since(start))
  2053. }
  2054. }
  2055. func (cm *CostModel) QueryAllocation(window opencost.Window, resolution, step time.Duration, aggregate []string, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer bool, accumulateBy opencost.AccumulateOption, shareIdle bool) (*opencost.AllocationSetRange, error) {
  2056. // Validate window is legal
  2057. if window.IsOpen() || window.IsNegative() {
  2058. return nil, fmt.Errorf("illegal window: %s", window)
  2059. }
  2060. var totalsStore opencost.TotalsStore
  2061. // Idle is required for proportional asset costs
  2062. if includeProportionalAssetResourceCosts {
  2063. if !includeIdle {
  2064. return nil, errors.New("bad request - includeIdle must be set true if includeProportionalAssetResourceCosts is true")
  2065. }
  2066. totalsStore = opencost.NewMemoryTotalsStore()
  2067. }
  2068. // Begin with empty response
  2069. asr := opencost.NewAllocationSetRange()
  2070. // Query for AllocationSets in increments of the given step duration,
  2071. // appending each to the response.
  2072. stepStart := *window.Start()
  2073. stepEnd := stepStart.Add(step)
  2074. var isAKS bool
  2075. for window.End().After(stepStart) {
  2076. allocSet, err := cm.ComputeAllocation(stepStart, stepEnd, resolution)
  2077. if err != nil {
  2078. return nil, fmt.Errorf("error computing allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2079. }
  2080. if includeIdle {
  2081. assetSet, err := cm.ComputeAssets(stepStart, stepEnd)
  2082. if err != nil {
  2083. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2084. }
  2085. if includeProportionalAssetResourceCosts {
  2086. // AKS is a special case - there can be a maximum of 2
  2087. // load balancers (1 public and 1 private) in an AKS cluster
  2088. // therefore, when calculating PARCs for load balancers,
  2089. // we must know if this is an AKS cluster
  2090. for _, node := range assetSet.Nodes {
  2091. if _, found := node.Labels["label_kubernetes_azure_com_cluster"]; found {
  2092. isAKS = true
  2093. break
  2094. }
  2095. }
  2096. _, err := opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2097. if err != nil {
  2098. log.Errorf("ETL: error updating asset resource totals for %s: %s", assetSet.Window, err)
  2099. }
  2100. }
  2101. idleSet, err := computeIdleAllocations(allocSet, assetSet, true)
  2102. if err != nil {
  2103. return nil, fmt.Errorf("error computing idle allocations for %s: %w", opencost.NewClosedWindow(stepStart, stepEnd), err)
  2104. }
  2105. for _, idleAlloc := range idleSet.Allocations {
  2106. allocSet.Insert(idleAlloc)
  2107. }
  2108. }
  2109. asr.Append(allocSet)
  2110. stepStart = stepEnd
  2111. stepEnd = stepStart.Add(step)
  2112. }
  2113. // Set aggregation options and aggregate
  2114. var shareIdleOpt string
  2115. if shareIdle {
  2116. shareIdleOpt = opencost.ShareWeighted
  2117. } else {
  2118. shareIdleOpt = opencost.ShareNone
  2119. }
  2120. opts := &opencost.AllocationAggregationOptions{
  2121. IncludeProportionalAssetResourceCosts: includeProportionalAssetResourceCosts,
  2122. IdleByNode: idleByNode,
  2123. IncludeAggregatedMetadata: includeAggregatedMetadata,
  2124. ShareIdle: shareIdleOpt,
  2125. }
  2126. // Aggregate
  2127. err := asr.AggregateBy(aggregate, opts)
  2128. if err != nil {
  2129. return nil, fmt.Errorf("error aggregating for %s: %w", window, err)
  2130. }
  2131. // Accumulate, if requested
  2132. if accumulateBy != opencost.AccumulateOptionNone {
  2133. asr, err = asr.Accumulate(accumulateBy)
  2134. if err != nil {
  2135. log.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2136. return nil, fmt.Errorf("error accumulating by %v: %s", accumulateBy, err)
  2137. }
  2138. // when accumulating and returning PARCs, we need the totals for the
  2139. // accumulated windows to accurately compute a fraction
  2140. if includeProportionalAssetResourceCosts {
  2141. assetSet, err := cm.ComputeAssets(*asr.Window().Start(), *asr.Window().End())
  2142. if err != nil {
  2143. return nil, fmt.Errorf("error computing assets for %s: %w", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2144. }
  2145. _, err = opencost.UpdateAssetTotalsStore(totalsStore, assetSet)
  2146. if err != nil {
  2147. log.Errorf("ETL: error updating asset resource totals for %s: %s", opencost.NewClosedWindow(*asr.Window().Start(), *asr.Window().End()), err)
  2148. }
  2149. }
  2150. }
  2151. if includeProportionalAssetResourceCosts {
  2152. for _, as := range asr.Allocations {
  2153. totalStoreByNode, ok := totalsStore.GetAssetTotalsByNode(as.Start(), as.End())
  2154. if !ok {
  2155. log.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2156. return nil, fmt.Errorf("unable to locate allocation totals for node for window %v - %v", as.Start(), as.End())
  2157. }
  2158. totalStoreByCluster, ok := totalsStore.GetAssetTotalsByCluster(as.Start(), as.End())
  2159. if !ok {
  2160. log.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2161. return nil, fmt.Errorf("unable to locate allocation totals for cluster for window %v - %v", as.Start(), as.End())
  2162. }
  2163. var totalPublicLbCost, totalPrivateLbCost float64
  2164. if isAKS && sharedLoadBalancer {
  2165. // loop through all assetTotals, adding all load balancer costs by public and private
  2166. for _, tot := range totalStoreByNode {
  2167. if tot.PrivateLoadBalancer {
  2168. totalPrivateLbCost += tot.LoadBalancerCost
  2169. } else {
  2170. totalPublicLbCost += tot.LoadBalancerCost
  2171. }
  2172. }
  2173. }
  2174. // loop through each allocation set, using total cost from totals store
  2175. for _, alloc := range as.Allocations {
  2176. for rawKey, parc := range alloc.ProportionalAssetResourceCosts {
  2177. key := strings.TrimSuffix(strings.ReplaceAll(rawKey, ",", "/"), "/")
  2178. // for each parc , check the totals store for each
  2179. // on a totals hit, set the corresponding total and calculate percentage
  2180. var totals *opencost.AssetTotals
  2181. if totalsLoc, found := totalStoreByCluster[key]; found {
  2182. totals = totalsLoc
  2183. }
  2184. if totalsLoc, found := totalStoreByNode[key]; found {
  2185. totals = totalsLoc
  2186. }
  2187. if totals == nil {
  2188. log.Errorf("unable to locate asset totals for allocation %s, corresponding PARC is being skipped", key)
  2189. continue
  2190. }
  2191. parc.CPUTotalCost = totals.CPUCost
  2192. parc.GPUTotalCost = totals.GPUCost
  2193. parc.RAMTotalCost = totals.RAMCost
  2194. parc.PVTotalCost = totals.PersistentVolumeCost
  2195. if isAKS && sharedLoadBalancer && len(alloc.LoadBalancers) > 0 {
  2196. // Azure is a special case - use computed totals above
  2197. // use the lbAllocations in the object to determine if
  2198. // this PARC is a public or private load balancer
  2199. // then set the total accordingly
  2200. // AKS only has 1 public and 1 private load balancer
  2201. lbAlloc, found := alloc.LoadBalancers[key]
  2202. if found {
  2203. if lbAlloc.Private {
  2204. parc.LoadBalancerTotalCost = totalPrivateLbCost
  2205. } else {
  2206. parc.LoadBalancerTotalCost = totalPublicLbCost
  2207. }
  2208. }
  2209. } else {
  2210. parc.LoadBalancerTotalCost = totals.LoadBalancerCost
  2211. }
  2212. opencost.ComputePercentages(&parc)
  2213. alloc.ProportionalAssetResourceCosts[rawKey] = parc
  2214. }
  2215. }
  2216. }
  2217. }
  2218. return asr, nil
  2219. }
  2220. func computeIdleAllocations(allocSet *opencost.AllocationSet, assetSet *opencost.AssetSet, idleByNode bool) (*opencost.AllocationSet, error) {
  2221. if !allocSet.Window.Equal(assetSet.Window) {
  2222. return nil, fmt.Errorf("cannot compute idle allocations for mismatched sets: %s does not equal %s", allocSet.Window, assetSet.Window)
  2223. }
  2224. var allocTotals map[string]*opencost.AllocationTotals
  2225. var assetTotals map[string]*opencost.AssetTotals
  2226. if idleByNode {
  2227. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationNodeProp)
  2228. assetTotals = opencost.ComputeAssetTotals(assetSet, true)
  2229. } else {
  2230. allocTotals = opencost.ComputeAllocationTotals(allocSet, opencost.AllocationClusterProp)
  2231. assetTotals = opencost.ComputeAssetTotals(assetSet, false)
  2232. }
  2233. start, end := *allocSet.Window.Start(), *allocSet.Window.End()
  2234. idleSet := opencost.NewAllocationSet(start, end)
  2235. for key, assetTotal := range assetTotals {
  2236. allocTotal, ok := allocTotals[key]
  2237. if !ok {
  2238. log.Warnf("ETL: did not find allocations for asset key: %s", key)
  2239. // Use a zero-value set of totals. This indicates either (1) an
  2240. // error computing totals, or (2) that no allocations ran on the
  2241. // given node for the given window.
  2242. allocTotal = &opencost.AllocationTotals{
  2243. Cluster: assetTotal.Cluster,
  2244. Node: assetTotal.Node,
  2245. Start: assetTotal.Start,
  2246. End: assetTotal.End,
  2247. }
  2248. }
  2249. // Insert one idle allocation for each key (whether by node or
  2250. // by cluster), defined as the difference between the total
  2251. // asset cost and the allocated cost per-resource.
  2252. name := fmt.Sprintf("%s/%s", key, opencost.IdleSuffix)
  2253. err := idleSet.Insert(&opencost.Allocation{
  2254. Name: name,
  2255. Window: idleSet.Window.Clone(),
  2256. Properties: &opencost.AllocationProperties{
  2257. Cluster: assetTotal.Cluster,
  2258. Node: assetTotal.Node,
  2259. ProviderID: assetTotal.Node,
  2260. },
  2261. Start: assetTotal.Start,
  2262. End: assetTotal.End,
  2263. CPUCost: assetTotal.TotalCPUCost() - allocTotal.TotalCPUCost(),
  2264. GPUCost: assetTotal.TotalGPUCost() - allocTotal.TotalGPUCost(),
  2265. RAMCost: assetTotal.TotalRAMCost() - allocTotal.TotalRAMCost(),
  2266. })
  2267. if err != nil {
  2268. return nil, fmt.Errorf("failed to insert idle allocation %s: %w", name, err)
  2269. }
  2270. }
  2271. return idleSet, nil
  2272. }