costmodel.go 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math"
  7. "net/http"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. costAnalyzerCloud "github.com/kubecost/cost-model/cloud"
  14. "github.com/kubecost/cost-model/clustercache"
  15. prometheusClient "github.com/prometheus/client_golang/api"
  16. v1 "k8s.io/api/core/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/apimachinery/pkg/labels"
  19. "k8s.io/client-go/kubernetes"
  20. "k8s.io/klog"
  21. "github.com/google/uuid"
  22. "golang.org/x/sync/singleflight"
  23. )
  24. const (
  25. statusAPIError = 422
  26. profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
  27. apiPrefix = "/api/v1"
  28. epAlertManagers = apiPrefix + "/alertmanagers"
  29. epQuery = apiPrefix + "/query"
  30. epQueryRange = apiPrefix + "/query_range"
  31. epLabelValues = apiPrefix + "/label/:name/values"
  32. epSeries = apiPrefix + "/series"
  33. epTargets = apiPrefix + "/targets"
  34. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  35. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  36. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  37. epConfig = apiPrefix + "/status/config"
  38. epFlags = apiPrefix + "/status/flags"
  39. clusterIDKey = "CLUSTER_ID"
  40. remoteEnabled = "REMOTE_WRITE_ENABLED"
  41. thanosEnabled = "THANOS_ENABLED"
  42. thanosQueryUrl = "THANOS_QUERY_URL"
  43. )
  44. type CostModel struct {
  45. Cache clustercache.ClusterCache
  46. RequestGroup *singleflight.Group
  47. }
  48. func NewCostModel(cache clustercache.ClusterCache) *CostModel {
  49. // request grouping to prevent over-requesting the same data prior to caching
  50. requestGroup := new(singleflight.Group)
  51. return &CostModel{
  52. Cache: cache,
  53. RequestGroup: requestGroup,
  54. }
  55. }
  56. type CostData struct {
  57. Name string `json:"name,omitempty"`
  58. PodName string `json:"podName,omitempty"`
  59. NodeName string `json:"nodeName,omitempty"`
  60. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  61. Namespace string `json:"namespace,omitempty"`
  62. Deployments []string `json:"deployments,omitempty"`
  63. Services []string `json:"services,omitempty"`
  64. Daemonsets []string `json:"daemonsets,omitempty"`
  65. Statefulsets []string `json:"statefulsets,omitempty"`
  66. Jobs []string `json:"jobs,omitempty"`
  67. RAMReq []*Vector `json:"ramreq,omitempty"`
  68. RAMUsed []*Vector `json:"ramused,omitempty"`
  69. RAMAllocation []*Vector `json:"ramallocated,omitempty"`
  70. CPUReq []*Vector `json:"cpureq,omitempty"`
  71. CPUUsed []*Vector `json:"cpuused,omitempty"`
  72. CPUAllocation []*Vector `json:"cpuallocated,omitempty"`
  73. GPUReq []*Vector `json:"gpureq,omitempty"`
  74. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  75. NetworkData []*Vector `json:"network,omitempty"`
  76. Labels map[string]string `json:"labels,omitempty"`
  77. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  78. ClusterID string `json:"clusterId"`
  79. }
  80. func (cd *CostData) String() string {
  81. 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",
  82. cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
  83. len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
  84. len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
  85. }
  86. // Error collection helper
  87. type ErrorCollector struct {
  88. m sync.Mutex
  89. errors []error
  90. }
  91. // Reports an error to the collector. Ignores if the error is nil.
  92. func (ec *ErrorCollector) Report(e error) {
  93. if e == nil {
  94. return
  95. }
  96. ec.m.Lock()
  97. defer ec.m.Unlock()
  98. ec.errors = append(ec.errors, e)
  99. }
  100. // Whether or not the collector caught errors
  101. func (ec *ErrorCollector) IsError() bool {
  102. ec.m.Lock()
  103. defer ec.m.Unlock()
  104. return len(ec.errors) > 0
  105. }
  106. // Errors caught by the collector
  107. func (ec *ErrorCollector) Errors() []error {
  108. ec.m.Lock()
  109. defer ec.m.Unlock()
  110. errs := make([]error, len(ec.errors))
  111. copy(errs, ec.errors)
  112. return errs
  113. }
  114. const (
  115. queryRAMRequestsStr = `avg(
  116. label_replace(
  117. label_replace(
  118. avg(
  119. count_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD", node!=""}[%s] %s)
  120. *
  121. avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD", node!=""}[%s] %s)
  122. ) by (namespace,container,pod,node,cluster_id) , "container_name","$1","container","(.+)"
  123. ), "pod_name","$1","pod","(.+)"
  124. )
  125. ) by (namespace,container_name,pod_name,node,cluster_id)`
  126. queryRAMUsageStr = `sort_desc(
  127. avg(
  128. label_replace(count_over_time(container_memory_working_set_bytes{container_name!="",container_name!="POD", instance!=""}[%s] %s), "node", "$1", "instance","(.+)")
  129. *
  130. label_replace(avg_over_time(container_memory_working_set_bytes{container_name!="",container_name!="POD", instance!=""}[%s] %s), "node", "$1", "instance","(.+)")
  131. ) by (namespace,container_name,pod_name,node,cluster_id)
  132. )`
  133. queryCPURequestsStr = `avg(
  134. label_replace(
  135. label_replace(
  136. avg(
  137. count_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD", node!=""}[%s] %s)
  138. *
  139. avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD", node!=""}[%s] %s)
  140. ) by (namespace,container,pod,node,cluster_id) , "container_name","$1","container","(.+)"
  141. ), "pod_name","$1","pod","(.+)"
  142. )
  143. ) by (namespace,container_name,pod_name,node,cluster_id)`
  144. queryCPUUsageStr = `avg(
  145. label_replace(
  146. rate(
  147. container_cpu_usage_seconds_total{container_name!="",container_name!="POD",instance!=""}[%s] %s
  148. ) , "node", "$1", "instance", "(.+)"
  149. )
  150. ) by (namespace,container_name,pod_name,node,cluster_id)`
  151. queryGPURequestsStr = `avg(
  152. label_replace(
  153. label_replace(
  154. avg(
  155. count_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s] %s)
  156. *
  157. avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s] %s)
  158. ) by (namespace,container,pod,node,cluster_id) , "container_name","$1","container","(.+)"
  159. ), "pod_name","$1","pod","(.+)"
  160. )
  161. ) by (namespace,container_name,pod_name,node,cluster_id)
  162. * on (pod_name, namespace, cluster_id) group_left(container) label_replace(avg(avg_over_time(kube_pod_status_phase{phase="Running"}[%s] %s)) by (pod,namespace,cluster_id), "pod_name","$1","pod","(.+)")`
  163. queryPVRequestsStr = `avg(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass, namespace, volumename, cluster_id)
  164. *
  165. on (persistentvolumeclaim, namespace, cluster_id) group_right(storageclass, volumename)
  166. sum(kube_persistentvolumeclaim_resource_requests_storage_bytes) by (persistentvolumeclaim, namespace, cluster_id)`
  167. // queryRAMAllocationByteHours yields the total byte-hour RAM allocation over the given
  168. // window, aggregated by container.
  169. // [line 3] sum(all byte measurements) = [byte*scrape] by metric
  170. // [lines 4-6] (") / (approximate scrape count per hour) = [byte*hour] by metric
  171. // [lines 2,7] sum(") by unique container key = [byte*hour] by container
  172. // [lines 1,8] relabeling
  173. queryRAMAllocationByteHours = `label_replace(label_replace(
  174. sum(
  175. sum_over_time(container_memory_allocation_bytes{container!="",container!="POD", node!=""}[%s])
  176. / clamp_min(
  177. count_over_time(container_memory_allocation_bytes{container!="",container!="POD", node!=""}[%s])/%f,
  178. scalar(avg(avg_over_time(prometheus_target_interval_length_seconds[%s])))*%f)
  179. ) by (namespace,container,pod,node,cluster_id)
  180. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  181. // queryCPUAllocationVCPUHours yields the total VCPU-hour CPU allocation over the given
  182. // window, aggregated by container.
  183. // [line 3] sum(all VCPU measurements within given window) = [VCPU*scrape] by metric
  184. // [lines 4-6] (") / (approximate scrape count per hour) = [VCPU*hour] by metric
  185. // [lines 2,7] sum(") by unique container key = [VCPU*hour] by container
  186. // [lines 1,8] relabeling
  187. queryCPUAllocationVCPUHours = `label_replace(label_replace(
  188. sum(
  189. sum_over_time(container_cpu_allocation{container!="",container!="POD", node!=""}[%s])
  190. / clamp_min(
  191. count_over_time(container_cpu_allocation{container!="",container!="POD", node!=""}[%s])/%f,
  192. scalar(avg(avg_over_time(prometheus_target_interval_length_seconds[%s])))*%f)
  193. ) by (namespace,container,pod,node,cluster_id)
  194. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  195. queryPVCAllocation = `avg_over_time(pod_pvc_allocation[%s])`
  196. queryPVHourlyCost = `avg_over_time(pv_hourly_cost[%s])`
  197. queryNSLabels = `avg_over_time(kube_namespace_labels[%s])`
  198. queryPodLabels = `avg_over_time(kube_pod_labels[%s])`
  199. queryDeploymentLabels = `avg_over_time(deployment_match_labels[%s])`
  200. queryStatefulsetLabels = `avg_over_time(statefulSet_match_labels[%s])`
  201. queryServiceLabels = `avg_over_time(service_selector_labels[%s])`
  202. queryZoneNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true"}[%s] %s)) by (namespace,pod_name,cluster_id) / 1024 / 1024 / 1024`
  203. queryRegionNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false"}[%s] %s)) by (namespace,pod_name,cluster_id) / 1024 / 1024 / 1024`
  204. queryInternetNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true"}[%s] %s)) by (namespace,pod_name,cluster_id) / 1024 / 1024 / 1024`
  205. normalizationStr = `max(count_over_time(kube_pod_container_resource_requests_memory_bytes{}[%s] %s))`
  206. )
  207. type PrometheusMetadata struct {
  208. Running bool `json:"running"`
  209. KubecostDataExists bool `json:"kubecostDataExists"`
  210. }
  211. // ValidatePrometheus tells the model what data prometheus has on it.
  212. func ValidatePrometheus(cli prometheusClient.Client, isThanos bool) (*PrometheusMetadata, error) {
  213. q := "up"
  214. if isThanos {
  215. q += " offset 3h"
  216. }
  217. data, err := Query(cli, q)
  218. if err != nil {
  219. return &PrometheusMetadata{
  220. Running: false,
  221. KubecostDataExists: false,
  222. }, err
  223. }
  224. v, kcmetrics, err := getUptimeData(data)
  225. if err != nil {
  226. return &PrometheusMetadata{
  227. Running: false,
  228. KubecostDataExists: false,
  229. }, err
  230. }
  231. if len(v) > 0 {
  232. return &PrometheusMetadata{
  233. Running: true,
  234. KubecostDataExists: kcmetrics,
  235. }, nil
  236. } else {
  237. return &PrometheusMetadata{
  238. Running: false,
  239. KubecostDataExists: false,
  240. }, fmt.Errorf("No running jobs found on Prometheus at %s", cli.URL(epQuery, nil).Path)
  241. }
  242. }
  243. func getUptimeData(qr interface{}) ([]*Vector, bool, error) {
  244. data, ok := qr.(map[string]interface{})["data"]
  245. if !ok {
  246. e, err := wrapPrometheusError(qr)
  247. if err != nil {
  248. return nil, false, err
  249. }
  250. return nil, false, fmt.Errorf(e)
  251. }
  252. r, ok := data.(map[string]interface{})["result"]
  253. if !ok {
  254. return nil, false, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  255. }
  256. results, ok := r.([]interface{})
  257. if !ok {
  258. return nil, false, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  259. }
  260. jobData := []*Vector{}
  261. kubecostMetrics := false
  262. for _, val := range results {
  263. // For now, just do this for validation. TODO: This can be parsed to figure out the exact running jobs.
  264. metrics, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  265. if !ok {
  266. return nil, false, fmt.Errorf("Prometheus vector does not have metric labels")
  267. }
  268. jobname, ok := metrics["job"]
  269. if !ok {
  270. return nil, false, fmt.Errorf("up query does not have job names")
  271. }
  272. if jobname == "kubecost" {
  273. kubecostMetrics = true
  274. }
  275. value, ok := val.(map[string]interface{})["value"]
  276. if !ok {
  277. return nil, false, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
  278. }
  279. dataPoint, ok := value.([]interface{})
  280. if !ok || len(dataPoint) != 2 {
  281. return nil, false, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  282. }
  283. strVal := dataPoint[1].(string)
  284. v, _ := strconv.ParseFloat(strVal, 64)
  285. toReturn := &Vector{
  286. Timestamp: dataPoint[0].(float64),
  287. Value: v,
  288. }
  289. jobData = append(jobData, toReturn)
  290. }
  291. return jobData, kubecostMetrics, nil
  292. }
  293. func ComputeUptimes(cli prometheusClient.Client) (map[string]float64, error) {
  294. res, err := Query(cli, `container_start_time_seconds{container_name != "POD",container_name != ""}`)
  295. if err != nil {
  296. return nil, err
  297. }
  298. vectors, err := GetContainerMetricVector(res, false, 0, os.Getenv(clusterIDKey))
  299. if err != nil {
  300. return nil, err
  301. }
  302. results := make(map[string]float64)
  303. for key, vector := range vectors {
  304. if err != nil {
  305. return nil, err
  306. }
  307. val := vector[0].Value
  308. uptime := time.Now().Sub(time.Unix(int64(val), 0)).Seconds()
  309. results[key] = uptime
  310. }
  311. return results, nil
  312. }
  313. func (cm *CostModel) ComputeCostData(cli prometheusClient.Client, clientset kubernetes.Interface, cp costAnalyzerCloud.Provider, window string, offset string, filterNamespace string) (map[string]*CostData, error) {
  314. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, window, offset, window, offset)
  315. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, window, offset, window, offset)
  316. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, window, offset, window, offset)
  317. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, window, offset)
  318. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, window, offset, window, offset, window, offset)
  319. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  320. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, window, "")
  321. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, window, "")
  322. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, window, "")
  323. normalization := fmt.Sprintf(normalizationStr, window, offset)
  324. // Cluster ID is specific to the source cluster
  325. clusterID := os.Getenv(clusterIDKey)
  326. var wg sync.WaitGroup
  327. wg.Add(11)
  328. var ec ErrorCollector
  329. var resultRAMRequests interface{}
  330. go func() {
  331. defer wg.Done()
  332. var promErr error
  333. resultRAMRequests, promErr = Query(cli, queryRAMRequests)
  334. ec.Report(promErr)
  335. }()
  336. var resultRAMUsage interface{}
  337. go func() {
  338. defer wg.Done()
  339. var promErr error
  340. resultRAMUsage, promErr = Query(cli, queryRAMUsage)
  341. ec.Report(promErr)
  342. }()
  343. var resultCPURequests interface{}
  344. go func() {
  345. defer wg.Done()
  346. var promErr error
  347. resultCPURequests, promErr = Query(cli, queryCPURequests)
  348. ec.Report(promErr)
  349. }()
  350. var resultCPUUsage interface{}
  351. go func() {
  352. defer wg.Done()
  353. var promErr error
  354. resultCPUUsage, promErr = Query(cli, queryCPUUsage)
  355. ec.Report(promErr)
  356. }()
  357. var resultGPURequests interface{}
  358. go func() {
  359. defer wg.Done()
  360. var promErr error
  361. resultGPURequests, promErr = Query(cli, queryGPURequests)
  362. ec.Report(promErr)
  363. }()
  364. var resultPVRequests interface{}
  365. go func() {
  366. defer wg.Done()
  367. var promErr error
  368. resultPVRequests, promErr = Query(cli, queryPVRequests)
  369. ec.Report(promErr)
  370. }()
  371. var resultNetZoneRequests interface{}
  372. go func() {
  373. defer wg.Done()
  374. var promErr error
  375. resultNetZoneRequests, promErr = Query(cli, queryNetZoneRequests)
  376. ec.Report(promErr)
  377. }()
  378. var resultNetRegionRequests interface{}
  379. go func() {
  380. defer wg.Done()
  381. var promErr error
  382. resultNetRegionRequests, promErr = Query(cli, queryNetRegionRequests)
  383. ec.Report(promErr)
  384. }()
  385. var resultNetInternetRequests interface{}
  386. go func() {
  387. defer wg.Done()
  388. var promErr error
  389. resultNetInternetRequests, promErr = Query(cli, queryNetInternetRequests)
  390. ec.Report(promErr)
  391. }()
  392. var normalizationResult interface{}
  393. go func() {
  394. defer wg.Done()
  395. var promErr error
  396. normalizationResult, promErr = Query(cli, normalization)
  397. ec.Report(promErr)
  398. }()
  399. podDeploymentsMapping := make(map[string]map[string][]string)
  400. podServicesMapping := make(map[string]map[string][]string)
  401. namespaceLabelsMapping := make(map[string]map[string]string)
  402. podlist := cm.Cache.GetAllPods()
  403. var k8sErr error
  404. go func() {
  405. defer wg.Done()
  406. podDeploymentsMapping, k8sErr = getPodDeployments(cm.Cache, podlist, clusterID)
  407. if k8sErr != nil {
  408. return
  409. }
  410. podServicesMapping, k8sErr = getPodServices(cm.Cache, podlist, clusterID)
  411. if k8sErr != nil {
  412. return
  413. }
  414. namespaceLabelsMapping, k8sErr = getNamespaceLabels(cm.Cache, clusterID)
  415. if k8sErr != nil {
  416. return
  417. }
  418. }()
  419. wg.Wait()
  420. defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
  421. if ec.IsError() {
  422. for _, promErr := range ec.Errors() {
  423. klog.V(1).Infof("[Warning] Query Error: %s", promErr.Error())
  424. }
  425. // TODO: Categorize fatal prometheus query failures
  426. // return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  427. }
  428. if k8sErr != nil {
  429. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  430. }
  431. normalizationValue, err := getNormalization(normalizationResult)
  432. if err != nil {
  433. return nil, fmt.Errorf("Error parsing normalization values: " + err.Error())
  434. }
  435. nodes, err := cm.GetNodeCost(cp)
  436. if err != nil {
  437. klog.V(1).Infof("[Warning] no Node cost model available: " + err.Error())
  438. return nil, err
  439. }
  440. pvClaimMapping, err := GetPVInfo(resultPVRequests, clusterID)
  441. if err != nil {
  442. klog.Infof("[Warning] Unable to get PV Data: %s", err.Error())
  443. }
  444. if pvClaimMapping != nil {
  445. err = addPVData(cm.Cache, pvClaimMapping, cp)
  446. if err != nil {
  447. return nil, err
  448. }
  449. }
  450. networkUsageMap, err := GetNetworkUsageData(resultNetZoneRequests, resultNetRegionRequests, resultNetInternetRequests, clusterID)
  451. if err != nil {
  452. klog.V(1).Infof("[Warning] Unable to get Network Cost Data: %s", err.Error())
  453. networkUsageMap = make(map[string]*NetworkUsageData)
  454. }
  455. containerNameCost := make(map[string]*CostData)
  456. containers := make(map[string]bool)
  457. RAMReqMap, err := GetContainerMetricVector(resultRAMRequests, true, normalizationValue, clusterID)
  458. if err != nil {
  459. return nil, err
  460. }
  461. for key := range RAMReqMap {
  462. containers[key] = true
  463. }
  464. RAMUsedMap, err := GetContainerMetricVector(resultRAMUsage, true, normalizationValue, clusterID)
  465. if err != nil {
  466. return nil, err
  467. }
  468. for key := range RAMUsedMap {
  469. containers[key] = true
  470. }
  471. CPUReqMap, err := GetContainerMetricVector(resultCPURequests, true, normalizationValue, clusterID)
  472. if err != nil {
  473. return nil, err
  474. }
  475. for key := range CPUReqMap {
  476. containers[key] = true
  477. }
  478. GPUReqMap, err := GetContainerMetricVector(resultGPURequests, true, normalizationValue, clusterID)
  479. if err != nil {
  480. return nil, err
  481. }
  482. for key := range GPUReqMap {
  483. containers[key] = true
  484. }
  485. CPUUsedMap, err := GetContainerMetricVector(resultCPUUsage, false, 0, clusterID) // No need to normalize here, as this comes from a counter
  486. if err != nil {
  487. return nil, err
  488. }
  489. for key := range CPUUsedMap {
  490. containers[key] = true
  491. }
  492. currentContainers := make(map[string]v1.Pod)
  493. for _, pod := range podlist {
  494. if pod.Status.Phase != v1.PodRunning {
  495. continue
  496. }
  497. cs, err := newContainerMetricsFromPod(*pod, clusterID)
  498. if err != nil {
  499. return nil, err
  500. }
  501. for _, c := range cs {
  502. 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.
  503. currentContainers[c.Key()] = *pod
  504. }
  505. }
  506. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  507. missingContainers := make(map[string]*CostData)
  508. for key := range containers {
  509. if _, ok := containerNameCost[key]; ok {
  510. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  511. }
  512. if pod, ok := currentContainers[key]; ok {
  513. podName := pod.GetObjectMeta().GetName()
  514. ns := pod.GetObjectMeta().GetNamespace()
  515. nsLabels := namespaceLabelsMapping[ns+","+clusterID]
  516. podLabels := pod.GetObjectMeta().GetLabels()
  517. if podLabels == nil {
  518. podLabels = make(map[string]string)
  519. }
  520. for k, v := range nsLabels {
  521. podLabels[k] = v
  522. }
  523. nodeName := pod.Spec.NodeName
  524. var nodeData *costAnalyzerCloud.Node
  525. if _, ok := nodes[nodeName]; ok {
  526. nodeData = nodes[nodeName]
  527. }
  528. nsKey := ns + "," + clusterID
  529. var podDeployments []string
  530. if _, ok := podDeploymentsMapping[nsKey]; ok {
  531. if ds, ok := podDeploymentsMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  532. podDeployments = ds
  533. } else {
  534. podDeployments = []string{}
  535. }
  536. }
  537. var podPVs []*PersistentVolumeClaimData
  538. podClaims := pod.Spec.Volumes
  539. for _, vol := range podClaims {
  540. if vol.PersistentVolumeClaim != nil {
  541. name := vol.PersistentVolumeClaim.ClaimName
  542. if pvClaim, ok := pvClaimMapping[ns+","+name+","+clusterID]; ok {
  543. podPVs = append(podPVs, pvClaim)
  544. }
  545. }
  546. }
  547. var podNetCosts []*Vector
  548. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  549. netCosts, err := GetNetworkCost(usage, cp)
  550. if err != nil {
  551. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  552. } else {
  553. podNetCosts = netCosts
  554. }
  555. }
  556. var podServices []string
  557. if _, ok := podServicesMapping[nsKey]; ok {
  558. if svcs, ok := podServicesMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  559. podServices = svcs
  560. } else {
  561. podServices = []string{}
  562. }
  563. }
  564. for i, container := range pod.Spec.Containers {
  565. containerName := container.Name
  566. // recreate the key and look up data for this container
  567. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  568. RAMReqV, ok := RAMReqMap[newKey]
  569. if !ok {
  570. klog.V(4).Info("no RAM requests for " + newKey)
  571. RAMReqV = []*Vector{&Vector{}}
  572. }
  573. RAMUsedV, ok := RAMUsedMap[newKey]
  574. if !ok {
  575. klog.V(4).Info("no RAM usage for " + newKey)
  576. RAMUsedV = []*Vector{&Vector{}}
  577. }
  578. CPUReqV, ok := CPUReqMap[newKey]
  579. if !ok {
  580. klog.V(4).Info("no CPU requests for " + newKey)
  581. CPUReqV = []*Vector{&Vector{}}
  582. }
  583. GPUReqV, ok := GPUReqMap[newKey]
  584. if !ok {
  585. klog.V(4).Info("no GPU requests for " + newKey)
  586. GPUReqV = []*Vector{&Vector{}}
  587. }
  588. CPUUsedV, ok := CPUUsedMap[newKey]
  589. if !ok {
  590. klog.V(4).Info("no CPU usage for " + newKey)
  591. CPUUsedV = []*Vector{&Vector{}}
  592. }
  593. var pvReq []*PersistentVolumeClaimData
  594. var netReq []*Vector
  595. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  596. pvReq = podPVs
  597. netReq = podNetCosts
  598. }
  599. costs := &CostData{
  600. Name: containerName,
  601. PodName: podName,
  602. NodeName: nodeName,
  603. Namespace: ns,
  604. Deployments: podDeployments,
  605. Services: podServices,
  606. Daemonsets: getDaemonsetsOfPod(pod),
  607. Jobs: getJobsOfPod(pod),
  608. Statefulsets: getStatefulSetsOfPod(pod),
  609. NodeData: nodeData,
  610. RAMReq: RAMReqV,
  611. RAMUsed: RAMUsedV,
  612. CPUReq: CPUReqV,
  613. CPUUsed: CPUUsedV,
  614. GPUReq: GPUReqV,
  615. PVCData: pvReq,
  616. NetworkData: netReq,
  617. Labels: podLabels,
  618. NamespaceLabels: nsLabels,
  619. ClusterID: clusterID,
  620. }
  621. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed, "CPU")
  622. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed, "RAM")
  623. if filterNamespace == "" {
  624. containerNameCost[newKey] = costs
  625. } else if costs.Namespace == filterNamespace {
  626. containerNameCost[newKey] = costs
  627. }
  628. }
  629. } else {
  630. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  631. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  632. c, err := NewContainerMetricFromKey(key)
  633. if err != nil {
  634. return nil, err
  635. }
  636. RAMReqV, ok := RAMReqMap[key]
  637. if !ok {
  638. klog.V(4).Info("no RAM requests for " + key)
  639. RAMReqV = []*Vector{&Vector{}}
  640. }
  641. RAMUsedV, ok := RAMUsedMap[key]
  642. if !ok {
  643. klog.V(4).Info("no RAM usage for " + key)
  644. RAMUsedV = []*Vector{&Vector{}}
  645. }
  646. CPUReqV, ok := CPUReqMap[key]
  647. if !ok {
  648. klog.V(4).Info("no CPU requests for " + key)
  649. CPUReqV = []*Vector{&Vector{}}
  650. }
  651. GPUReqV, ok := GPUReqMap[key]
  652. if !ok {
  653. klog.V(4).Info("no GPU requests for " + key)
  654. GPUReqV = []*Vector{&Vector{}}
  655. }
  656. CPUUsedV, ok := CPUUsedMap[key]
  657. if !ok {
  658. klog.V(4).Info("no CPU usage for " + key)
  659. CPUUsedV = []*Vector{&Vector{}}
  660. }
  661. node, ok := nodes[c.NodeName]
  662. if !ok {
  663. klog.V(4).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  664. if n, ok := missingNodes[c.NodeName]; ok {
  665. node = n
  666. } else {
  667. node = &costAnalyzerCloud.Node{}
  668. missingNodes[c.NodeName] = node
  669. }
  670. }
  671. namespacelabels, ok := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
  672. if !ok {
  673. klog.V(3).Infof("Missing data for namespace %s", c.Namespace)
  674. }
  675. costs := &CostData{
  676. Name: c.ContainerName,
  677. PodName: c.PodName,
  678. NodeName: c.NodeName,
  679. NodeData: node,
  680. Namespace: c.Namespace,
  681. RAMReq: RAMReqV,
  682. RAMUsed: RAMUsedV,
  683. CPUReq: CPUReqV,
  684. CPUUsed: CPUUsedV,
  685. GPUReq: GPUReqV,
  686. NamespaceLabels: namespacelabels,
  687. ClusterID: c.ClusterID,
  688. }
  689. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed, "CPU")
  690. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed, "RAM")
  691. if filterNamespace == "" {
  692. containerNameCost[key] = costs
  693. missingContainers[key] = costs
  694. } else if costs.Namespace == filterNamespace {
  695. containerNameCost[key] = costs
  696. missingContainers[key] = costs
  697. }
  698. }
  699. }
  700. err = findDeletedNodeInfo(cli, missingNodes, window)
  701. if err != nil {
  702. klog.V(1).Infof("Error fetching historical node data: %s", err.Error())
  703. }
  704. err = findDeletedPodInfo(cli, missingContainers, window)
  705. if err != nil {
  706. klog.V(1).Infof("Error fetching historical pod data: %s", err.Error())
  707. }
  708. return containerNameCost, err
  709. }
  710. func findDeletedPodInfo(cli prometheusClient.Client, missingContainers map[string]*CostData, window string) error {
  711. if len(missingContainers) > 0 {
  712. queryHistoricalPodLabels := fmt.Sprintf(`kube_pod_labels{}[%s]`, window)
  713. podLabelsResult, err := Query(cli, queryHistoricalPodLabels)
  714. if err != nil {
  715. klog.V(1).Infof("Error parsing historical labels: %s", err.Error())
  716. }
  717. podLabels := make(map[string]map[string]string)
  718. if podLabelsResult != nil {
  719. podLabels, err = labelsFromPrometheusQuery(podLabelsResult)
  720. if err != nil {
  721. klog.V(1).Infof("Error parsing historical labels: %s", err.Error())
  722. }
  723. }
  724. for key, costData := range missingContainers {
  725. cm, _ := NewContainerMetricFromKey(key)
  726. labels, ok := podLabels[cm.PodName]
  727. if !ok {
  728. klog.V(1).Infof("Unable to find historical data for pod '%s'", cm.PodName)
  729. labels = make(map[string]string)
  730. }
  731. for k, v := range costData.NamespaceLabels {
  732. labels[k] = v
  733. }
  734. costData.Labels = labels
  735. }
  736. }
  737. return nil
  738. }
  739. func labelsFromPrometheusQuery(qr interface{}) (map[string]map[string]string, error) {
  740. toReturn := make(map[string]map[string]string)
  741. data, ok := qr.(map[string]interface{})["data"]
  742. if !ok {
  743. e, err := wrapPrometheusError(qr)
  744. if err != nil {
  745. return toReturn, err
  746. }
  747. return toReturn, fmt.Errorf(e)
  748. }
  749. for _, val := range data.(map[string]interface{})["result"].([]interface{}) {
  750. metricInterface, ok := val.(map[string]interface{})["metric"]
  751. if !ok {
  752. return toReturn, fmt.Errorf("Metric field does not exist in data result vector")
  753. }
  754. metricMap, ok := metricInterface.(map[string]interface{})
  755. if !ok {
  756. return toReturn, fmt.Errorf("Metric field is improperly formatted")
  757. }
  758. pod, ok := metricMap["pod"]
  759. if !ok {
  760. return toReturn, fmt.Errorf("pod field does not exist in data result vector")
  761. }
  762. podName, ok := pod.(string)
  763. if !ok {
  764. return toReturn, fmt.Errorf("pod field is improperly formatted")
  765. }
  766. for labelName, labelValue := range metricMap {
  767. parsedLabelName := labelName
  768. parsedLv, ok := labelValue.(string)
  769. if !ok {
  770. return toReturn, fmt.Errorf("label value is improperly formatted")
  771. }
  772. if strings.HasPrefix(parsedLabelName, "label_") {
  773. l := strings.Replace(parsedLabelName, "label_", "", 1)
  774. if podLabels, ok := toReturn[podName]; ok {
  775. podLabels[l] = parsedLv
  776. } else {
  777. toReturn[podName] = make(map[string]string)
  778. toReturn[podName][l] = parsedLv
  779. }
  780. }
  781. }
  782. }
  783. return toReturn, nil
  784. }
  785. func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window string) error {
  786. if len(missingNodes) > 0 {
  787. defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
  788. q := make([]string, 0, len(missingNodes))
  789. for nodename := range missingNodes {
  790. klog.V(4).Infof("Finding data for deleted node %v", nodename)
  791. q = append(q, nodename)
  792. }
  793. l := strings.Join(q, "|")
  794. queryHistoricalCPUCost := fmt.Sprintf(`avg_over_time(node_cpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  795. queryHistoricalRAMCost := fmt.Sprintf(`avg_over_time(node_ram_hourly_cost{instance=~"%s"}[%s])`, l, window)
  796. queryHistoricalGPUCost := fmt.Sprintf(`avg_over_time(node_gpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  797. cpuCostResult, err := Query(cli, queryHistoricalCPUCost)
  798. if err != nil {
  799. return fmt.Errorf("Error fetching cpu cost data: " + err.Error())
  800. }
  801. ramCostResult, err := Query(cli, queryHistoricalRAMCost)
  802. if err != nil {
  803. return fmt.Errorf("Error fetching ram cost data: " + err.Error())
  804. }
  805. gpuCostResult, err := Query(cli, queryHistoricalGPUCost)
  806. if err != nil {
  807. return fmt.Errorf("Error fetching gpu cost data: " + err.Error())
  808. }
  809. cpuCosts, err := getCost(cpuCostResult)
  810. if err != nil {
  811. return err
  812. }
  813. ramCosts, err := getCost(ramCostResult)
  814. if err != nil {
  815. return err
  816. }
  817. gpuCosts, err := getCost(gpuCostResult)
  818. if err != nil {
  819. return err
  820. }
  821. if len(cpuCosts) == 0 {
  822. klog.V(1).Infof("Kubecost prometheus metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
  823. }
  824. for node, costv := range cpuCosts {
  825. if _, ok := missingNodes[node]; ok {
  826. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  827. }
  828. }
  829. for node, costv := range ramCosts {
  830. if _, ok := missingNodes[node]; ok {
  831. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  832. }
  833. }
  834. for node, costv := range gpuCosts {
  835. if _, ok := missingNodes[node]; ok {
  836. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  837. }
  838. }
  839. }
  840. return nil
  841. }
  842. func getContainerAllocation(req []*Vector, used []*Vector, allocationType string) []*Vector {
  843. // The result of the normalize operation will be a new []*Vector to replace the requests
  844. allocationOp := func(r *Vector, x *float64, y *float64) bool {
  845. if x != nil && y != nil {
  846. x1 := *x
  847. if math.IsNaN(x1) {
  848. klog.V(1).Infof("[Warning] NaN value found during %s allocation calculation for requests.", allocationType)
  849. x1 = 0.0
  850. }
  851. y1 := *y
  852. if math.IsNaN(y1) {
  853. klog.V(1).Infof("[Warning] NaN value found during %s allocation calculation for used.", allocationType)
  854. y1 = 0.0
  855. }
  856. r.Value = math.Max(x1, y1)
  857. } else if x != nil {
  858. r.Value = *x
  859. } else if y != nil {
  860. r.Value = *y
  861. }
  862. return true
  863. }
  864. return ApplyVectorOp(req, used, allocationOp)
  865. }
  866. func addPVData(cache clustercache.ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  867. cfg, err := cloud.GetConfig()
  868. if err != nil {
  869. return err
  870. }
  871. storageClasses := cache.GetAllStorageClasses()
  872. storageClassMap := make(map[string]map[string]string)
  873. for _, storageClass := range storageClasses {
  874. params := storageClass.Parameters
  875. storageClassMap[storageClass.ObjectMeta.Name] = params
  876. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  877. storageClassMap["default"] = params
  878. storageClassMap[""] = params
  879. }
  880. }
  881. pvs := cache.GetAllPersistentVolumes()
  882. pvMap := make(map[string]*costAnalyzerCloud.PV)
  883. for _, pv := range pvs {
  884. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  885. if !ok {
  886. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  887. }
  888. cacPv := &costAnalyzerCloud.PV{
  889. Class: pv.Spec.StorageClassName,
  890. Region: pv.Labels[v1.LabelZoneRegion],
  891. Parameters: parameters,
  892. }
  893. err := GetPVCost(cacPv, pv, cloud)
  894. if err != nil {
  895. return err
  896. }
  897. pvMap[pv.Name] = cacPv
  898. }
  899. for _, pvc := range pvClaimMapping {
  900. if vol, ok := pvMap[pvc.VolumeName]; ok {
  901. pvc.Volume = vol
  902. } else {
  903. klog.V(4).Infof("PV not found, using default")
  904. pvc.Volume = &costAnalyzerCloud.PV{
  905. Cost: cfg.Storage,
  906. }
  907. }
  908. }
  909. return nil
  910. }
  911. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cp costAnalyzerCloud.Provider) error {
  912. cfg, err := cp.GetConfig()
  913. if err != nil {
  914. return err
  915. }
  916. key := cp.GetPVKey(kpv, pv.Parameters)
  917. pvWithCost, err := cp.PVPricing(key)
  918. if err != nil {
  919. pv.Cost = cfg.Storage
  920. return err
  921. }
  922. if pvWithCost == nil || pvWithCost.Cost == "" {
  923. pv.Cost = cfg.Storage
  924. return nil // set default cost
  925. }
  926. pv.Cost = pvWithCost.Cost
  927. return nil
  928. }
  929. func (cm *CostModel) GetNodeCost(cp costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  930. cfg, err := cp.GetConfig()
  931. if err != nil {
  932. return nil, err
  933. }
  934. nodeList := cm.Cache.GetAllNodes()
  935. nodes := make(map[string]*costAnalyzerCloud.Node)
  936. for _, n := range nodeList {
  937. name := n.GetObjectMeta().GetName()
  938. nodeLabels := n.GetObjectMeta().GetLabels()
  939. nodeLabels["providerID"] = n.Spec.ProviderID
  940. cnode, err := cp.NodePricing(cp.GetKey(nodeLabels))
  941. if err != nil {
  942. klog.V(1).Infof("[Warning] Error getting node pricing. Error: " + err.Error())
  943. nodes[name] = cnode
  944. continue
  945. }
  946. newCnode := *cnode
  947. var cpu float64
  948. if newCnode.VCPU == "" {
  949. cpu = float64(n.Status.Capacity.Cpu().Value())
  950. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  951. } else {
  952. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  953. if err != nil {
  954. klog.V(1).Infof("[Warning] parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  955. }
  956. }
  957. if math.IsNaN(cpu) {
  958. klog.V(1).Infof("[Warning] cpu parsed as NaN. Setting to 0.")
  959. cpu = 0
  960. }
  961. var ram float64
  962. if newCnode.RAM == "" {
  963. newCnode.RAM = n.Status.Capacity.Memory().String()
  964. }
  965. ram = float64(n.Status.Capacity.Memory().Value())
  966. if math.IsNaN(ram) {
  967. klog.V(1).Infof("[Warning] ram parsed as NaN. Setting to 0.")
  968. ram = 0
  969. }
  970. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  971. if newCnode.GPU != "" && newCnode.GPUCost == "" {
  972. // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  973. klog.V(4).Infof("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels).Features())
  974. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  975. if err != nil {
  976. klog.V(3).Infof("Could not parse default cpu price")
  977. return nil, err
  978. }
  979. if math.IsNaN(defaultCPU) {
  980. klog.V(1).Infof("[Warning] defaultCPU parsed as NaN. Setting to 0.")
  981. defaultCPU = 0
  982. }
  983. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  984. if err != nil {
  985. klog.V(3).Infof("Could not parse default ram price")
  986. return nil, err
  987. }
  988. if math.IsNaN(defaultRAM) {
  989. klog.V(1).Infof("[Warning] defaultRAM parsed as NaN. Setting to 0.")
  990. defaultRAM = 0
  991. }
  992. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  993. if err != nil {
  994. klog.V(3).Infof("Could not parse default gpu price")
  995. return nil, err
  996. }
  997. if math.IsNaN(defaultGPU) {
  998. klog.V(1).Infof("[Warning] defaultGPU parsed as NaN. Setting to 0.")
  999. defaultGPU = 0
  1000. }
  1001. cpuToRAMRatio := defaultCPU / defaultRAM
  1002. if math.IsNaN(cpuToRAMRatio) {
  1003. klog.V(1).Infof("[Warning] cpuToRAMRatio[defaultCPU: %f / defaultRam: %f] is NaN. Setting to 0.", defaultCPU, defaultRAM)
  1004. cpuToRAMRatio = 0
  1005. }
  1006. gpuToRAMRatio := defaultGPU / defaultRAM
  1007. if math.IsNaN(gpuToRAMRatio) {
  1008. klog.V(1).Infof("[Warning] gpuToRAMRatio is NaN. Setting to 0.")
  1009. gpuToRAMRatio = 0
  1010. }
  1011. ramGB := ram / 1024 / 1024 / 1024
  1012. if math.IsNaN(ramGB) {
  1013. klog.V(1).Infof("[Warning] ramGB is NaN. Setting to 0.")
  1014. ramGB = 0
  1015. }
  1016. ramMultiple := gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  1017. if math.IsNaN(ramMultiple) {
  1018. klog.V(1).Infof("[Warning] ramMultiple is NaN. Setting to 0.")
  1019. ramMultiple = 0
  1020. }
  1021. var nodePrice float64
  1022. if newCnode.Cost != "" {
  1023. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1024. if err != nil {
  1025. klog.V(3).Infof("Could not parse total node price")
  1026. return nil, err
  1027. }
  1028. } else {
  1029. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  1030. if err != nil {
  1031. klog.V(3).Infof("Could not parse node vcpu price")
  1032. return nil, err
  1033. }
  1034. }
  1035. if math.IsNaN(nodePrice) {
  1036. klog.V(1).Infof("[Warning] nodePrice parsed as NaN. Setting to 0.")
  1037. nodePrice = 0
  1038. }
  1039. ramPrice := (nodePrice / ramMultiple)
  1040. if math.IsNaN(ramPrice) {
  1041. klog.V(1).Infof("[Warning] ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1042. ramPrice = 0
  1043. }
  1044. cpuPrice := ramPrice * cpuToRAMRatio
  1045. gpuPrice := ramPrice * gpuToRAMRatio
  1046. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1047. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1048. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1049. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1050. } else if newCnode.RAMCost == "" {
  1051. // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  1052. klog.V(4).Infof("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels).Features())
  1053. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1054. if err != nil {
  1055. klog.V(3).Infof("Could not parse default cpu price")
  1056. return nil, err
  1057. }
  1058. if math.IsNaN(defaultCPU) {
  1059. klog.V(1).Infof("[Warning] defaultCPU parsed as NaN. Setting to 0.")
  1060. defaultCPU = 0
  1061. }
  1062. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1063. if err != nil {
  1064. klog.V(3).Infof("Could not parse default ram price")
  1065. return nil, err
  1066. }
  1067. if math.IsNaN(defaultRAM) {
  1068. klog.V(1).Infof("[Warning] defaultRAM parsed as NaN. Setting to 0.")
  1069. defaultRAM = 0
  1070. }
  1071. cpuToRAMRatio := defaultCPU / defaultRAM
  1072. if math.IsNaN(cpuToRAMRatio) {
  1073. klog.V(1).Infof("[Warning] cpuToRAMRatio[defaultCPU: %f / defaultRam: %f] is NaN. Setting to 0.", defaultCPU, defaultRAM)
  1074. cpuToRAMRatio = 0
  1075. }
  1076. ramGB := ram / 1024 / 1024 / 1024
  1077. if math.IsNaN(ramGB) {
  1078. klog.V(1).Infof("[Warning] ramGB is NaN. Setting to 0.")
  1079. ramGB = 0
  1080. }
  1081. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1082. if math.IsNaN(ramMultiple) {
  1083. klog.V(1).Infof("[Warning] ramMultiple is NaN. Setting to 0.")
  1084. ramMultiple = 0
  1085. }
  1086. var nodePrice float64
  1087. if newCnode.Cost != "" {
  1088. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1089. if err != nil {
  1090. klog.V(3).Infof("Could not parse total node price")
  1091. return nil, err
  1092. }
  1093. } else {
  1094. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  1095. if err != nil {
  1096. klog.V(3).Infof("Could not parse node vcpu price")
  1097. return nil, err
  1098. }
  1099. }
  1100. if math.IsNaN(nodePrice) {
  1101. klog.V(1).Infof("[Warning] nodePrice parsed as NaN. Setting to 0.")
  1102. nodePrice = 0
  1103. }
  1104. ramPrice := (nodePrice / ramMultiple)
  1105. if math.IsNaN(ramPrice) {
  1106. klog.V(1).Infof("[Warning] ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1107. ramPrice = 0
  1108. }
  1109. cpuPrice := ramPrice * cpuToRAMRatio
  1110. if defaultRAM != 0 {
  1111. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1112. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1113. } else { // just assign the full price to CPU
  1114. if cpu != 0 {
  1115. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1116. } else {
  1117. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1118. }
  1119. }
  1120. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1121. klog.V(4).Infof("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1122. }
  1123. nodes[name] = &newCnode
  1124. }
  1125. cp.ApplyReservedInstancePricing(nodes)
  1126. return nodes, nil
  1127. }
  1128. func getPodServices(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1129. servicesList := cache.GetAllServices()
  1130. podServicesMapping := make(map[string]map[string][]string)
  1131. for _, service := range servicesList {
  1132. namespace := service.GetObjectMeta().GetNamespace()
  1133. name := service.GetObjectMeta().GetName()
  1134. key := namespace + "," + clusterID
  1135. if _, ok := podServicesMapping[key]; !ok {
  1136. podServicesMapping[key] = make(map[string][]string)
  1137. }
  1138. s := labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  1139. for _, pod := range podList {
  1140. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1141. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1142. services, ok := podServicesMapping[key][pod.GetObjectMeta().GetName()]
  1143. if ok {
  1144. podServicesMapping[key][pod.GetObjectMeta().GetName()] = append(services, name)
  1145. } else {
  1146. podServicesMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1147. }
  1148. }
  1149. }
  1150. }
  1151. return podServicesMapping, nil
  1152. }
  1153. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1154. ssList := cache.GetAllStatefulSets()
  1155. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1156. for _, ss := range ssList {
  1157. namespace := ss.GetObjectMeta().GetNamespace()
  1158. name := ss.GetObjectMeta().GetName()
  1159. key := namespace + "," + clusterID
  1160. if _, ok := podSSMapping[key]; !ok {
  1161. podSSMapping[key] = make(map[string][]string)
  1162. }
  1163. s, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)
  1164. if err != nil {
  1165. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  1166. }
  1167. for _, pod := range podList {
  1168. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1169. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1170. sss, ok := podSSMapping[key][pod.GetObjectMeta().GetName()]
  1171. if ok {
  1172. podSSMapping[key][pod.GetObjectMeta().GetName()] = append(sss, name)
  1173. } else {
  1174. podSSMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1175. }
  1176. }
  1177. }
  1178. }
  1179. return podSSMapping, nil
  1180. }
  1181. func getPodDeployments(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1182. deploymentsList := cache.GetAllDeployments()
  1183. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1184. for _, deployment := range deploymentsList {
  1185. namespace := deployment.GetObjectMeta().GetNamespace()
  1186. name := deployment.GetObjectMeta().GetName()
  1187. key := namespace + "," + clusterID
  1188. if _, ok := podDeploymentsMapping[key]; !ok {
  1189. podDeploymentsMapping[key] = make(map[string][]string)
  1190. }
  1191. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1192. if err != nil {
  1193. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  1194. }
  1195. for _, pod := range podList {
  1196. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1197. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1198. deployments, ok := podDeploymentsMapping[key][pod.GetObjectMeta().GetName()]
  1199. if ok {
  1200. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1201. } else {
  1202. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1203. }
  1204. }
  1205. }
  1206. }
  1207. return podDeploymentsMapping, nil
  1208. }
  1209. func getPodDeploymentsWithMetrics(deploymentLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1210. podDeploymentsMapping := make(map[string]map[string][]string)
  1211. for depKey, depLabels := range deploymentLabels {
  1212. kt, err := NewKeyTuple(depKey)
  1213. if err != nil {
  1214. continue
  1215. }
  1216. namespace := kt.Namespace
  1217. name := kt.Key
  1218. clusterID := kt.ClusterID
  1219. key := namespace + "," + clusterID
  1220. if _, ok := podDeploymentsMapping[key]; !ok {
  1221. podDeploymentsMapping[key] = make(map[string][]string)
  1222. }
  1223. s := labels.Set(depLabels).AsSelectorPreValidated()
  1224. for podKey, pLabels := range podLabels {
  1225. pkey, err := NewKeyTuple(podKey)
  1226. if err != nil {
  1227. continue
  1228. }
  1229. podNamespace := pkey.Namespace
  1230. podName := pkey.Key
  1231. podClusterID := pkey.ClusterID
  1232. labelSet := labels.Set(pLabels)
  1233. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1234. deployments, ok := podDeploymentsMapping[key][podName]
  1235. if ok {
  1236. podDeploymentsMapping[key][podName] = append(deployments, name)
  1237. } else {
  1238. podDeploymentsMapping[key][podName] = []string{name}
  1239. }
  1240. }
  1241. }
  1242. }
  1243. // Remove any duplicate data created by metric names
  1244. pruneDuplicateData(podDeploymentsMapping)
  1245. return podDeploymentsMapping, nil
  1246. }
  1247. func getPodServicesWithMetrics(serviceLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1248. podServicesMapping := make(map[string]map[string][]string)
  1249. for servKey, servLabels := range serviceLabels {
  1250. kt, err := NewKeyTuple(servKey)
  1251. if err != nil {
  1252. continue
  1253. }
  1254. namespace := kt.Namespace
  1255. name := kt.Key
  1256. clusterID := kt.ClusterID
  1257. key := namespace + "," + clusterID
  1258. if _, ok := podServicesMapping[key]; !ok {
  1259. podServicesMapping[key] = make(map[string][]string)
  1260. }
  1261. s := labels.Set(servLabels).AsSelectorPreValidated()
  1262. for podKey, pLabels := range podLabels {
  1263. pkey, err := NewKeyTuple(podKey)
  1264. if err != nil {
  1265. continue
  1266. }
  1267. podNamespace := pkey.Namespace
  1268. podName := pkey.Key
  1269. podClusterID := pkey.ClusterID
  1270. labelSet := labels.Set(pLabels)
  1271. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1272. services, ok := podServicesMapping[key][podName]
  1273. if ok {
  1274. podServicesMapping[key][podName] = append(services, name)
  1275. } else {
  1276. podServicesMapping[key][podName] = []string{name}
  1277. }
  1278. }
  1279. }
  1280. }
  1281. // Remove any duplicate data created by metric names
  1282. pruneDuplicateData(podServicesMapping)
  1283. return podServicesMapping, nil
  1284. }
  1285. // This method alleviates an issue with metrics that used a '_' to replace '-' in deployment
  1286. // and service names. To avoid counting these as multiple deployments/services, we'll remove
  1287. // the '_' version. Not optimal, but takes care of the issue
  1288. func pruneDuplicateData(data map[string]map[string][]string) {
  1289. for _, podMap := range data {
  1290. for podName, values := range podMap {
  1291. podMap[podName] = pruneDuplicates(values)
  1292. }
  1293. }
  1294. }
  1295. // Determine if there is an underscore in the value of a slice. If so, replace _ with -, and then
  1296. // check to see if the result exists in the slice. If both are true, then we DO NOT include that
  1297. // original value in the new slice.
  1298. func pruneDuplicates(s []string) []string {
  1299. m := sliceToSet(s)
  1300. for _, v := range s {
  1301. if strings.Contains(v, "_") {
  1302. name := strings.Replace(v, "_", "-", -1)
  1303. if !m[name] {
  1304. m[name] = true
  1305. }
  1306. delete(m, v)
  1307. }
  1308. }
  1309. return setToSlice(m)
  1310. }
  1311. // Creates a map[string]bool containing the slice values as keys
  1312. func sliceToSet(s []string) map[string]bool {
  1313. m := make(map[string]bool)
  1314. for _, v := range s {
  1315. m[v] = true
  1316. }
  1317. return m
  1318. }
  1319. func setToSlice(m map[string]bool) []string {
  1320. var result []string
  1321. for k, _ := range m {
  1322. result = append(result, k)
  1323. }
  1324. return result
  1325. }
  1326. func costDataPassesFilters(costs *CostData, namespace string, cluster string) bool {
  1327. passesNamespace := namespace == "" || costs.Namespace == namespace
  1328. passesCluster := cluster == "" || costs.ClusterID == cluster
  1329. return passesNamespace && passesCluster
  1330. }
  1331. // Finds the a closest multiple less than value
  1332. func floorMultiple(value int64, multiple int64) int64 {
  1333. return (value / multiple) * multiple
  1334. }
  1335. // Attempt to create a key for the request. Reduce the times to minutes in order to more easily group requests based on
  1336. // real time ranges. If for any reason, the key generation fails, return a uuid to ensure uniqueness.
  1337. func requestKeyFor(startString string, endString string, windowString string, filterNamespace string, filterCluster string, remoteEnabled bool) string {
  1338. fullLayout := "2006-01-02T15:04:05.000Z"
  1339. keyLayout := "2006-01-02T15:04Z"
  1340. sTime, err := time.Parse(fullLayout, startString)
  1341. if err != nil {
  1342. klog.V(1).Infof("[Warning] Start=%s failed to parse when generating request key: %s", startString, err.Error())
  1343. return uuid.New().String()
  1344. }
  1345. eTime, err := time.Parse(fullLayout, endString)
  1346. if err != nil {
  1347. klog.V(1).Infof("[Warning] End=%s failed to parse when generating request key: %s", endString, err.Error())
  1348. return uuid.New().String()
  1349. }
  1350. // We "snap" start time and duration to their closest 5 min multiple less than itself, by
  1351. // applying a snapped duration to a snapped start time.
  1352. durMins := int64(eTime.Sub(sTime).Minutes())
  1353. durMins = floorMultiple(durMins, 5)
  1354. sMins := int64(sTime.Minute())
  1355. sOffset := sMins - floorMultiple(sMins, 5)
  1356. sTime = sTime.Add(-time.Duration(sOffset) * time.Minute)
  1357. eTime = sTime.Add(time.Duration(durMins) * time.Minute)
  1358. startKey := sTime.Format(keyLayout)
  1359. endKey := eTime.Format(keyLayout)
  1360. return fmt.Sprintf("%s,%s,%s,%s,%s,%t", startKey, endKey, windowString, filterNamespace, filterCluster, remoteEnabled)
  1361. }
  1362. // Executes a range query for cost data
  1363. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cp costAnalyzerCloud.Provider,
  1364. startString, endString, windowString string, resolutionHours float64, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1365. // Create a request key for request grouping. This key will be used to represent the cost-model result
  1366. // for the specific inputs to prevent multiple queries for identical data.
  1367. key := requestKeyFor(startString, endString, windowString, filterNamespace, filterCluster, remoteEnabled)
  1368. klog.V(4).Infof("ComputeCostDataRange with Key: %s", key)
  1369. // If there is already a request out that uses the same data, wait for it to return to share the results.
  1370. // Otherwise, start executing.
  1371. result, err, _ := cm.RequestGroup.Do(key, func() (interface{}, error) {
  1372. return cm.costDataRange(cli, clientset, cp, startString, endString, windowString, resolutionHours, filterNamespace, filterCluster, remoteEnabled)
  1373. })
  1374. data, ok := result.(map[string]*CostData)
  1375. if !ok {
  1376. return nil, fmt.Errorf("Failed to cast result as map[string]*CostData")
  1377. }
  1378. return data, err
  1379. }
  1380. func (cm *CostModel) costDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cp costAnalyzerCloud.Provider,
  1381. startString, endString, windowString string, resolutionHours float64, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1382. // Use a heuristic to tell the difference between missed scrapes and an incomplete window
  1383. // of data due to fresh install, etc.
  1384. minimumExpectedScrapeRate := 0.95
  1385. queryRAMAlloc := fmt.Sprintf(queryRAMAllocationByteHours, windowString, windowString, resolutionHours, windowString, minimumExpectedScrapeRate)
  1386. queryCPUAlloc := fmt.Sprintf(queryCPUAllocationVCPUHours, windowString, windowString, resolutionHours, windowString, minimumExpectedScrapeRate)
  1387. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, windowString, "", windowString, "")
  1388. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, windowString, "", windowString, "")
  1389. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, windowString, "", windowString, "")
  1390. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, windowString, "")
  1391. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, windowString, "", windowString, "", windowString, "")
  1392. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  1393. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, windowString, "")
  1394. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, windowString, "")
  1395. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, windowString, "")
  1396. normalization := fmt.Sprintf(normalizationStr, windowString, "")
  1397. layout := "2006-01-02T15:04:05.000Z"
  1398. start, err := time.Parse(layout, startString)
  1399. if err != nil {
  1400. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1401. return nil, err
  1402. }
  1403. end, err := time.Parse(layout, endString)
  1404. if err != nil {
  1405. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1406. return nil, err
  1407. }
  1408. window, err := time.ParseDuration(windowString)
  1409. if err != nil {
  1410. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1411. return nil, err
  1412. }
  1413. clusterID := os.Getenv(clusterIDKey)
  1414. durHrs := end.Sub(start).Hours() + 1
  1415. if remoteEnabled == true {
  1416. remoteLayout := "2006-01-02T15:04:05Z"
  1417. remoteStartStr := start.Format(remoteLayout)
  1418. remoteEndStr := end.Format(remoteLayout)
  1419. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  1420. return CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  1421. }
  1422. numQueries := 20
  1423. var wg sync.WaitGroup
  1424. wg.Add(numQueries)
  1425. queryProfileStart := time.Now()
  1426. queryProfileCh := make(chan string, numQueries)
  1427. var ec ErrorCollector
  1428. var resultRAMRequests interface{}
  1429. go func() {
  1430. defer wg.Done()
  1431. defer measureTimeAsync(time.Now(), profileThreshold, "RAMRequests", queryProfileCh)
  1432. var promErr error
  1433. resultRAMRequests, promErr = QueryRange(cli, queryRAMRequests, start, end, window)
  1434. ec.Report(promErr)
  1435. }()
  1436. var resultRAMUsage interface{}
  1437. go func() {
  1438. defer wg.Done()
  1439. defer measureTimeAsync(time.Now(), profileThreshold, "RAMUsage", queryProfileCh)
  1440. var promErr error
  1441. resultRAMUsage, promErr = QueryRange(cli, queryRAMUsage, start, end, window)
  1442. ec.Report(promErr)
  1443. }()
  1444. var resultCPURequests interface{}
  1445. go func() {
  1446. defer wg.Done()
  1447. defer measureTimeAsync(time.Now(), profileThreshold, "CPURequests", queryProfileCh)
  1448. var promErr error
  1449. resultCPURequests, promErr = QueryRange(cli, queryCPURequests, start, end, window)
  1450. ec.Report(promErr)
  1451. }()
  1452. var resultCPUUsage interface{}
  1453. go func() {
  1454. defer wg.Done()
  1455. defer measureTimeAsync(time.Now(), profileThreshold, "CPUUsage", queryProfileCh)
  1456. var promErr error
  1457. resultCPUUsage, promErr = QueryRange(cli, queryCPUUsage, start, end, window)
  1458. ec.Report(promErr)
  1459. }()
  1460. var resultRAMAllocations interface{}
  1461. go func() {
  1462. defer wg.Done()
  1463. defer measureTimeAsync(time.Now(), profileThreshold, "RAMAllocations", queryProfileCh)
  1464. var promErr error
  1465. resultRAMAllocations, promErr = QueryRange(cli, queryRAMAlloc, start, end, window)
  1466. ec.Report(promErr)
  1467. }()
  1468. var resultCPUAllocations interface{}
  1469. go func() {
  1470. defer wg.Done()
  1471. defer measureTimeAsync(time.Now(), profileThreshold, "CPUAllocations", queryProfileCh)
  1472. var promErr error
  1473. resultCPUAllocations, promErr = QueryRange(cli, queryCPUAlloc, start, end, window)
  1474. ec.Report(promErr)
  1475. }()
  1476. var resultGPURequests interface{}
  1477. go func() {
  1478. defer wg.Done()
  1479. defer measureTimeAsync(time.Now(), profileThreshold, "GPURequests", queryProfileCh)
  1480. var promErr error
  1481. resultGPURequests, promErr = QueryRange(cli, queryGPURequests, start, end, window)
  1482. ec.Report(promErr)
  1483. }()
  1484. var resultPVRequests interface{}
  1485. go func() {
  1486. defer wg.Done()
  1487. defer measureTimeAsync(time.Now(), profileThreshold, "PVRequests", queryProfileCh)
  1488. var promErr error
  1489. resultPVRequests, promErr = QueryRange(cli, queryPVRequests, start, end, window)
  1490. ec.Report(promErr)
  1491. }()
  1492. var resultNetZoneRequests interface{}
  1493. go func() {
  1494. defer wg.Done()
  1495. defer measureTimeAsync(time.Now(), profileThreshold, "NetZoneRequests", queryProfileCh)
  1496. var promErr error
  1497. resultNetZoneRequests, promErr = QueryRange(cli, queryNetZoneRequests, start, end, window)
  1498. ec.Report(promErr)
  1499. }()
  1500. var resultNetRegionRequests interface{}
  1501. go func() {
  1502. defer wg.Done()
  1503. defer measureTimeAsync(time.Now(), profileThreshold, "NetRegionRequests", queryProfileCh)
  1504. var promErr error
  1505. resultNetRegionRequests, promErr = QueryRange(cli, queryNetRegionRequests, start, end, window)
  1506. ec.Report(promErr)
  1507. }()
  1508. var resultNetInternetRequests interface{}
  1509. go func() {
  1510. defer wg.Done()
  1511. defer measureTimeAsync(time.Now(), profileThreshold, "NetInternetRequests", queryProfileCh)
  1512. var promErr error
  1513. resultNetInternetRequests, promErr = QueryRange(cli, queryNetInternetRequests, start, end, window)
  1514. ec.Report(promErr)
  1515. }()
  1516. var pvPodAllocationResults interface{}
  1517. go func() {
  1518. defer wg.Done()
  1519. defer measureTimeAsync(time.Now(), profileThreshold, "PVPodAllocation", queryProfileCh)
  1520. var promErr error
  1521. pvPodAllocationResults, promErr = QueryRange(cli, fmt.Sprintf(queryPVCAllocation, windowString), start, end, window)
  1522. ec.Report(promErr)
  1523. }()
  1524. var pvCostResults interface{}
  1525. go func() {
  1526. defer wg.Done()
  1527. defer measureTimeAsync(time.Now(), profileThreshold, "PVCost", queryProfileCh)
  1528. var promErr error
  1529. pvCostResults, promErr = QueryRange(cli, fmt.Sprintf(queryPVHourlyCost, windowString), start, end, window)
  1530. ec.Report(promErr)
  1531. }()
  1532. var nsLabelsResults interface{}
  1533. go func() {
  1534. defer wg.Done()
  1535. defer measureTimeAsync(time.Now(), profileThreshold, "NSLabels", queryProfileCh)
  1536. var promErr error
  1537. nsLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryNSLabels, windowString), start, end, window)
  1538. ec.Report(promErr)
  1539. }()
  1540. var podLabelsResults interface{}
  1541. go func() {
  1542. defer wg.Done()
  1543. defer measureTimeAsync(time.Now(), profileThreshold, "PodLabels", queryProfileCh)
  1544. var promErr error
  1545. podLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryPodLabels, windowString), start, end, window)
  1546. ec.Report(promErr)
  1547. }()
  1548. var serviceLabelsResults interface{}
  1549. go func() {
  1550. defer wg.Done()
  1551. defer measureTimeAsync(time.Now(), profileThreshold, "ServiceLabels", queryProfileCh)
  1552. var promErr error
  1553. serviceLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryServiceLabels, windowString), start, end, window)
  1554. ec.Report(promErr)
  1555. }()
  1556. var deploymentLabelsResults interface{}
  1557. go func() {
  1558. defer wg.Done()
  1559. defer measureTimeAsync(time.Now(), profileThreshold, "DeploymentLabels", queryProfileCh)
  1560. var promErr error
  1561. deploymentLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryDeploymentLabels, windowString), start, end, window)
  1562. ec.Report(promErr)
  1563. }()
  1564. var statefulsetLabelsResults interface{}
  1565. go func() {
  1566. defer wg.Done()
  1567. defer measureTimeAsync(time.Now(), profileThreshold, "StatefulSetLabels", queryProfileCh)
  1568. var promErr error
  1569. statefulsetLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryStatefulsetLabels, windowString), start, end, window)
  1570. ec.Report(promErr)
  1571. }()
  1572. var normalizationResults interface{}
  1573. go func() {
  1574. defer wg.Done()
  1575. defer measureTimeAsync(time.Now(), profileThreshold, "Normalization", queryProfileCh)
  1576. var promErr error
  1577. normalizationResults, promErr = QueryRange(cli, normalization, start, end, window)
  1578. ec.Report(promErr)
  1579. }()
  1580. podDeploymentsMapping := make(map[string]map[string][]string)
  1581. podStatefulsetsMapping := make(map[string]map[string][]string)
  1582. podServicesMapping := make(map[string]map[string][]string)
  1583. namespaceLabelsMapping := make(map[string]map[string]string)
  1584. podlist := cm.Cache.GetAllPods()
  1585. var k8sErr error
  1586. go func() {
  1587. defer wg.Done()
  1588. podDeploymentsMapping, k8sErr = getPodDeployments(cm.Cache, podlist, clusterID)
  1589. if k8sErr != nil {
  1590. return
  1591. }
  1592. podStatefulsetsMapping, k8sErr = getPodStatefulsets(cm.Cache, podlist, clusterID)
  1593. if k8sErr != nil {
  1594. return
  1595. }
  1596. podServicesMapping, k8sErr = getPodServices(cm.Cache, podlist, clusterID)
  1597. if k8sErr != nil {
  1598. return
  1599. }
  1600. namespaceLabelsMapping, k8sErr = getNamespaceLabels(cm.Cache, clusterID)
  1601. if k8sErr != nil {
  1602. return
  1603. }
  1604. }()
  1605. wg.Wait()
  1606. // collect all query profiling messages
  1607. close(queryProfileCh)
  1608. queryProfileBreakdown := ""
  1609. for msg := range queryProfileCh {
  1610. queryProfileBreakdown += "\n - " + msg
  1611. }
  1612. measureTime(queryProfileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): Prom/k8s Queries: %s", durHrs, queryProfileBreakdown))
  1613. defer measureTime(time.Now(), profileThreshold, fmt.Sprintf("costDataRange(%fh): Processing Query Data", durHrs))
  1614. if ec.IsError() {
  1615. for _, promErr := range ec.Errors() {
  1616. klog.V(1).Infof("[Warning] Query Error: %s", promErr.Error())
  1617. }
  1618. // TODO: Categorize fatal prometheus query failures
  1619. // return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  1620. }
  1621. if k8sErr != nil {
  1622. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  1623. }
  1624. profileStart := time.Now()
  1625. normalizationValue, err := getNormalizations(normalizationResults)
  1626. if err != nil {
  1627. return nil, fmt.Errorf("error computing normalization for start=%s, end=%s, window=%s, res=%f: %s",
  1628. start, end, window, resolutionHours*60*60, err.Error())
  1629. }
  1630. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): compute normalizations", durHrs))
  1631. profileStart = time.Now()
  1632. nodes, err := cm.GetNodeCost(cp)
  1633. if err != nil {
  1634. klog.V(1).Infof("[Warning] no cost model available: " + err.Error())
  1635. return nil, err
  1636. }
  1637. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): GetNodeCost", durHrs))
  1638. profileStart = time.Now()
  1639. pvClaimMapping, err := GetPVInfo(resultPVRequests, clusterID)
  1640. if err != nil {
  1641. // Just log for compatibility with KSM less than 1.6
  1642. klog.Infof("Unable to get PV Data: %s", err.Error())
  1643. }
  1644. if pvClaimMapping != nil {
  1645. err = addPVData(cm.Cache, pvClaimMapping, cp)
  1646. if err != nil {
  1647. return nil, err
  1648. }
  1649. }
  1650. pvCostMapping, err := GetPVCostMetrics(pvCostResults, clusterID)
  1651. if err != nil {
  1652. klog.V(1).Infof("Unable to get PV Hourly Cost Data: %s", err.Error())
  1653. }
  1654. pvAllocationMapping, err := GetPVAllocationMetrics(pvPodAllocationResults, clusterID)
  1655. if err != nil {
  1656. klog.V(1).Infof("Unable to get PV Allocation Cost Data: %s", err.Error())
  1657. }
  1658. if pvAllocationMapping != nil {
  1659. addMetricPVData(pvAllocationMapping, pvCostMapping, cp)
  1660. }
  1661. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): process PV data", durHrs))
  1662. profileStart = time.Now()
  1663. nsLabels, err := GetNamespaceLabelsMetrics(nsLabelsResults, clusterID)
  1664. if err != nil {
  1665. klog.V(1).Infof("Unable to get Namespace Labels for Metrics: %s", err.Error())
  1666. }
  1667. if nsLabels != nil {
  1668. appendNamespaceLabels(namespaceLabelsMapping, nsLabels)
  1669. }
  1670. podLabels, err := GetPodLabelsMetrics(podLabelsResults, clusterID)
  1671. if err != nil {
  1672. klog.V(1).Infof("Unable to get Pod Labels for Metrics: %s", err.Error())
  1673. }
  1674. serviceLabels, err := GetServiceSelectorLabelsMetrics(serviceLabelsResults, clusterID)
  1675. if err != nil {
  1676. klog.V(1).Infof("Unable to get Service Selector Labels for Metrics: %s", err.Error())
  1677. }
  1678. deploymentLabels, err := GetDeploymentMatchLabelsMetrics(deploymentLabelsResults, clusterID)
  1679. if err != nil {
  1680. klog.V(1).Infof("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1681. }
  1682. statefulsetLabels, err := GetStatefulsetMatchLabelsMetrics(statefulsetLabelsResults, clusterID)
  1683. if err != nil {
  1684. klog.V(1).Infof("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1685. }
  1686. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): process labels", durHrs))
  1687. profileStart = time.Now()
  1688. podStatefulsetMetricsMapping, err := getPodDeploymentsWithMetrics(statefulsetLabels, podLabels)
  1689. if err != nil {
  1690. klog.V(1).Infof("Unable to get match Statefulset Labels Metrics to Pods: %s", err.Error())
  1691. }
  1692. appendLabelsList(podStatefulsetsMapping, podStatefulsetMetricsMapping)
  1693. podDeploymentsMetricsMapping, err := getPodDeploymentsWithMetrics(deploymentLabels, podLabels)
  1694. if err != nil {
  1695. klog.V(1).Infof("Unable to get match Deployment Labels Metrics to Pods: %s", err.Error())
  1696. }
  1697. appendLabelsList(podDeploymentsMapping, podDeploymentsMetricsMapping)
  1698. podServicesMetricsMapping, err := getPodServicesWithMetrics(serviceLabels, podLabels)
  1699. if err != nil {
  1700. klog.V(1).Infof("Unable to get match Service Labels Metrics to Pods: %s", err.Error())
  1701. }
  1702. appendLabelsList(podServicesMapping, podServicesMetricsMapping)
  1703. networkUsageMap, err := GetNetworkUsageData(resultNetZoneRequests, resultNetRegionRequests, resultNetInternetRequests, clusterID)
  1704. if err != nil {
  1705. klog.V(1).Infof("Unable to get Network Cost Data: %s", err.Error())
  1706. networkUsageMap = make(map[string]*NetworkUsageData)
  1707. }
  1708. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): process deployments, services, and network usage", durHrs))
  1709. profileStart = time.Now()
  1710. containerNameCost := make(map[string]*CostData)
  1711. containers := make(map[string]bool)
  1712. otherClusterPVRecorded := make(map[string]bool)
  1713. RAMReqMap, err := GetNormalizedContainerMetricVectors(resultRAMRequests, normalizationValue, clusterID)
  1714. if err != nil {
  1715. return nil, err
  1716. }
  1717. for key := range RAMReqMap {
  1718. containers[key] = true
  1719. }
  1720. RAMUsedMap, err := GetNormalizedContainerMetricVectors(resultRAMUsage, normalizationValue, clusterID)
  1721. if err != nil {
  1722. return nil, err
  1723. }
  1724. for key := range RAMUsedMap {
  1725. containers[key] = true
  1726. }
  1727. CPUReqMap, err := GetNormalizedContainerMetricVectors(resultCPURequests, normalizationValue, clusterID)
  1728. if err != nil {
  1729. return nil, err
  1730. }
  1731. for key := range CPUReqMap {
  1732. containers[key] = true
  1733. }
  1734. // No need to normalize here, as this comes from a counter, namely:
  1735. // rate(container_cpu_usage_seconds_total) which properly accounts for normalized rates
  1736. CPUUsedMap, err := GetContainerMetricVectors(resultCPUUsage, clusterID)
  1737. if err != nil {
  1738. return nil, err
  1739. }
  1740. for key := range CPUUsedMap {
  1741. containers[key] = true
  1742. }
  1743. RAMAllocMap, err := GetContainerMetricVectors(resultRAMAllocations, clusterID)
  1744. if err != nil {
  1745. return nil, err
  1746. }
  1747. for key := range RAMAllocMap {
  1748. containers[key] = true
  1749. }
  1750. CPUAllocMap, err := GetContainerMetricVectors(resultCPUAllocations, clusterID)
  1751. if err != nil {
  1752. return nil, err
  1753. }
  1754. for key := range CPUAllocMap {
  1755. containers[key] = true
  1756. }
  1757. GPUReqMap, err := GetNormalizedContainerMetricVectors(resultGPURequests, normalizationValue, clusterID)
  1758. if err != nil {
  1759. return nil, err
  1760. }
  1761. for key := range GPUReqMap {
  1762. containers[key] = true
  1763. }
  1764. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): GetContainerMetricVectors", durHrs))
  1765. profileStart = time.Now()
  1766. // Request metrics can show up after pod eviction and completion.
  1767. // This method synchronizes requests to allocations such that when
  1768. // allocation is 0, so are requests
  1769. applyAllocationToRequests(RAMAllocMap, RAMReqMap)
  1770. applyAllocationToRequests(CPUAllocMap, CPUReqMap)
  1771. currentContainers := make(map[string]v1.Pod)
  1772. for _, pod := range podlist {
  1773. if pod.Status.Phase != v1.PodRunning {
  1774. continue
  1775. }
  1776. cs, err := newContainerMetricsFromPod(*pod, clusterID)
  1777. if err != nil {
  1778. return nil, err
  1779. }
  1780. for _, c := range cs {
  1781. 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.
  1782. currentContainers[c.Key()] = *pod
  1783. }
  1784. }
  1785. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): applyAllocationToRequests", durHrs))
  1786. profileStart = time.Now()
  1787. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1788. missingContainers := make(map[string]*CostData)
  1789. for key := range containers {
  1790. if _, ok := containerNameCost[key]; ok {
  1791. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1792. }
  1793. if pod, ok := currentContainers[key]; ok {
  1794. podName := pod.GetObjectMeta().GetName()
  1795. ns := pod.GetObjectMeta().GetNamespace()
  1796. nodeName := pod.Spec.NodeName
  1797. var nodeData *costAnalyzerCloud.Node
  1798. if _, ok := nodes[nodeName]; ok {
  1799. nodeData = nodes[nodeName]
  1800. }
  1801. nsKey := ns + "," + clusterID
  1802. var podDeployments []string
  1803. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1804. if ds, ok := podDeploymentsMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  1805. podDeployments = ds
  1806. } else {
  1807. podDeployments = []string{}
  1808. }
  1809. }
  1810. var podStatefulSets []string
  1811. if _, ok := podStatefulsetsMapping[nsKey]; ok {
  1812. if ds, ok := podStatefulsetsMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  1813. podStatefulSets = ds
  1814. } else {
  1815. podStatefulSets = []string{}
  1816. }
  1817. }
  1818. var podPVs []*PersistentVolumeClaimData
  1819. podClaims := pod.Spec.Volumes
  1820. for _, vol := range podClaims {
  1821. if vol.PersistentVolumeClaim != nil {
  1822. name := vol.PersistentVolumeClaim.ClaimName
  1823. if pvClaim, ok := pvClaimMapping[ns+","+name+","+clusterID]; ok {
  1824. podPVs = append(podPVs, pvClaim)
  1825. }
  1826. }
  1827. }
  1828. var podNetCosts []*Vector
  1829. if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
  1830. netCosts, err := GetNetworkCost(usage, cp)
  1831. if err != nil {
  1832. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  1833. } else {
  1834. podNetCosts = netCosts
  1835. }
  1836. }
  1837. var podServices []string
  1838. if _, ok := podServicesMapping[nsKey]; ok {
  1839. if svcs, ok := podServicesMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
  1840. podServices = svcs
  1841. } else {
  1842. podServices = []string{}
  1843. }
  1844. }
  1845. nsLabels := namespaceLabelsMapping[nsKey]
  1846. podLabels := pod.GetObjectMeta().GetLabels()
  1847. if podLabels == nil {
  1848. podLabels = make(map[string]string)
  1849. }
  1850. for k, v := range nsLabels {
  1851. podLabels[k] = v
  1852. }
  1853. for i, container := range pod.Spec.Containers {
  1854. containerName := container.Name
  1855. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
  1856. RAMReqV, ok := RAMReqMap[newKey]
  1857. if !ok {
  1858. klog.V(4).Info("no RAM requests for " + newKey)
  1859. RAMReqV = []*Vector{}
  1860. }
  1861. RAMUsedV, ok := RAMUsedMap[newKey]
  1862. if !ok {
  1863. klog.V(4).Info("no RAM usage for " + newKey)
  1864. RAMUsedV = []*Vector{}
  1865. }
  1866. CPUReqV, ok := CPUReqMap[newKey]
  1867. if !ok {
  1868. klog.V(4).Info("no CPU requests for " + newKey)
  1869. CPUReqV = []*Vector{}
  1870. }
  1871. CPUUsedV, ok := CPUUsedMap[newKey]
  1872. if !ok {
  1873. klog.V(4).Info("no CPU usage for " + newKey)
  1874. CPUUsedV = []*Vector{}
  1875. }
  1876. RAMAllocsV, ok := RAMAllocMap[newKey]
  1877. if !ok {
  1878. klog.V(4).Info("no RAM allocation for " + newKey)
  1879. RAMAllocsV = []*Vector{}
  1880. }
  1881. CPUAllocsV, ok := CPUAllocMap[newKey]
  1882. if !ok {
  1883. klog.V(4).Info("no CPU allocation for " + newKey)
  1884. CPUAllocsV = []*Vector{}
  1885. }
  1886. GPUReqV, ok := GPUReqMap[newKey]
  1887. if !ok {
  1888. klog.V(4).Info("no GPU requests for " + newKey)
  1889. GPUReqV = []*Vector{}
  1890. }
  1891. var pvReq []*PersistentVolumeClaimData
  1892. var netReq []*Vector
  1893. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  1894. pvReq = podPVs
  1895. netReq = podNetCosts
  1896. }
  1897. costs := &CostData{
  1898. Name: containerName,
  1899. PodName: podName,
  1900. NodeName: nodeName,
  1901. Namespace: ns,
  1902. Deployments: podDeployments,
  1903. Services: podServices,
  1904. Daemonsets: getDaemonsetsOfPod(pod),
  1905. Jobs: getJobsOfPod(pod),
  1906. Statefulsets: podStatefulSets,
  1907. NodeData: nodeData,
  1908. RAMReq: RAMReqV,
  1909. RAMUsed: RAMUsedV,
  1910. CPUReq: CPUReqV,
  1911. CPUUsed: CPUUsedV,
  1912. RAMAllocation: RAMAllocsV,
  1913. CPUAllocation: CPUAllocsV,
  1914. GPUReq: GPUReqV,
  1915. PVCData: pvReq,
  1916. Labels: podLabels,
  1917. NetworkData: netReq,
  1918. NamespaceLabels: nsLabels,
  1919. ClusterID: clusterID,
  1920. }
  1921. if costDataPassesFilters(costs, filterNamespace, filterCluster) {
  1922. containerNameCost[newKey] = costs
  1923. }
  1924. }
  1925. } else {
  1926. // The container has been deleted, or is from a different clusterID
  1927. // Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  1928. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  1929. c, _ := NewContainerMetricFromKey(key)
  1930. RAMReqV, ok := RAMReqMap[key]
  1931. if !ok {
  1932. klog.V(4).Info("no RAM requests for " + key)
  1933. RAMReqV = []*Vector{}
  1934. }
  1935. RAMUsedV, ok := RAMUsedMap[key]
  1936. if !ok {
  1937. klog.V(4).Info("no RAM usage for " + key)
  1938. RAMUsedV = []*Vector{}
  1939. }
  1940. CPUReqV, ok := CPUReqMap[key]
  1941. if !ok {
  1942. klog.V(4).Info("no CPU requests for " + key)
  1943. CPUReqV = []*Vector{}
  1944. }
  1945. CPUUsedV, ok := CPUUsedMap[key]
  1946. if !ok {
  1947. klog.V(4).Info("no CPU usage for " + key)
  1948. CPUUsedV = []*Vector{}
  1949. }
  1950. RAMAllocsV, ok := RAMAllocMap[key]
  1951. if !ok {
  1952. klog.V(4).Info("no RAM allocation for " + key)
  1953. RAMAllocsV = []*Vector{}
  1954. }
  1955. CPUAllocsV, ok := CPUAllocMap[key]
  1956. if !ok {
  1957. klog.V(4).Info("no CPU allocation for " + key)
  1958. CPUAllocsV = []*Vector{}
  1959. }
  1960. GPUReqV, ok := GPUReqMap[key]
  1961. if !ok {
  1962. klog.V(4).Info("no GPU requests for " + key)
  1963. GPUReqV = []*Vector{}
  1964. }
  1965. node, ok := nodes[c.NodeName]
  1966. if !ok {
  1967. klog.V(4).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  1968. if n, ok := missingNodes[c.NodeName]; ok {
  1969. node = n
  1970. } else {
  1971. node = &costAnalyzerCloud.Node{}
  1972. missingNodes[c.NodeName] = node
  1973. }
  1974. }
  1975. nsKey := c.Namespace + "," + c.ClusterID
  1976. podKey := c.Namespace + "," + c.PodName + "," + c.ClusterID
  1977. namespaceLabels, ok := namespaceLabelsMapping[nsKey]
  1978. if !ok {
  1979. klog.V(3).Infof("Missing data for namespace %s", c.Namespace)
  1980. }
  1981. pLabels := podLabels[podKey]
  1982. if pLabels == nil {
  1983. pLabels = make(map[string]string)
  1984. }
  1985. for k, v := range namespaceLabels {
  1986. pLabels[k] = v
  1987. }
  1988. var podDeployments []string
  1989. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1990. if ds, ok := podDeploymentsMapping[nsKey][c.PodName]; ok {
  1991. podDeployments = ds
  1992. } else {
  1993. podDeployments = []string{}
  1994. }
  1995. }
  1996. var podServices []string
  1997. if _, ok := podServicesMapping[nsKey]; ok {
  1998. if svcs, ok := podServicesMapping[nsKey][c.PodName]; ok {
  1999. podServices = svcs
  2000. } else {
  2001. podServices = []string{}
  2002. }
  2003. }
  2004. var podPVs []*PersistentVolumeClaimData
  2005. var podNetCosts []*Vector
  2006. // For PVC data, we'll need to find the claim mapping and cost data. Will need to append
  2007. // cost data since that was populated by cluster data previously. We do this with
  2008. // the pod_pvc_allocation metric
  2009. podPVData, ok := pvAllocationMapping[podKey]
  2010. if !ok {
  2011. klog.V(4).Infof("Failed to locate pv allocation mapping for missing pod.")
  2012. }
  2013. // For network costs, we'll use existing map since it should still contain the
  2014. // correct data.
  2015. var podNetworkCosts []*Vector
  2016. if usage, ok := networkUsageMap[podKey]; ok {
  2017. netCosts, err := GetNetworkCost(usage, cp)
  2018. if err != nil {
  2019. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  2020. } else {
  2021. podNetworkCosts = netCosts
  2022. }
  2023. }
  2024. // Check to see if any other data has been recorded for this namespace, pod, clusterId
  2025. // Follow the pattern of only allowing claims data per pod
  2026. if !otherClusterPVRecorded[podKey] {
  2027. otherClusterPVRecorded[podKey] = true
  2028. podPVs = podPVData
  2029. podNetCosts = podNetworkCosts
  2030. }
  2031. costs := &CostData{
  2032. Name: c.ContainerName,
  2033. PodName: c.PodName,
  2034. NodeName: c.NodeName,
  2035. NodeData: node,
  2036. Namespace: c.Namespace,
  2037. Services: podServices,
  2038. Deployments: podDeployments,
  2039. RAMReq: RAMReqV,
  2040. RAMUsed: RAMUsedV,
  2041. CPUReq: CPUReqV,
  2042. CPUUsed: CPUUsedV,
  2043. RAMAllocation: RAMAllocsV,
  2044. CPUAllocation: CPUAllocsV,
  2045. GPUReq: GPUReqV,
  2046. Labels: pLabels,
  2047. NamespaceLabels: namespaceLabels,
  2048. PVCData: podPVs,
  2049. NetworkData: podNetCosts,
  2050. ClusterID: c.ClusterID,
  2051. }
  2052. if costDataPassesFilters(costs, filterNamespace, filterCluster) {
  2053. containerNameCost[key] = costs
  2054. missingContainers[key] = costs
  2055. }
  2056. }
  2057. }
  2058. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): build CostData map", durHrs))
  2059. w := end.Sub(start)
  2060. w += window
  2061. if w.Minutes() > 0 {
  2062. wStr := fmt.Sprintf("%dm", int(w.Minutes()))
  2063. err = findDeletedNodeInfo(cli, missingNodes, wStr)
  2064. if err != nil {
  2065. klog.V(1).Infof("Error fetching historical node data: %s", err.Error())
  2066. }
  2067. }
  2068. return containerNameCost, err
  2069. }
  2070. func applyAllocationToRequests(allocationMap map[string][]*Vector, requestMap map[string][]*Vector) {
  2071. // The result of the normalize operation will be a new []*Vector to replace the requests
  2072. normalizeOp := func(r *Vector, x *float64, y *float64) bool {
  2073. // Omit data (return false) if both x and y inputs don't exist
  2074. if x == nil || y == nil {
  2075. return false
  2076. }
  2077. // If the allocation value is 0, 0 out request value
  2078. if *x == 0 {
  2079. r.Value = 0
  2080. } else {
  2081. r.Value = *y
  2082. }
  2083. return true
  2084. }
  2085. // Run normalization on all request vectors in the mapping
  2086. for k, requests := range requestMap {
  2087. // Only run normalization where there are valid allocations
  2088. allocations, ok := allocationMap[k]
  2089. if !ok {
  2090. delete(requestMap, k)
  2091. continue
  2092. }
  2093. // Replace request map with normalized
  2094. requestMap[k] = ApplyVectorOp(allocations, requests, normalizeOp)
  2095. }
  2096. }
  2097. func addMetricPVData(pvAllocationMap map[string][]*PersistentVolumeClaimData, pvCostMap map[string]*costAnalyzerCloud.PV, cp costAnalyzerCloud.Provider) {
  2098. cfg, err := cp.GetConfig()
  2099. if err != nil {
  2100. klog.V(1).Infof("Failed to get provider config while adding pv metrics data.")
  2101. return
  2102. }
  2103. for _, pvcDataArray := range pvAllocationMap {
  2104. for _, pvcData := range pvcDataArray {
  2105. costKey := fmt.Sprintf("%s,%s", pvcData.VolumeName, pvcData.ClusterID)
  2106. pvCost, ok := pvCostMap[costKey]
  2107. if !ok {
  2108. pvcData.Volume = &costAnalyzerCloud.PV{
  2109. Cost: cfg.Storage,
  2110. }
  2111. continue
  2112. }
  2113. pvcData.Volume = pvCost
  2114. }
  2115. }
  2116. }
  2117. // Append labels into nsLabels iff the ns key doesn't already exist
  2118. func appendNamespaceLabels(nsLabels map[string]map[string]string, labels map[string]map[string]string) {
  2119. for k, v := range labels {
  2120. if _, ok := nsLabels[k]; !ok {
  2121. nsLabels[k] = v
  2122. }
  2123. }
  2124. }
  2125. func appendLabelsList(mainLabels map[string]map[string][]string, labels map[string]map[string][]string) {
  2126. for k, v := range labels {
  2127. mainLabels[k] = v
  2128. }
  2129. }
  2130. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  2131. nsToLabels := make(map[string]map[string]string)
  2132. nss := cache.GetAllNamespaces()
  2133. for _, ns := range nss {
  2134. nsToLabels[ns.Name+","+clusterID] = ns.Labels
  2135. }
  2136. return nsToLabels, nil
  2137. }
  2138. func getDaemonsetsOfPod(pod v1.Pod) []string {
  2139. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2140. if ownerReference.Kind == "DaemonSet" {
  2141. return []string{ownerReference.Name}
  2142. }
  2143. }
  2144. return []string{}
  2145. }
  2146. func getJobsOfPod(pod v1.Pod) []string {
  2147. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2148. if ownerReference.Kind == "Job" {
  2149. return []string{ownerReference.Name}
  2150. }
  2151. }
  2152. return []string{}
  2153. }
  2154. func getStatefulSetsOfPod(pod v1.Pod) []string {
  2155. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2156. if ownerReference.Kind == "StatefulSet" {
  2157. return []string{ownerReference.Name}
  2158. }
  2159. }
  2160. return []string{}
  2161. }
  2162. type PersistentVolumeClaimData struct {
  2163. Class string `json:"class"`
  2164. Claim string `json:"claim"`
  2165. Namespace string `json:"namespace"`
  2166. ClusterID string `json:"clusterId"`
  2167. VolumeName string `json:"volumeName"`
  2168. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  2169. Values []*Vector `json:"values"`
  2170. }
  2171. func getCost(qr interface{}) (map[string][]*Vector, error) {
  2172. toReturn := make(map[string][]*Vector)
  2173. result, err := NewQueryResults(qr)
  2174. if err != nil {
  2175. return toReturn, err
  2176. }
  2177. for _, val := range result {
  2178. instance, err := val.GetString("instance")
  2179. if err != nil {
  2180. return toReturn, err
  2181. }
  2182. toReturn[instance] = val.Values
  2183. }
  2184. return toReturn, nil
  2185. }
  2186. func QueryRange(cli prometheusClient.Client, query string, start, end time.Time, step time.Duration) (interface{}, error) {
  2187. u := cli.URL(epQueryRange, nil)
  2188. q := u.Query()
  2189. q.Set("query", query)
  2190. q.Set("start", start.Format(time.RFC3339Nano))
  2191. q.Set("end", end.Format(time.RFC3339Nano))
  2192. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  2193. u.RawQuery = q.Encode()
  2194. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  2195. if err != nil {
  2196. return nil, err
  2197. }
  2198. _, body, warnings, err := cli.Do(context.Background(), req)
  2199. for _, w := range warnings {
  2200. klog.V(3).Infof("%s", w)
  2201. }
  2202. if err != nil {
  2203. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  2204. }
  2205. var toReturn interface{}
  2206. err = json.Unmarshal(body, &toReturn)
  2207. if err != nil {
  2208. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  2209. }
  2210. return toReturn, err
  2211. }
  2212. func Query(cli prometheusClient.Client, query string) (interface{}, error) {
  2213. u := cli.URL(epQuery, nil)
  2214. q := u.Query()
  2215. q.Set("query", query)
  2216. u.RawQuery = q.Encode()
  2217. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  2218. if err != nil {
  2219. return nil, err
  2220. }
  2221. resp, body, warnings, err := cli.Do(context.Background(), req)
  2222. for _, w := range warnings {
  2223. klog.V(3).Infof("%s", w)
  2224. }
  2225. if err != nil {
  2226. if resp == nil {
  2227. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  2228. }
  2229. return nil, fmt.Errorf("%d Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  2230. }
  2231. var toReturn interface{}
  2232. err = json.Unmarshal(body, &toReturn)
  2233. if err != nil {
  2234. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  2235. }
  2236. return toReturn, nil
  2237. }
  2238. //todo: don't cast, implement unmarshaler interface
  2239. func getNormalization(qr interface{}) (float64, error) {
  2240. queryResults, err := NewQueryResults(qr)
  2241. if err != nil {
  2242. return 0, err
  2243. }
  2244. if len(queryResults) > 0 {
  2245. values := queryResults[0].Values
  2246. if len(values) > 0 {
  2247. return values[0].Value, nil
  2248. }
  2249. return 0, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  2250. }
  2251. return 0, fmt.Errorf("Normalization data is empty, kube-state-metrics or node-exporter may not be running")
  2252. }
  2253. //todo: don't cast, implement unmarshaler interface
  2254. func getNormalizations(qr interface{}) ([]*Vector, error) {
  2255. queryResults, err := NewQueryResults(qr)
  2256. if err != nil {
  2257. return nil, err
  2258. }
  2259. if len(queryResults) > 0 {
  2260. vectors := []*Vector{}
  2261. for _, value := range queryResults {
  2262. vectors = append(vectors, value.Values...)
  2263. }
  2264. return vectors, nil
  2265. }
  2266. return nil, fmt.Errorf("normalization data is empty: time window may be invalid or kube-state-metrics or node-exporter may not be running")
  2267. }
  2268. type ContainerMetric struct {
  2269. Namespace string
  2270. PodName string
  2271. ContainerName string
  2272. NodeName string
  2273. ClusterID string
  2274. }
  2275. func (c *ContainerMetric) Key() string {
  2276. return c.Namespace + "," + c.PodName + "," + c.ContainerName + "," + c.NodeName + "," + c.ClusterID
  2277. }
  2278. func NewContainerMetricFromKey(key string) (*ContainerMetric, error) {
  2279. s := strings.Split(key, ",")
  2280. if len(s) == 5 {
  2281. return &ContainerMetric{
  2282. Namespace: s[0],
  2283. PodName: s[1],
  2284. ContainerName: s[2],
  2285. NodeName: s[3],
  2286. ClusterID: s[4],
  2287. }, nil
  2288. }
  2289. return nil, fmt.Errorf("Not a valid key")
  2290. }
  2291. func newContainerMetricFromValues(ns string, podName string, containerName string, nodeName string, clusterId string) *ContainerMetric {
  2292. return &ContainerMetric{
  2293. Namespace: ns,
  2294. PodName: podName,
  2295. ContainerName: containerName,
  2296. NodeName: nodeName,
  2297. ClusterID: clusterId,
  2298. }
  2299. }
  2300. func newContainerMetricsFromPod(pod v1.Pod, clusterID string) ([]*ContainerMetric, error) {
  2301. podName := pod.GetObjectMeta().GetName()
  2302. ns := pod.GetObjectMeta().GetNamespace()
  2303. node := pod.Spec.NodeName
  2304. var cs []*ContainerMetric
  2305. for _, container := range pod.Spec.Containers {
  2306. containerName := container.Name
  2307. cs = append(cs, &ContainerMetric{
  2308. Namespace: ns,
  2309. PodName: podName,
  2310. ContainerName: containerName,
  2311. NodeName: node,
  2312. ClusterID: clusterID,
  2313. })
  2314. }
  2315. return cs, nil
  2316. }
  2317. func newContainerMetricFromPrometheus(metrics map[string]interface{}, defaultClusterID string) (*ContainerMetric, error) {
  2318. cName, ok := metrics["container_name"]
  2319. if !ok {
  2320. return nil, fmt.Errorf("Prometheus vector does not have container name")
  2321. }
  2322. containerName, ok := cName.(string)
  2323. if !ok {
  2324. return nil, fmt.Errorf("Prometheus vector does not have string container name")
  2325. }
  2326. pName, ok := metrics["pod_name"]
  2327. if !ok {
  2328. return nil, fmt.Errorf("Prometheus vector does not have pod name")
  2329. }
  2330. podName, ok := pName.(string)
  2331. if !ok {
  2332. return nil, fmt.Errorf("Prometheus vector does not have string pod name")
  2333. }
  2334. ns, ok := metrics["namespace"]
  2335. if !ok {
  2336. return nil, fmt.Errorf("Prometheus vector does not have namespace")
  2337. }
  2338. namespace, ok := ns.(string)
  2339. if !ok {
  2340. return nil, fmt.Errorf("Prometheus vector does not have string namespace")
  2341. }
  2342. node, ok := metrics["node"]
  2343. if !ok {
  2344. klog.V(4).Info("Prometheus vector does not have node name")
  2345. node = ""
  2346. }
  2347. nodeName, ok := node.(string)
  2348. if !ok {
  2349. return nil, fmt.Errorf("Prometheus vector does not have string node")
  2350. }
  2351. cid, ok := metrics["cluster_id"]
  2352. if !ok {
  2353. klog.V(4).Info("Prometheus vector does not have cluster id")
  2354. cid = defaultClusterID
  2355. }
  2356. clusterID, ok := cid.(string)
  2357. if !ok {
  2358. return nil, fmt.Errorf("Prometheus vector does not have string cluster_id")
  2359. }
  2360. return &ContainerMetric{
  2361. ContainerName: containerName,
  2362. PodName: podName,
  2363. Namespace: namespace,
  2364. NodeName: nodeName,
  2365. ClusterID: clusterID,
  2366. }, nil
  2367. }
  2368. type KeyTuple struct {
  2369. Namespace string
  2370. Key string
  2371. ClusterID string
  2372. }
  2373. func NewKeyTuple(key string) (*KeyTuple, error) {
  2374. r := strings.Split(key, ",")
  2375. if len(r) != 3 {
  2376. return nil, fmt.Errorf("NewKeyTuple() Provided key not containing exactly 3 components.")
  2377. }
  2378. return &KeyTuple{
  2379. Namespace: r[0],
  2380. Key: r[1],
  2381. ClusterID: r[2],
  2382. }, nil
  2383. }
  2384. func GetContainerMetricVector(qr interface{}, normalize bool, normalizationValue float64, defaultClusterID string) (map[string][]*Vector, error) {
  2385. result, err := NewQueryResults(qr)
  2386. if err != nil {
  2387. return nil, err
  2388. }
  2389. containerData := make(map[string][]*Vector)
  2390. for _, val := range result {
  2391. containerMetric, err := newContainerMetricFromPrometheus(val.Metric, defaultClusterID)
  2392. if err != nil {
  2393. return nil, err
  2394. }
  2395. if normalize && normalizationValue != 0 {
  2396. for _, v := range val.Values {
  2397. v.Value = v.Value / normalizationValue
  2398. }
  2399. }
  2400. containerData[containerMetric.Key()] = val.Values
  2401. }
  2402. return containerData, nil
  2403. }
  2404. func GetContainerMetricVectors(qr interface{}, defaultClusterID string) (map[string][]*Vector, error) {
  2405. result, err := NewQueryResults(qr)
  2406. if err != nil {
  2407. return nil, err
  2408. }
  2409. containerData := make(map[string][]*Vector)
  2410. for _, val := range result {
  2411. containerMetric, err := newContainerMetricFromPrometheus(val.Metric, defaultClusterID)
  2412. if err != nil {
  2413. return nil, err
  2414. }
  2415. containerData[containerMetric.Key()] = val.Values
  2416. }
  2417. return containerData, nil
  2418. }
  2419. func GetNormalizedContainerMetricVectors(qr interface{}, normalizationValues []*Vector, defaultClusterID string) (map[string][]*Vector, error) {
  2420. result, err := NewQueryResults(qr)
  2421. if err != nil {
  2422. return nil, err
  2423. }
  2424. containerData := make(map[string][]*Vector)
  2425. for _, val := range result {
  2426. containerMetric, err := newContainerMetricFromPrometheus(val.Metric, defaultClusterID)
  2427. if err != nil {
  2428. return nil, err
  2429. }
  2430. containerData[containerMetric.Key()] = NormalizeVectorByVector(val.Values, normalizationValues)
  2431. }
  2432. return containerData, nil
  2433. }
  2434. func wrapPrometheusError(qr interface{}) (string, error) {
  2435. e, ok := qr.(map[string]interface{})["error"]
  2436. if !ok {
  2437. return "", fmt.Errorf("Unexpected response from Prometheus")
  2438. }
  2439. eStr, ok := e.(string)
  2440. return eStr, nil
  2441. }
  2442. func measureTime(start time.Time, threshold time.Duration, name string) {
  2443. elapsed := time.Since(start)
  2444. if elapsed > threshold {
  2445. klog.V(3).Infof("[Profiler] %s: %s", elapsed, name)
  2446. }
  2447. }
  2448. func measureTimeAsync(start time.Time, threshold time.Duration, name string, ch chan string) {
  2449. elapsed := time.Since(start)
  2450. if elapsed > threshold {
  2451. ch <- fmt.Sprintf("%s took %s", name, time.Since(start))
  2452. }
  2453. }