costmodel.go 84 KB

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