costmodel.go 84 KB

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