2
0

costmodel.go 89 KB

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