costmodel.go 92 KB

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