costmodel.go 91 KB

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