costmodel.go 89 KB

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