costmodel.go 89 KB

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