costmodel.go 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math"
  7. "net/http"
  8. "os"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. costAnalyzerCloud "github.com/kubecost/cost-model/cloud"
  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. )
  22. const (
  23. statusAPIError = 422
  24. apiPrefix = "/api/v1"
  25. epAlertManagers = apiPrefix + "/alertmanagers"
  26. epQuery = apiPrefix + "/query"
  27. epQueryRange = apiPrefix + "/query_range"
  28. epLabelValues = apiPrefix + "/label/:name/values"
  29. epSeries = apiPrefix + "/series"
  30. epTargets = apiPrefix + "/targets"
  31. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  32. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  33. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  34. epConfig = apiPrefix + "/status/config"
  35. epFlags = apiPrefix + "/status/flags"
  36. remoteEnabled = "REMOTE_WRITE_ENABLED"
  37. CLUSTER_ID = "CLUSTER_ID"
  38. )
  39. type CostModel struct {
  40. Cache ClusterCache
  41. stop chan struct{}
  42. }
  43. func NewCostModel(client kubernetes.Interface) *CostModel {
  44. stopCh := make(chan struct{})
  45. cache := NewKubernetesClusterCache(client)
  46. cache.Run(stopCh)
  47. return &CostModel{
  48. Cache: cache,
  49. stop: stopCh,
  50. }
  51. }
  52. type CostData struct {
  53. Name string `json:"name,omitempty"`
  54. PodName string `json:"podName,omitempty"`
  55. NodeName string `json:"nodeName,omitempty"`
  56. NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
  57. Namespace string `json:"namespace,omitempty"`
  58. Deployments []string `json:"deployments,omitempty"`
  59. Services []string `json:"services,omitempty"`
  60. Daemonsets []string `json:"daemonsets,omitempty"`
  61. Statefulsets []string `json:"statefulsets,omitempty"`
  62. Jobs []string `json:"jobs,omitempty"`
  63. RAMReq []*Vector `json:"ramreq,omitempty"`
  64. RAMUsed []*Vector `json:"ramused,omitempty"`
  65. CPUReq []*Vector `json:"cpureq,omitempty"`
  66. CPUUsed []*Vector `json:"cpuused,omitempty"`
  67. RAMAllocation []*Vector `json:"ramallocated,omitempty"`
  68. CPUAllocation []*Vector `json:"cpuallocated,omitempty"`
  69. GPUReq []*Vector `json:"gpureq,omitempty"`
  70. PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
  71. NetworkData []*Vector `json:"network,omitempty"`
  72. Labels map[string]string `json:"labels,omitempty"`
  73. NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
  74. ClusterID string `json:"clusterId"`
  75. }
  76. type Vector struct {
  77. Timestamp float64 `json:"timestamp"`
  78. Value float64 `json:"value"`
  79. }
  80. const (
  81. queryRAMRequestsStr = `avg(
  82. label_replace(
  83. label_replace(
  84. avg(
  85. count_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD", node!=""}[%s] %s)
  86. *
  87. avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD", node!=""}[%s] %s)
  88. ) by (namespace,container,pod,node) , "container_name","$1","container","(.+)"
  89. ), "pod_name","$1","pod","(.+)"
  90. )
  91. ) by (namespace,container_name,pod_name,node)`
  92. queryRAMUsageStr = `sort_desc(
  93. avg(
  94. label_replace(count_over_time(container_memory_working_set_bytes{container_name!="",container_name!="POD", instance!=""}[%s] %s), "node", "$1", "instance","(.+)")
  95. *
  96. label_replace(avg_over_time(container_memory_working_set_bytes{container_name!="",container_name!="POD", instance!=""}[%s] %s), "node", "$1", "instance","(.+)")
  97. ) by (namespace,container_name,pod_name,node)
  98. )`
  99. queryCPURequestsStr = `avg(
  100. label_replace(
  101. label_replace(
  102. avg(
  103. count_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD", node!=""}[%s] %s)
  104. *
  105. avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD", node!=""}[%s] %s)
  106. ) by (namespace,container,pod,node) , "container_name","$1","container","(.+)"
  107. ), "pod_name","$1","pod","(.+)"
  108. )
  109. ) by (namespace,container_name,pod_name,node)`
  110. queryCPUUsageStr = `avg(
  111. label_replace(
  112. rate(
  113. container_cpu_usage_seconds_total{container_name!="",container_name!="POD",instance!=""}[%s] %s
  114. ) , "node", "$1", "instance", "(.+)"
  115. )
  116. ) by (namespace,container_name,pod_name,node)`
  117. queryGPURequestsStr = `avg(
  118. label_replace(
  119. label_replace(
  120. avg(
  121. count_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s] %s)
  122. *
  123. avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s] %s)
  124. ) by (namespace,container,pod,node) , "container_name","$1","container","(.+)"
  125. ), "pod_name","$1","pod","(.+)"
  126. )
  127. ) by (namespace,container_name,pod_name,node)`
  128. queryPVRequestsStr = `avg(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass, namespace, volumename)
  129. *
  130. on (persistentvolumeclaim, namespace) group_right(storageclass, volumename)
  131. sum(kube_persistentvolumeclaim_resource_requests_storage_bytes) by (persistentvolumeclaim, namespace)`
  132. queryZoneNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true"}[%s] %s)) by (namespace,pod_name) / 1024 / 1024 / 1024`
  133. queryRegionNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false"}[%s] %s)) by (namespace,pod_name) / 1024 / 1024 / 1024`
  134. queryInternetNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true"}[%s] %s)) by (namespace,pod_name) / 1024 / 1024 / 1024`
  135. normalizationStr = `max(count_over_time(kube_pod_container_resource_requests_memory_bytes{}[%s] %s))`
  136. )
  137. type PrometheusMetadata struct {
  138. Running bool `json:"running"`
  139. KubecostDataExists bool `json:"kubecostDataExists"`
  140. }
  141. // ValidatePrometheus tells the model what data prometheus has on it.
  142. func ValidatePrometheus(cli prometheusClient.Client) (*PrometheusMetadata, error) {
  143. data, err := Query(cli, "up")
  144. if err != nil {
  145. return &PrometheusMetadata{
  146. Running: false,
  147. KubecostDataExists: false,
  148. }, err
  149. }
  150. v, kcmetrics, err := getUptimeData(data)
  151. if err != nil {
  152. return &PrometheusMetadata{
  153. Running: false,
  154. KubecostDataExists: false,
  155. }, err
  156. }
  157. if len(v) > 0 {
  158. return &PrometheusMetadata{
  159. Running: true,
  160. KubecostDataExists: kcmetrics,
  161. }, nil
  162. } else {
  163. return &PrometheusMetadata{
  164. Running: false,
  165. KubecostDataExists: false,
  166. }, fmt.Errorf("No running jobs found on Prometheus at %s", cli.URL(epQuery, nil).Path)
  167. }
  168. }
  169. func getUptimeData(qr interface{}) ([]*Vector, bool, error) {
  170. data, ok := qr.(map[string]interface{})["data"]
  171. if !ok {
  172. e, err := wrapPrometheusError(qr)
  173. if err != nil {
  174. return nil, false, err
  175. }
  176. return nil, false, fmt.Errorf(e)
  177. }
  178. r, ok := data.(map[string]interface{})["result"]
  179. if !ok {
  180. return nil, false, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  181. }
  182. results, ok := r.([]interface{})
  183. if !ok {
  184. return nil, false, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  185. }
  186. jobData := []*Vector{}
  187. kubecostMetrics := false
  188. for _, val := range results {
  189. // For now, just do this for validation. TODO: This can be parsed to figure out the exact running jobs.
  190. metrics, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  191. if !ok {
  192. return nil, false, fmt.Errorf("Prometheus vector does not have metric labels")
  193. }
  194. jobname, ok := metrics["job"]
  195. if !ok {
  196. return nil, false, fmt.Errorf("up query does not have job names")
  197. }
  198. if jobname == "kubecost" {
  199. kubecostMetrics = true
  200. }
  201. value, ok := val.(map[string]interface{})["value"]
  202. if !ok {
  203. return nil, false, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
  204. }
  205. dataPoint, ok := value.([]interface{})
  206. if !ok || len(dataPoint) != 2 {
  207. return nil, false, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  208. }
  209. strVal := dataPoint[1].(string)
  210. v, _ := strconv.ParseFloat(strVal, 64)
  211. toReturn := &Vector{
  212. Timestamp: dataPoint[0].(float64),
  213. Value: v,
  214. }
  215. jobData = append(jobData, toReturn)
  216. }
  217. return jobData, kubecostMetrics, nil
  218. }
  219. func ComputeUptimes(cli prometheusClient.Client) (map[string]float64, error) {
  220. res, err := Query(cli, `container_start_time_seconds{container_name != "POD",container_name != ""}`)
  221. if err != nil {
  222. return nil, err
  223. }
  224. vectors, err := GetContainerMetricVector(res, false, 0)
  225. if err != nil {
  226. return nil, err
  227. }
  228. results := make(map[string]float64)
  229. for key, vector := range vectors {
  230. if err != nil {
  231. return nil, err
  232. }
  233. val := vector[0].Value
  234. uptime := time.Now().Sub(time.Unix(int64(val), 0)).Seconds()
  235. results[key] = uptime
  236. }
  237. return results, nil
  238. }
  239. func (cm *CostModel) ComputeCostData(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider, window string, offset string, filterNamespace string) (map[string]*CostData, error) {
  240. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, window, offset, window, offset)
  241. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, window, offset, window, offset)
  242. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, window, offset, window, offset)
  243. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, window, offset)
  244. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, window, offset, window, offset)
  245. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  246. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, window, "")
  247. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, window, "")
  248. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, window, "")
  249. normalization := fmt.Sprintf(normalizationStr, window, offset)
  250. clustID := os.Getenv(CLUSTER_ID)
  251. var wg sync.WaitGroup
  252. wg.Add(11)
  253. var promErr error
  254. var resultRAMRequests interface{}
  255. go func() {
  256. resultRAMRequests, promErr = Query(cli, queryRAMRequests)
  257. defer wg.Done()
  258. }()
  259. var resultRAMUsage interface{}
  260. go func() {
  261. resultRAMUsage, promErr = Query(cli, queryRAMUsage)
  262. defer wg.Done()
  263. }()
  264. var resultCPURequests interface{}
  265. go func() {
  266. resultCPURequests, promErr = Query(cli, queryCPURequests)
  267. defer wg.Done()
  268. }()
  269. var resultCPUUsage interface{}
  270. go func() {
  271. resultCPUUsage, promErr = Query(cli, queryCPUUsage)
  272. defer wg.Done()
  273. }()
  274. var resultGPURequests interface{}
  275. go func() {
  276. resultGPURequests, promErr = Query(cli, queryGPURequests)
  277. defer wg.Done()
  278. }()
  279. var resultPVRequests interface{}
  280. go func() {
  281. resultPVRequests, promErr = Query(cli, queryPVRequests)
  282. defer wg.Done()
  283. }()
  284. var resultNetZoneRequests interface{}
  285. go func() {
  286. resultNetZoneRequests, promErr = Query(cli, queryNetZoneRequests)
  287. defer wg.Done()
  288. }()
  289. var resultNetRegionRequests interface{}
  290. go func() {
  291. resultNetRegionRequests, promErr = Query(cli, queryNetRegionRequests)
  292. defer wg.Done()
  293. }()
  294. var resultNetInternetRequests interface{}
  295. go func() {
  296. resultNetInternetRequests, promErr = Query(cli, queryNetInternetRequests)
  297. defer wg.Done()
  298. }()
  299. var normalizationResult interface{}
  300. go func() {
  301. normalizationResult, promErr = Query(cli, normalization)
  302. defer wg.Done()
  303. }()
  304. podDeploymentsMapping := make(map[string]map[string][]string)
  305. podServicesMapping := make(map[string]map[string][]string)
  306. namespaceLabelsMapping := make(map[string]map[string]string)
  307. podlist := cm.Cache.GetAllPods()
  308. var k8sErr error
  309. go func() {
  310. defer wg.Done()
  311. podDeploymentsMapping, k8sErr = getPodDeployments(cm.Cache, podlist)
  312. if k8sErr != nil {
  313. return
  314. }
  315. podServicesMapping, k8sErr = getPodServices(cm.Cache, podlist)
  316. if k8sErr != nil {
  317. return
  318. }
  319. namespaceLabelsMapping, k8sErr = getNamespaceLabels(cm.Cache)
  320. if k8sErr != nil {
  321. return
  322. }
  323. }()
  324. wg.Wait()
  325. if promErr != nil {
  326. return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  327. }
  328. if k8sErr != nil {
  329. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  330. }
  331. normalizationValue, err := getNormalization(normalizationResult)
  332. if err != nil {
  333. return nil, fmt.Errorf("Error parsing normalization values: " + err.Error())
  334. }
  335. nodes, err := getNodeCost(cm.Cache, cloud)
  336. if err != nil {
  337. klog.V(1).Infof("Warning, no Node cost model available: " + err.Error())
  338. return nil, err
  339. }
  340. pvClaimMapping, err := getPVInfoVector(resultPVRequests)
  341. if err != nil {
  342. klog.Infof("Unable to get PV Data: %s", err.Error())
  343. }
  344. if pvClaimMapping != nil {
  345. err = addPVData(cm.Cache, pvClaimMapping, cloud)
  346. if err != nil {
  347. return nil, err
  348. }
  349. }
  350. networkUsageMap, err := GetNetworkUsageData(resultNetZoneRequests, resultNetRegionRequests, resultNetInternetRequests, false)
  351. if err != nil {
  352. klog.V(1).Infof("Unable to get Network Cost Data: %s", err.Error())
  353. networkUsageMap = make(map[string]*NetworkUsageData)
  354. }
  355. containerNameCost := make(map[string]*CostData)
  356. containers := make(map[string]bool)
  357. RAMReqMap, err := GetContainerMetricVector(resultRAMRequests, true, normalizationValue)
  358. if err != nil {
  359. return nil, err
  360. }
  361. for key := range RAMReqMap {
  362. containers[key] = true
  363. }
  364. RAMUsedMap, err := GetContainerMetricVector(resultRAMUsage, true, normalizationValue)
  365. if err != nil {
  366. return nil, err
  367. }
  368. for key := range RAMUsedMap {
  369. containers[key] = true
  370. }
  371. CPUReqMap, err := GetContainerMetricVector(resultCPURequests, true, normalizationValue)
  372. if err != nil {
  373. return nil, err
  374. }
  375. for key := range CPUReqMap {
  376. containers[key] = true
  377. }
  378. GPUReqMap, err := GetContainerMetricVector(resultGPURequests, true, normalizationValue)
  379. if err != nil {
  380. return nil, err
  381. }
  382. for key := range GPUReqMap {
  383. containers[key] = true
  384. }
  385. CPUUsedMap, err := GetContainerMetricVector(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
  386. if err != nil {
  387. return nil, err
  388. }
  389. for key := range CPUUsedMap {
  390. containers[key] = true
  391. }
  392. currentContainers := make(map[string]v1.Pod)
  393. for _, pod := range podlist {
  394. if pod.Status.Phase != v1.PodRunning {
  395. continue
  396. }
  397. cs, err := newContainerMetricsFromPod(*pod)
  398. if err != nil {
  399. return nil, err
  400. }
  401. for _, c := range cs {
  402. 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.
  403. currentContainers[c.Key()] = *pod
  404. }
  405. }
  406. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  407. missingContainers := make(map[string]*CostData)
  408. for key := range containers {
  409. if _, ok := containerNameCost[key]; ok {
  410. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  411. }
  412. if pod, ok := currentContainers[key]; ok {
  413. podName := pod.GetObjectMeta().GetName()
  414. ns := pod.GetObjectMeta().GetNamespace()
  415. nsLabels := namespaceLabelsMapping[ns]
  416. podLabels := pod.GetObjectMeta().GetLabels()
  417. if podLabels == nil {
  418. podLabels = make(map[string]string)
  419. }
  420. for k, v := range nsLabels {
  421. if _, ok := podLabels[k]; !ok {
  422. podLabels[k] = v
  423. }
  424. }
  425. nodeName := pod.Spec.NodeName
  426. var nodeData *costAnalyzerCloud.Node
  427. if _, ok := nodes[nodeName]; ok {
  428. nodeData = nodes[nodeName]
  429. }
  430. var podDeployments []string
  431. if _, ok := podDeploymentsMapping[ns]; ok {
  432. if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  433. podDeployments = ds
  434. } else {
  435. podDeployments = []string{}
  436. }
  437. }
  438. var podPVs []*PersistentVolumeClaimData
  439. podClaims := pod.Spec.Volumes
  440. for _, vol := range podClaims {
  441. if vol.PersistentVolumeClaim != nil {
  442. name := vol.PersistentVolumeClaim.ClaimName
  443. if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
  444. podPVs = append(podPVs, pvClaim)
  445. }
  446. }
  447. }
  448. var podNetCosts []*Vector
  449. if usage, ok := networkUsageMap[ns+","+podName]; ok {
  450. netCosts, err := GetNetworkCost(usage, cloud)
  451. if err != nil {
  452. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  453. } else {
  454. podNetCosts = netCosts
  455. }
  456. }
  457. var podServices []string
  458. if _, ok := podServicesMapping[ns]; ok {
  459. if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  460. podServices = svcs
  461. } else {
  462. podServices = []string{}
  463. }
  464. }
  465. for i, container := range pod.Spec.Containers {
  466. containerName := container.Name
  467. // recreate the key and look up data for this container
  468. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName).Key()
  469. RAMReqV, ok := RAMReqMap[newKey]
  470. if !ok {
  471. klog.V(4).Info("no RAM requests for " + newKey)
  472. RAMReqV = []*Vector{&Vector{}}
  473. }
  474. RAMUsedV, ok := RAMUsedMap[newKey]
  475. if !ok {
  476. klog.V(4).Info("no RAM usage for " + newKey)
  477. RAMUsedV = []*Vector{&Vector{}}
  478. }
  479. CPUReqV, ok := CPUReqMap[newKey]
  480. if !ok {
  481. klog.V(4).Info("no CPU requests for " + newKey)
  482. CPUReqV = []*Vector{&Vector{}}
  483. }
  484. GPUReqV, ok := GPUReqMap[newKey]
  485. if !ok {
  486. klog.V(4).Info("no GPU requests for " + newKey)
  487. GPUReqV = []*Vector{&Vector{}}
  488. }
  489. CPUUsedV, ok := CPUUsedMap[newKey]
  490. if !ok {
  491. klog.V(4).Info("no CPU usage for " + newKey)
  492. CPUUsedV = []*Vector{&Vector{}}
  493. }
  494. var pvReq []*PersistentVolumeClaimData
  495. var netReq []*Vector
  496. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  497. pvReq = podPVs
  498. netReq = podNetCosts
  499. }
  500. costs := &CostData{
  501. Name: containerName,
  502. PodName: podName,
  503. NodeName: nodeName,
  504. Namespace: ns,
  505. Deployments: podDeployments,
  506. Services: podServices,
  507. Daemonsets: getDaemonsetsOfPod(pod),
  508. Jobs: getJobsOfPod(pod),
  509. Statefulsets: getStatefulSetsOfPod(pod),
  510. NodeData: nodeData,
  511. RAMReq: RAMReqV,
  512. RAMUsed: RAMUsedV,
  513. CPUReq: CPUReqV,
  514. CPUUsed: CPUUsedV,
  515. GPUReq: GPUReqV,
  516. PVCData: pvReq,
  517. NetworkData: netReq,
  518. Labels: podLabels,
  519. NamespaceLabels: nsLabels,
  520. ClusterID: clustID,
  521. }
  522. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  523. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  524. if filterNamespace == "" {
  525. containerNameCost[newKey] = costs
  526. } else if costs.Namespace == filterNamespace {
  527. containerNameCost[newKey] = costs
  528. }
  529. }
  530. } else {
  531. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  532. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  533. c, err := NewContainerMetricFromKey(key)
  534. if err != nil {
  535. return nil, err
  536. }
  537. RAMReqV, ok := RAMReqMap[key]
  538. if !ok {
  539. klog.V(4).Info("no RAM requests for " + key)
  540. RAMReqV = []*Vector{&Vector{}}
  541. }
  542. RAMUsedV, ok := RAMUsedMap[key]
  543. if !ok {
  544. klog.V(4).Info("no RAM usage for " + key)
  545. RAMUsedV = []*Vector{&Vector{}}
  546. }
  547. CPUReqV, ok := CPUReqMap[key]
  548. if !ok {
  549. klog.V(4).Info("no CPU requests for " + key)
  550. CPUReqV = []*Vector{&Vector{}}
  551. }
  552. GPUReqV, ok := GPUReqMap[key]
  553. if !ok {
  554. klog.V(4).Info("no GPU requests for " + key)
  555. GPUReqV = []*Vector{&Vector{}}
  556. }
  557. CPUUsedV, ok := CPUUsedMap[key]
  558. if !ok {
  559. klog.V(4).Info("no CPU usage for " + key)
  560. CPUUsedV = []*Vector{&Vector{}}
  561. }
  562. node, ok := nodes[c.NodeName]
  563. if !ok {
  564. klog.V(2).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  565. if n, ok := missingNodes[c.NodeName]; ok {
  566. node = n
  567. } else {
  568. node = &costAnalyzerCloud.Node{}
  569. missingNodes[c.NodeName] = node
  570. }
  571. }
  572. namespacelabels, ok := namespaceLabelsMapping[c.Namespace]
  573. if !ok {
  574. klog.V(3).Infof("Missing data for namespace %s", c.Namespace)
  575. }
  576. costs := &CostData{
  577. Name: c.ContainerName,
  578. PodName: c.PodName,
  579. NodeName: c.NodeName,
  580. NodeData: node,
  581. Namespace: c.Namespace,
  582. RAMReq: RAMReqV,
  583. RAMUsed: RAMUsedV,
  584. CPUReq: CPUReqV,
  585. CPUUsed: CPUUsedV,
  586. GPUReq: GPUReqV,
  587. NamespaceLabels: namespacelabels,
  588. ClusterID: clustID,
  589. }
  590. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  591. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  592. if filterNamespace == "" {
  593. containerNameCost[key] = costs
  594. missingContainers[key] = costs
  595. } else if costs.Namespace == filterNamespace {
  596. containerNameCost[key] = costs
  597. missingContainers[key] = costs
  598. }
  599. }
  600. }
  601. err = findDeletedNodeInfo(cli, missingNodes, window)
  602. if err != nil {
  603. return nil, err
  604. }
  605. err = findDeletedPodInfo(cli, missingContainers, window)
  606. if err != nil {
  607. return nil, err
  608. }
  609. return containerNameCost, err
  610. }
  611. func findDeletedPodInfo(cli prometheusClient.Client, missingContainers map[string]*CostData, window string) error {
  612. if len(missingContainers) > 0 {
  613. q := make([]string, 0, len(missingContainers))
  614. for key := range missingContainers {
  615. cm, _ := NewContainerMetricFromKey(key)
  616. q = append(q, cm.PodName)
  617. }
  618. l := strings.Join(q, "|")
  619. queryHistoricalPodLabels := fmt.Sprintf(`kube_pod_labels{pod=~"%s"}[%s]`, l, window)
  620. podLabelsResult, err := Query(cli, queryHistoricalPodLabels)
  621. if err != nil {
  622. return fmt.Errorf("Error fetching historical pod labels: " + err.Error())
  623. }
  624. podLabels, err := labelsFromPrometheusQuery(podLabelsResult)
  625. for key, costData := range missingContainers {
  626. cm, _ := NewContainerMetricFromKey(key)
  627. labels, ok := podLabels[cm.PodName]
  628. if !ok {
  629. klog.V(1).Infof("Unable to find historical data for pod '%s'", cm.PodName)
  630. labels = make(map[string]string)
  631. }
  632. for k, v := range costData.NamespaceLabels {
  633. if _, ok := labels[k]; !ok {
  634. labels[k] = v
  635. }
  636. }
  637. costData.Labels = labels
  638. }
  639. }
  640. return nil
  641. }
  642. func labelsFromPrometheusQuery(qr interface{}) (map[string]map[string]string, error) {
  643. toReturn := make(map[string]map[string]string)
  644. for _, val := range qr.(map[string]interface{})["data"].(map[string]interface{})["result"].([]interface{}) {
  645. metricInterface, ok := val.(map[string]interface{})["metric"]
  646. if !ok {
  647. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  648. }
  649. metricMap, ok := metricInterface.(map[string]interface{})
  650. if !ok {
  651. return nil, fmt.Errorf("Metric field is improperly formatted")
  652. }
  653. pod, ok := metricMap["pod"]
  654. if !ok {
  655. return nil, fmt.Errorf("pod field does not exist in data result vector")
  656. }
  657. podName, ok := pod.(string)
  658. if !ok {
  659. return nil, fmt.Errorf("pod field is improperly formatted")
  660. }
  661. for labelName, labelValue := range metricMap {
  662. parsedLabelName := labelName
  663. parsedLv, ok := labelValue.(string)
  664. if !ok {
  665. return nil, fmt.Errorf("label value is improperly formatted")
  666. }
  667. if strings.HasPrefix(parsedLabelName, "label_") {
  668. l := strings.Replace(parsedLabelName, "label_", "", 1)
  669. if podLabels, ok := toReturn[podName]; ok {
  670. podLabels[l] = parsedLv
  671. } else {
  672. toReturn[podName] = make(map[string]string)
  673. toReturn[podName][l] = parsedLv
  674. }
  675. }
  676. }
  677. }
  678. return toReturn, nil
  679. }
  680. func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window string) error {
  681. if len(missingNodes) > 0 {
  682. q := make([]string, 0, len(missingNodes))
  683. for nodename := range missingNodes {
  684. klog.V(3).Infof("Finding data for deleted node %v", nodename)
  685. q = append(q, nodename)
  686. }
  687. l := strings.Join(q, "|")
  688. queryHistoricalCPUCost := fmt.Sprintf(`avg_over_time(node_cpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  689. queryHistoricalRAMCost := fmt.Sprintf(`avg_over_time(node_ram_hourly_cost{instance=~"%s"}[%s])`, l, window)
  690. queryHistoricalGPUCost := fmt.Sprintf(`avg_over_time(node_gpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  691. cpuCostResult, err := Query(cli, queryHistoricalCPUCost)
  692. if err != nil {
  693. return fmt.Errorf("Error fetching cpu cost data: " + err.Error())
  694. }
  695. ramCostResult, err := Query(cli, queryHistoricalRAMCost)
  696. if err != nil {
  697. return fmt.Errorf("Error fetching ram cost data: " + err.Error())
  698. }
  699. gpuCostResult, err := Query(cli, queryHistoricalGPUCost)
  700. if err != nil {
  701. return fmt.Errorf("Error fetching gpu cost data: " + err.Error())
  702. }
  703. cpuCosts, err := getCost(cpuCostResult)
  704. if err != nil {
  705. return err
  706. }
  707. ramCosts, err := getCost(ramCostResult)
  708. if err != nil {
  709. return err
  710. }
  711. gpuCosts, err := getCost(gpuCostResult)
  712. if err != nil {
  713. return err
  714. }
  715. if len(cpuCosts) == 0 {
  716. klog.V(1).Infof("Historical data for node prices not available. Ingest this server's /metrics endpoint to get that data.")
  717. }
  718. for node, costv := range cpuCosts {
  719. if _, ok := missingNodes[node]; ok {
  720. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  721. }
  722. }
  723. for node, costv := range ramCosts {
  724. if _, ok := missingNodes[node]; ok {
  725. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  726. }
  727. }
  728. for node, costv := range gpuCosts {
  729. if _, ok := missingNodes[node]; ok {
  730. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  731. }
  732. }
  733. }
  734. return nil
  735. }
  736. func getContainerAllocation(req []*Vector, used []*Vector) []*Vector {
  737. if req == nil || len(req) == 0 {
  738. for _, usedV := range used {
  739. if usedV.Timestamp == 0 {
  740. continue
  741. }
  742. usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
  743. }
  744. return used
  745. }
  746. if used == nil || len(used) == 0 {
  747. for _, reqV := range req {
  748. if reqV.Timestamp == 0 {
  749. continue
  750. }
  751. reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
  752. }
  753. return req
  754. }
  755. var allocation []*Vector
  756. var timestamps []float64
  757. reqMap := make(map[float64]float64)
  758. for _, reqV := range req {
  759. if reqV.Timestamp == 0 {
  760. continue
  761. }
  762. reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
  763. reqMap[reqV.Timestamp] = reqV.Value
  764. timestamps = append(timestamps, reqV.Timestamp)
  765. }
  766. usedMap := make(map[float64]float64)
  767. for _, usedV := range used {
  768. if usedV.Timestamp == 0 {
  769. continue
  770. }
  771. usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
  772. usedMap[usedV.Timestamp] = usedV.Value
  773. if _, ok := reqMap[usedV.Timestamp]; !ok { // no need to double add, since we'll range over sorted timestamps and check.
  774. timestamps = append(timestamps, usedV.Timestamp)
  775. }
  776. }
  777. sort.Float64s(timestamps)
  778. for _, t := range timestamps {
  779. rv, okR := reqMap[t]
  780. uv, okU := usedMap[t]
  781. allocationVector := &Vector{
  782. Timestamp: t,
  783. }
  784. if okR && okU {
  785. allocationVector.Value = math.Max(rv, uv)
  786. } else if okR {
  787. allocationVector.Value = rv
  788. } else if okU {
  789. allocationVector.Value = uv
  790. }
  791. allocation = append(allocation, allocationVector)
  792. }
  793. return allocation
  794. }
  795. func addPVData(cache ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  796. cfg, err := cloud.GetConfig()
  797. if err != nil {
  798. return err
  799. }
  800. storageClasses := cache.GetAllStorageClasses()
  801. storageClassMap := make(map[string]map[string]string)
  802. for _, storageClass := range storageClasses {
  803. params := storageClass.Parameters
  804. storageClassMap[storageClass.ObjectMeta.Name] = params
  805. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  806. storageClassMap["default"] = params
  807. storageClassMap[""] = params
  808. }
  809. }
  810. pvs := cache.GetAllPersistentVolumes()
  811. pvMap := make(map[string]*costAnalyzerCloud.PV)
  812. for _, pv := range pvs {
  813. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  814. if !ok {
  815. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  816. }
  817. cacPv := &costAnalyzerCloud.PV{
  818. Class: pv.Spec.StorageClassName,
  819. Region: pv.Labels[v1.LabelZoneRegion],
  820. Parameters: parameters,
  821. }
  822. err := GetPVCost(cacPv, pv, cloud)
  823. if err != nil {
  824. return err
  825. }
  826. pvMap[pv.Name] = cacPv
  827. }
  828. for _, pvc := range pvClaimMapping {
  829. if vol, ok := pvMap[pvc.VolumeName]; ok {
  830. pvc.Volume = vol
  831. } else {
  832. klog.V(1).Infof("PV not found, using default")
  833. pvc.Volume = &costAnalyzerCloud.PV{
  834. Cost: cfg.Storage,
  835. }
  836. }
  837. }
  838. return nil
  839. }
  840. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cloud costAnalyzerCloud.Provider) error {
  841. cfg, err := cloud.GetConfig()
  842. if err != nil {
  843. return err
  844. }
  845. key := cloud.GetPVKey(kpv, pv.Parameters)
  846. pvWithCost, err := cloud.PVPricing(key)
  847. if err != nil {
  848. pv.Cost = cfg.Storage
  849. return err
  850. }
  851. if pvWithCost == nil || pvWithCost.Cost == "" {
  852. pv.Cost = cfg.Storage
  853. return nil // set default cost
  854. }
  855. pv.Cost = pvWithCost.Cost
  856. return nil
  857. }
  858. func getNodeCost(cache ClusterCache, cloud costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  859. cfg, err := cloud.GetConfig()
  860. if err != nil {
  861. return nil, err
  862. }
  863. nodeList := cache.GetAllNodes()
  864. nodes := make(map[string]*costAnalyzerCloud.Node)
  865. for _, n := range nodeList {
  866. name := n.GetObjectMeta().GetName()
  867. nodeLabels := n.GetObjectMeta().GetLabels()
  868. nodeLabels["providerID"] = n.Spec.ProviderID
  869. cnode, err := cloud.NodePricing(cloud.GetKey(nodeLabels))
  870. if err != nil {
  871. klog.V(1).Infof("Error getting node. Error: " + err.Error())
  872. nodes[name] = cnode
  873. continue
  874. }
  875. newCnode := *cnode
  876. var cpu float64
  877. if newCnode.VCPU == "" {
  878. cpu = float64(n.Status.Capacity.Cpu().Value())
  879. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  880. } else {
  881. cpu, _ = strconv.ParseFloat(newCnode.VCPU, 64)
  882. }
  883. var ram float64
  884. if newCnode.RAM == "" {
  885. newCnode.RAM = n.Status.Capacity.Memory().String()
  886. }
  887. ram = float64(n.Status.Capacity.Memory().Value())
  888. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  889. if newCnode.GPU != "" && newCnode.GPUCost == "" { // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  890. klog.V(4).Infof("GPU without cost found for %s, calculating...", cloud.GetKey(nodeLabels).Features())
  891. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  892. if err != nil {
  893. klog.V(3).Infof("Could not parse default cpu price")
  894. return nil, err
  895. }
  896. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  897. if err != nil {
  898. klog.V(3).Infof("Could not parse default ram price")
  899. return nil, err
  900. }
  901. defaultGPU, err := strconv.ParseFloat(cfg.RAM, 64)
  902. if err != nil {
  903. klog.V(3).Infof("Could not parse default gpu price")
  904. return nil, err
  905. }
  906. cpuToRAMRatio := defaultCPU / defaultRAM
  907. gpuToRAMRatio := defaultGPU / defaultRAM
  908. ramGB := ram / 1024 / 1024 / 1024
  909. ramMultiple := gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  910. var nodePrice float64
  911. if newCnode.Cost != "" {
  912. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  913. if err != nil {
  914. klog.V(3).Infof("Could not parse total node price")
  915. return nil, err
  916. }
  917. } else {
  918. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  919. if err != nil {
  920. klog.V(3).Infof("Could not parse node vcpu price")
  921. return nil, err
  922. }
  923. }
  924. ramPrice := (nodePrice / ramMultiple)
  925. cpuPrice := ramPrice * cpuToRAMRatio
  926. gpuPrice := ramPrice * gpuToRAMRatio
  927. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  928. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  929. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  930. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  931. } else {
  932. if newCnode.RAMCost == "" { // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  933. klog.V(4).Infof("No RAM cost found for %s, calculating...", cloud.GetKey(nodeLabels).Features())
  934. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  935. if err != nil {
  936. klog.V(3).Infof("Could not parse default cpu price")
  937. return nil, err
  938. }
  939. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  940. if err != nil {
  941. klog.V(3).Infof("Could not parse default ram price")
  942. return nil, err
  943. }
  944. cpuToRAMRatio := defaultCPU / defaultRAM
  945. ramGB := ram / 1024 / 1024 / 1024
  946. ramMultiple := cpu*cpuToRAMRatio + ramGB
  947. var nodePrice float64
  948. if newCnode.Cost != "" {
  949. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  950. if err != nil {
  951. klog.V(3).Infof("Could not parse total node price")
  952. return nil, err
  953. }
  954. } else {
  955. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  956. if err != nil {
  957. klog.V(3).Infof("Could not parse node vcpu price")
  958. return nil, err
  959. }
  960. }
  961. ramPrice := (nodePrice / ramMultiple)
  962. cpuPrice := ramPrice * cpuToRAMRatio
  963. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  964. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  965. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  966. klog.V(4).Infof("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  967. }
  968. }
  969. nodes[name] = &newCnode
  970. }
  971. return nodes, nil
  972. }
  973. func getPodServices(cache ClusterCache, podList []*v1.Pod) (map[string]map[string][]string, error) {
  974. servicesList := cache.GetAllServices()
  975. podServicesMapping := make(map[string]map[string][]string)
  976. for _, service := range servicesList {
  977. namespace := service.GetObjectMeta().GetNamespace()
  978. name := service.GetObjectMeta().GetName()
  979. if _, ok := podServicesMapping[namespace]; !ok {
  980. podServicesMapping[namespace] = make(map[string][]string)
  981. }
  982. s := labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  983. for _, pod := range podList {
  984. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  985. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  986. services, ok := podServicesMapping[namespace][pod.GetObjectMeta().GetName()]
  987. if ok {
  988. podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = append(services, name)
  989. } else {
  990. podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
  991. }
  992. }
  993. }
  994. }
  995. return podServicesMapping, nil
  996. }
  997. func getPodDeployments(cache ClusterCache, podList []*v1.Pod) (map[string]map[string][]string, error) {
  998. deploymentsList := cache.GetAllDeployments()
  999. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1000. for _, deployment := range deploymentsList {
  1001. namespace := deployment.GetObjectMeta().GetNamespace()
  1002. name := deployment.GetObjectMeta().GetName()
  1003. if _, ok := podDeploymentsMapping[namespace]; !ok {
  1004. podDeploymentsMapping[namespace] = make(map[string][]string)
  1005. }
  1006. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1007. if err != nil {
  1008. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  1009. }
  1010. for _, pod := range podList {
  1011. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1012. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1013. deployments, ok := podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()]
  1014. if ok {
  1015. podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1016. } else {
  1017. podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
  1018. }
  1019. }
  1020. }
  1021. }
  1022. return podDeploymentsMapping, nil
  1023. }
  1024. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider,
  1025. startString, endString, windowString string, filterNamespace string) (map[string]*CostData, error) {
  1026. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, windowString, "", windowString, "")
  1027. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, windowString, "", windowString, "")
  1028. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, windowString, "", windowString, "")
  1029. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, windowString, "")
  1030. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, windowString, "", windowString, "")
  1031. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  1032. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, windowString, "")
  1033. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, windowString, "")
  1034. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, windowString, "")
  1035. normalization := fmt.Sprintf(normalizationStr, windowString, "")
  1036. layout := "2006-01-02T15:04:05.000Z"
  1037. start, err := time.Parse(layout, startString)
  1038. if err != nil {
  1039. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1040. return nil, err
  1041. }
  1042. end, err := time.Parse(layout, endString)
  1043. if err != nil {
  1044. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1045. return nil, err
  1046. }
  1047. window, err := time.ParseDuration(windowString)
  1048. if err != nil {
  1049. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1050. return nil, err
  1051. }
  1052. clustID := os.Getenv(CLUSTER_ID)
  1053. remoteEnabled := os.Getenv(remoteEnabled)
  1054. if remoteEnabled == "true" {
  1055. remoteLayout := "2006-01-02T15:04:05Z"
  1056. remoteStartStr := start.Format(remoteLayout)
  1057. remoteEndStr := end.Format(remoteLayout)
  1058. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  1059. return CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  1060. }
  1061. var wg sync.WaitGroup
  1062. wg.Add(11)
  1063. var promErr error
  1064. var resultRAMRequests interface{}
  1065. go func() {
  1066. resultRAMRequests, promErr = QueryRange(cli, queryRAMRequests, start, end, window)
  1067. defer wg.Done()
  1068. }()
  1069. var resultRAMUsage interface{}
  1070. go func() {
  1071. resultRAMUsage, promErr = QueryRange(cli, queryRAMUsage, start, end, window)
  1072. defer wg.Done()
  1073. }()
  1074. var resultCPURequests interface{}
  1075. go func() {
  1076. resultCPURequests, promErr = QueryRange(cli, queryCPURequests, start, end, window)
  1077. defer wg.Done()
  1078. }()
  1079. var resultCPUUsage interface{}
  1080. go func() {
  1081. resultCPUUsage, promErr = QueryRange(cli, queryCPUUsage, start, end, window)
  1082. defer wg.Done()
  1083. }()
  1084. var resultGPURequests interface{}
  1085. go func() {
  1086. resultGPURequests, promErr = QueryRange(cli, queryGPURequests, start, end, window)
  1087. defer wg.Done()
  1088. }()
  1089. var resultPVRequests interface{}
  1090. go func() {
  1091. resultPVRequests, promErr = QueryRange(cli, queryPVRequests, start, end, window)
  1092. defer wg.Done()
  1093. }()
  1094. var resultNetZoneRequests interface{}
  1095. go func() {
  1096. resultNetZoneRequests, promErr = QueryRange(cli, queryNetZoneRequests, start, end, window)
  1097. defer wg.Done()
  1098. }()
  1099. var resultNetRegionRequests interface{}
  1100. go func() {
  1101. resultNetRegionRequests, promErr = QueryRange(cli, queryNetRegionRequests, start, end, window)
  1102. defer wg.Done()
  1103. }()
  1104. var resultNetInternetRequests interface{}
  1105. go func() {
  1106. resultNetInternetRequests, promErr = QueryRange(cli, queryNetInternetRequests, start, end, window)
  1107. defer wg.Done()
  1108. }()
  1109. var normalizationResult interface{}
  1110. go func() {
  1111. normalizationResult, promErr = Query(cli, normalization)
  1112. defer wg.Done()
  1113. }()
  1114. podDeploymentsMapping := make(map[string]map[string][]string)
  1115. podServicesMapping := make(map[string]map[string][]string)
  1116. namespaceLabelsMapping := make(map[string]map[string]string)
  1117. podlist := cm.Cache.GetAllPods()
  1118. var k8sErr error
  1119. go func() {
  1120. podDeploymentsMapping, k8sErr = getPodDeployments(cm.Cache, podlist)
  1121. if k8sErr != nil {
  1122. return
  1123. }
  1124. podServicesMapping, k8sErr = getPodServices(cm.Cache, podlist)
  1125. if k8sErr != nil {
  1126. return
  1127. }
  1128. namespaceLabelsMapping, k8sErr = getNamespaceLabels(cm.Cache)
  1129. if k8sErr != nil {
  1130. return
  1131. }
  1132. wg.Done()
  1133. }()
  1134. wg.Wait()
  1135. if promErr != nil {
  1136. return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  1137. }
  1138. if k8sErr != nil {
  1139. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  1140. }
  1141. normalizationValue, err := getNormalization(normalizationResult)
  1142. if err != nil {
  1143. return nil, fmt.Errorf("Error parsing normalization values: " + err.Error())
  1144. }
  1145. nodes, err := getNodeCost(cm.Cache, cloud)
  1146. if err != nil {
  1147. klog.V(1).Infof("Warning, no cost model available: " + err.Error())
  1148. return nil, err
  1149. }
  1150. pvClaimMapping, err := getPVInfoVectors(resultPVRequests)
  1151. if err != nil {
  1152. // Just log for compatibility with KSM less than 1.6
  1153. klog.Infof("Unable to get PV Data: %s", err.Error())
  1154. }
  1155. if pvClaimMapping != nil {
  1156. err = addPVData(cm.Cache, pvClaimMapping, cloud)
  1157. if err != nil {
  1158. return nil, err
  1159. }
  1160. }
  1161. networkUsageMap, err := GetNetworkUsageData(resultNetZoneRequests, resultNetRegionRequests, resultNetInternetRequests, true)
  1162. if err != nil {
  1163. klog.V(1).Infof("Unable to get Network Cost Data: %s", err.Error())
  1164. networkUsageMap = make(map[string]*NetworkUsageData)
  1165. }
  1166. containerNameCost := make(map[string]*CostData)
  1167. containers := make(map[string]bool)
  1168. RAMReqMap, err := GetContainerMetricVectors(resultRAMRequests, true, normalizationValue)
  1169. if err != nil {
  1170. return nil, err
  1171. }
  1172. for key := range RAMReqMap {
  1173. containers[key] = true
  1174. }
  1175. RAMUsedMap, err := GetContainerMetricVectors(resultRAMUsage, true, normalizationValue)
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. for key := range RAMUsedMap {
  1180. containers[key] = true
  1181. }
  1182. CPUReqMap, err := GetContainerMetricVectors(resultCPURequests, true, normalizationValue)
  1183. if err != nil {
  1184. return nil, err
  1185. }
  1186. for key := range CPUReqMap {
  1187. containers[key] = true
  1188. }
  1189. GPUReqMap, err := GetContainerMetricVectors(resultGPURequests, true, normalizationValue)
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. for key := range GPUReqMap {
  1194. containers[key] = true
  1195. }
  1196. CPUUsedMap, err := GetContainerMetricVectors(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
  1197. if err != nil {
  1198. return nil, err
  1199. }
  1200. for key := range CPUUsedMap {
  1201. containers[key] = true
  1202. }
  1203. currentContainers := make(map[string]v1.Pod)
  1204. for _, pod := range podlist {
  1205. if pod.Status.Phase != v1.PodRunning {
  1206. continue
  1207. }
  1208. cs, err := newContainerMetricsFromPod(*pod)
  1209. if err != nil {
  1210. return nil, err
  1211. }
  1212. for _, c := range cs {
  1213. 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.
  1214. currentContainers[c.Key()] = *pod
  1215. }
  1216. }
  1217. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1218. missingContainers := make(map[string]*CostData)
  1219. for key := range containers {
  1220. if _, ok := containerNameCost[key]; ok {
  1221. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1222. }
  1223. if pod, ok := currentContainers[key]; ok {
  1224. podName := pod.GetObjectMeta().GetName()
  1225. ns := pod.GetObjectMeta().GetNamespace()
  1226. nodeName := pod.Spec.NodeName
  1227. var nodeData *costAnalyzerCloud.Node
  1228. if _, ok := nodes[nodeName]; ok {
  1229. nodeData = nodes[nodeName]
  1230. }
  1231. var podDeployments []string
  1232. if _, ok := podDeploymentsMapping[ns]; ok {
  1233. if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  1234. podDeployments = ds
  1235. } else {
  1236. podDeployments = []string{}
  1237. }
  1238. }
  1239. var podPVs []*PersistentVolumeClaimData
  1240. podClaims := pod.Spec.Volumes
  1241. for _, vol := range podClaims {
  1242. if vol.PersistentVolumeClaim != nil {
  1243. name := vol.PersistentVolumeClaim.ClaimName
  1244. if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
  1245. podPVs = append(podPVs, pvClaim)
  1246. }
  1247. }
  1248. }
  1249. var podNetCosts []*Vector
  1250. if usage, ok := networkUsageMap[ns+","+podName]; ok {
  1251. netCosts, err := GetNetworkCost(usage, cloud)
  1252. if err != nil {
  1253. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  1254. } else {
  1255. podNetCosts = netCosts
  1256. }
  1257. }
  1258. var podServices []string
  1259. if _, ok := podServicesMapping[ns]; ok {
  1260. if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  1261. podServices = svcs
  1262. } else {
  1263. podServices = []string{}
  1264. }
  1265. }
  1266. nsLabels := namespaceLabelsMapping[ns]
  1267. podLabels := pod.GetObjectMeta().GetLabels()
  1268. if podLabels == nil {
  1269. podLabels = make(map[string]string)
  1270. }
  1271. for k, v := range nsLabels {
  1272. if _, ok := podLabels[k]; !ok {
  1273. podLabels[k] = v
  1274. }
  1275. }
  1276. for i, container := range pod.Spec.Containers {
  1277. containerName := container.Name
  1278. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName).Key()
  1279. RAMReqV, ok := RAMReqMap[newKey]
  1280. if !ok {
  1281. klog.V(4).Info("no RAM requests for " + newKey)
  1282. RAMReqV = []*Vector{}
  1283. }
  1284. RAMUsedV, ok := RAMUsedMap[newKey]
  1285. if !ok {
  1286. klog.V(4).Info("no RAM usage for " + newKey)
  1287. RAMUsedV = []*Vector{}
  1288. }
  1289. CPUReqV, ok := CPUReqMap[newKey]
  1290. if !ok {
  1291. klog.V(4).Info("no CPU requests for " + newKey)
  1292. CPUReqV = []*Vector{}
  1293. }
  1294. GPUReqV, ok := GPUReqMap[newKey]
  1295. if !ok {
  1296. klog.V(4).Info("no GPU requests for " + newKey)
  1297. GPUReqV = []*Vector{}
  1298. }
  1299. CPUUsedV, ok := CPUUsedMap[newKey]
  1300. if !ok {
  1301. klog.V(4).Info("no CPU usage for " + newKey)
  1302. CPUUsedV = []*Vector{}
  1303. }
  1304. var pvReq []*PersistentVolumeClaimData
  1305. var netReq []*Vector
  1306. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  1307. pvReq = podPVs
  1308. netReq = podNetCosts
  1309. }
  1310. costs := &CostData{
  1311. Name: containerName,
  1312. PodName: podName,
  1313. NodeName: nodeName,
  1314. Namespace: ns,
  1315. Deployments: podDeployments,
  1316. Services: podServices,
  1317. Daemonsets: getDaemonsetsOfPod(pod),
  1318. Jobs: getJobsOfPod(pod),
  1319. Statefulsets: getStatefulSetsOfPod(pod),
  1320. NodeData: nodeData,
  1321. RAMReq: RAMReqV,
  1322. RAMUsed: RAMUsedV,
  1323. CPUReq: CPUReqV,
  1324. CPUUsed: CPUUsedV,
  1325. GPUReq: GPUReqV,
  1326. PVCData: pvReq,
  1327. Labels: podLabels,
  1328. NetworkData: netReq,
  1329. NamespaceLabels: nsLabels,
  1330. ClusterID: clustID,
  1331. }
  1332. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  1333. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  1334. if filterNamespace == "" {
  1335. containerNameCost[newKey] = costs
  1336. } else if costs.Namespace == filterNamespace {
  1337. containerNameCost[newKey] = costs
  1338. }
  1339. }
  1340. } else {
  1341. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  1342. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  1343. c, _ := NewContainerMetricFromKey(key)
  1344. RAMReqV, ok := RAMReqMap[key]
  1345. if !ok {
  1346. klog.V(4).Info("no RAM requests for " + key)
  1347. RAMReqV = []*Vector{}
  1348. }
  1349. RAMUsedV, ok := RAMUsedMap[key]
  1350. if !ok {
  1351. klog.V(4).Info("no RAM usage for " + key)
  1352. RAMUsedV = []*Vector{}
  1353. }
  1354. CPUReqV, ok := CPUReqMap[key]
  1355. if !ok {
  1356. klog.V(4).Info("no CPU requests for " + key)
  1357. CPUReqV = []*Vector{}
  1358. }
  1359. GPUReqV, ok := GPUReqMap[key]
  1360. if !ok {
  1361. klog.V(4).Info("no GPU requests for " + key)
  1362. GPUReqV = []*Vector{}
  1363. }
  1364. CPUUsedV, ok := CPUUsedMap[key]
  1365. if !ok {
  1366. klog.V(4).Info("no CPU usage for " + key)
  1367. CPUUsedV = []*Vector{}
  1368. }
  1369. node, ok := nodes[c.NodeName]
  1370. if !ok {
  1371. klog.V(2).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  1372. if n, ok := missingNodes[c.NodeName]; ok {
  1373. node = n
  1374. } else {
  1375. node = &costAnalyzerCloud.Node{}
  1376. missingNodes[c.NodeName] = node
  1377. }
  1378. }
  1379. namespacelabels, ok := namespaceLabelsMapping[c.Namespace]
  1380. if !ok {
  1381. klog.V(3).Infof("Missing data for namespace %s", c.Namespace)
  1382. }
  1383. costs := &CostData{
  1384. Name: c.ContainerName,
  1385. PodName: c.PodName,
  1386. NodeName: c.NodeName,
  1387. NodeData: node,
  1388. Namespace: c.Namespace,
  1389. RAMReq: RAMReqV,
  1390. RAMUsed: RAMUsedV,
  1391. CPUReq: CPUReqV,
  1392. CPUUsed: CPUUsedV,
  1393. GPUReq: GPUReqV,
  1394. NamespaceLabels: namespacelabels,
  1395. ClusterID: clustID,
  1396. }
  1397. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  1398. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  1399. if filterNamespace == "" {
  1400. containerNameCost[key] = costs
  1401. missingContainers[key] = costs
  1402. } else if costs.Namespace == filterNamespace {
  1403. containerNameCost[key] = costs
  1404. missingContainers[key] = costs
  1405. }
  1406. }
  1407. }
  1408. w := end.Sub(start)
  1409. w += window
  1410. if w.Minutes() > 0 {
  1411. wStr := fmt.Sprintf("%dm", int(w.Minutes()))
  1412. err = findDeletedNodeInfo(cli, missingNodes, wStr)
  1413. if err != nil {
  1414. return nil, err
  1415. }
  1416. klog.Infof("Finding deleted pod info from range query:")
  1417. err = findDeletedPodInfo(cli, missingContainers, wStr)
  1418. if err != nil {
  1419. return nil, err
  1420. }
  1421. }
  1422. return containerNameCost, err
  1423. }
  1424. func getNamespaceLabels(cache ClusterCache) (map[string]map[string]string, error) {
  1425. nsToLabels := make(map[string]map[string]string)
  1426. nss := cache.GetAllNamespaces()
  1427. for _, ns := range nss {
  1428. nsToLabels[ns.Name] = ns.Labels
  1429. }
  1430. return nsToLabels, nil
  1431. }
  1432. func getDaemonsetsOfPod(pod v1.Pod) []string {
  1433. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1434. if ownerReference.Kind == "DaemonSet" {
  1435. return []string{ownerReference.Name}
  1436. }
  1437. }
  1438. return []string{}
  1439. }
  1440. func getJobsOfPod(pod v1.Pod) []string {
  1441. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1442. if ownerReference.Kind == "Job" {
  1443. return []string{ownerReference.Name}
  1444. }
  1445. }
  1446. return []string{}
  1447. }
  1448. func getStatefulSetsOfPod(pod v1.Pod) []string {
  1449. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1450. if ownerReference.Kind == "StatefulSet" {
  1451. return []string{ownerReference.Name}
  1452. }
  1453. }
  1454. return []string{}
  1455. }
  1456. type PersistentVolumeClaimData struct {
  1457. Class string `json:"class"`
  1458. Claim string `json:"claim"`
  1459. Namespace string `json:"namespace"`
  1460. VolumeName string `json:"volumeName"`
  1461. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  1462. Values []*Vector `json:"values"`
  1463. }
  1464. func getCost(qr interface{}) (map[string][]*Vector, error) {
  1465. toReturn := make(map[string][]*Vector)
  1466. for _, val := range qr.(map[string]interface{})["data"].(map[string]interface{})["result"].([]interface{}) {
  1467. metricInterface, ok := val.(map[string]interface{})["metric"]
  1468. if !ok {
  1469. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1470. }
  1471. metricMap, ok := metricInterface.(map[string]interface{})
  1472. if !ok {
  1473. return nil, fmt.Errorf("Metric field is improperly formatted")
  1474. }
  1475. instance, ok := metricMap["instance"]
  1476. if !ok {
  1477. return nil, fmt.Errorf("Instance field does not exist in data result vector")
  1478. }
  1479. instanceStr, ok := instance.(string)
  1480. if !ok {
  1481. return nil, fmt.Errorf("Instance is improperly formatted")
  1482. }
  1483. dataPoint, ok := val.(map[string]interface{})["value"]
  1484. if !ok {
  1485. return nil, fmt.Errorf("Value field does not exist in data result vector")
  1486. }
  1487. value, ok := dataPoint.([]interface{})
  1488. if !ok || len(value) != 2 {
  1489. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1490. }
  1491. var vectors []*Vector
  1492. strVal := value[1].(string)
  1493. v, _ := strconv.ParseFloat(strVal, 64)
  1494. vectors = append(vectors, &Vector{
  1495. Timestamp: value[0].(float64),
  1496. Value: v,
  1497. })
  1498. toReturn[instanceStr] = vectors
  1499. }
  1500. return toReturn, nil
  1501. }
  1502. func getPVInfoVectors(qr interface{}) (map[string]*PersistentVolumeClaimData, error) {
  1503. pvmap := make(map[string]*PersistentVolumeClaimData)
  1504. data, ok := qr.(map[string]interface{})["data"]
  1505. if !ok {
  1506. e, err := wrapPrometheusError(qr)
  1507. if err != nil {
  1508. return nil, err
  1509. }
  1510. return nil, fmt.Errorf(e)
  1511. }
  1512. d, ok := data.(map[string]interface{})
  1513. if !ok {
  1514. return nil, fmt.Errorf("Data field improperly formatted in prometheus repsonse")
  1515. }
  1516. result, ok := d["result"]
  1517. if !ok {
  1518. return nil, fmt.Errorf("Result field not present in prometheus response")
  1519. }
  1520. results, ok := result.([]interface{})
  1521. if !ok {
  1522. return nil, fmt.Errorf("Result field improperly formatted in prometheus response")
  1523. }
  1524. for _, val := range results {
  1525. metricInterface, ok := val.(map[string]interface{})["metric"]
  1526. if !ok {
  1527. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1528. }
  1529. metricMap, ok := metricInterface.(map[string]interface{})
  1530. if !ok {
  1531. return nil, fmt.Errorf("Metric field is improperly formatted")
  1532. }
  1533. pvclaim, ok := metricMap["persistentvolumeclaim"]
  1534. if !ok {
  1535. return nil, fmt.Errorf("Claim field does not exist in data result vector")
  1536. }
  1537. pvclaimStr, ok := pvclaim.(string)
  1538. if !ok {
  1539. return nil, fmt.Errorf("Claim field improperly formatted")
  1540. }
  1541. pvnamespace, ok := metricMap["namespace"]
  1542. if !ok {
  1543. return nil, fmt.Errorf("Namespace field does not exist in data result vector")
  1544. }
  1545. pvnamespaceStr, ok := pvnamespace.(string)
  1546. if !ok {
  1547. return nil, fmt.Errorf("Namespace field improperly formatted")
  1548. }
  1549. pv, ok := metricMap["volumename"]
  1550. if !ok {
  1551. klog.V(3).Infof("Warning: Unfulfilled claim %s: volumename field does not exist in data result vector", pvclaimStr)
  1552. pv = ""
  1553. }
  1554. pvStr, ok := pv.(string)
  1555. if !ok {
  1556. return nil, fmt.Errorf("Volumename field improperly formatted")
  1557. }
  1558. pvclass, ok := metricMap["storageclass"]
  1559. if !ok { // TODO: We need to look up the actual PV and PV capacity. For now just proceed with "".
  1560. klog.V(2).Infof("Storage Class not found for claim \"%s/%s\".", pvnamespaceStr, pvclaimStr)
  1561. pvclass = ""
  1562. }
  1563. pvclassStr, ok := pvclass.(string)
  1564. if !ok {
  1565. return nil, fmt.Errorf("StorageClass field improperly formatted")
  1566. }
  1567. values, ok := val.(map[string]interface{})["values"].([]interface{})
  1568. if !ok {
  1569. return nil, fmt.Errorf("Values field is improperly formatted")
  1570. }
  1571. var vectors []*Vector
  1572. for _, value := range values {
  1573. dataPoint, ok := value.([]interface{})
  1574. if !ok || len(dataPoint) != 2 {
  1575. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1576. }
  1577. strVal := dataPoint[1].(string)
  1578. v, _ := strconv.ParseFloat(strVal, 64)
  1579. vectors = append(vectors, &Vector{
  1580. Timestamp: math.Round(dataPoint[0].(float64)/10) * 10,
  1581. Value: v,
  1582. })
  1583. }
  1584. key := pvnamespaceStr + "," + pvclaimStr
  1585. pvmap[key] = &PersistentVolumeClaimData{
  1586. Class: pvclassStr,
  1587. Claim: pvclaimStr,
  1588. Namespace: pvnamespaceStr,
  1589. VolumeName: pvStr,
  1590. Values: vectors,
  1591. }
  1592. }
  1593. return pvmap, nil
  1594. }
  1595. func getPVInfoVector(qr interface{}) (map[string]*PersistentVolumeClaimData, error) {
  1596. pvmap := make(map[string]*PersistentVolumeClaimData)
  1597. data, ok := qr.(map[string]interface{})["data"]
  1598. if !ok {
  1599. e, err := wrapPrometheusError(qr)
  1600. if err != nil {
  1601. return nil, err
  1602. }
  1603. return nil, fmt.Errorf(e)
  1604. }
  1605. d, ok := data.(map[string]interface{})
  1606. if !ok {
  1607. return nil, fmt.Errorf("Data field improperly formatted in prometheus repsonse")
  1608. }
  1609. result, ok := d["result"]
  1610. if !ok {
  1611. return nil, fmt.Errorf("Result field not present in prometheus response")
  1612. }
  1613. results, ok := result.([]interface{})
  1614. if !ok {
  1615. return nil, fmt.Errorf("Result field improperly formatted in prometheus response")
  1616. }
  1617. for _, val := range results {
  1618. metricInterface, ok := val.(map[string]interface{})["metric"]
  1619. if !ok {
  1620. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1621. }
  1622. metricMap, ok := metricInterface.(map[string]interface{})
  1623. if !ok {
  1624. return nil, fmt.Errorf("Metric field is improperly formatted")
  1625. }
  1626. pvclaim, ok := metricMap["persistentvolumeclaim"]
  1627. if !ok {
  1628. return nil, fmt.Errorf("Claim field does not exist in data result vector")
  1629. }
  1630. pvclaimStr, ok := pvclaim.(string)
  1631. if !ok {
  1632. return nil, fmt.Errorf("Claim field improperly formatted")
  1633. }
  1634. pvnamespace, ok := metricMap["namespace"]
  1635. if !ok {
  1636. return nil, fmt.Errorf("Namespace field does not exist in data result vector")
  1637. }
  1638. pvnamespaceStr, ok := pvnamespace.(string)
  1639. if !ok {
  1640. return nil, fmt.Errorf("Namespace field improperly formatted")
  1641. }
  1642. pv, ok := metricMap["volumename"]
  1643. if !ok {
  1644. klog.V(3).Infof("Warning: Unfulfilled claim %s: volumename field does not exist in data result vector", pvclaimStr)
  1645. pv = ""
  1646. }
  1647. pvStr, ok := pv.(string)
  1648. if !ok {
  1649. return nil, fmt.Errorf("Volumename field improperly formatted")
  1650. }
  1651. pvclass, ok := metricMap["storageclass"]
  1652. if !ok { // TODO: We need to look up the actual PV and PV capacity. For now just proceed with "".
  1653. klog.V(2).Infof("Storage Class not found for claim \"%s/%s\".", pvnamespaceStr, pvclaimStr)
  1654. pvclass = ""
  1655. }
  1656. pvclassStr, ok := pvclass.(string)
  1657. if !ok {
  1658. return nil, fmt.Errorf("StorageClass field improperly formatted")
  1659. }
  1660. dataPoint, ok := val.(map[string]interface{})["value"]
  1661. if !ok {
  1662. return nil, fmt.Errorf("Value field does not exist in data result vector")
  1663. }
  1664. value, ok := dataPoint.([]interface{})
  1665. if !ok || len(value) != 2 {
  1666. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1667. }
  1668. var vectors []*Vector
  1669. strVal := value[1].(string)
  1670. v, _ := strconv.ParseFloat(strVal, 64)
  1671. vectors = append(vectors, &Vector{
  1672. Timestamp: value[0].(float64),
  1673. Value: v,
  1674. })
  1675. key := pvnamespaceStr + "," + pvclaimStr
  1676. pvmap[key] = &PersistentVolumeClaimData{
  1677. Class: pvclassStr,
  1678. Claim: pvclaimStr,
  1679. Namespace: pvnamespaceStr,
  1680. VolumeName: pvStr,
  1681. Values: vectors,
  1682. }
  1683. }
  1684. return pvmap, nil
  1685. }
  1686. func QueryRange(cli prometheusClient.Client, query string, start, end time.Time, step time.Duration) (interface{}, error) {
  1687. u := cli.URL(epQueryRange, nil)
  1688. q := u.Query()
  1689. q.Set("query", query)
  1690. q.Set("start", start.Format(time.RFC3339Nano))
  1691. q.Set("end", end.Format(time.RFC3339Nano))
  1692. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  1693. u.RawQuery = q.Encode()
  1694. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  1695. if err != nil {
  1696. return nil, err
  1697. }
  1698. _, body, _, err := cli.Do(context.Background(), req)
  1699. if err != nil {
  1700. klog.V(1).Infof("ERROR" + err.Error())
  1701. }
  1702. if err != nil {
  1703. return nil, err
  1704. }
  1705. var toReturn interface{}
  1706. err = json.Unmarshal(body, &toReturn)
  1707. if err != nil {
  1708. klog.V(1).Infof("ERROR" + err.Error())
  1709. }
  1710. return toReturn, err
  1711. }
  1712. func Query(cli prometheusClient.Client, query string) (interface{}, error) {
  1713. u := cli.URL(epQuery, nil)
  1714. q := u.Query()
  1715. q.Set("query", query)
  1716. u.RawQuery = q.Encode()
  1717. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  1718. if err != nil {
  1719. return nil, err
  1720. }
  1721. _, body, _, err := cli.Do(context.Background(), req)
  1722. if err != nil {
  1723. return nil, err
  1724. }
  1725. var toReturn interface{}
  1726. err = json.Unmarshal(body, &toReturn)
  1727. if err != nil {
  1728. klog.V(1).Infof("ERROR" + err.Error())
  1729. }
  1730. return toReturn, err
  1731. }
  1732. //todo: don't cast, implement unmarshaler interface
  1733. func getNormalization(qr interface{}) (float64, error) {
  1734. data, ok := qr.(map[string]interface{})["data"]
  1735. if !ok {
  1736. e, err := wrapPrometheusError(qr)
  1737. if err != nil {
  1738. return 0, err
  1739. }
  1740. return 0, fmt.Errorf(e)
  1741. }
  1742. results, ok := data.(map[string]interface{})["result"].([]interface{})
  1743. if !ok {
  1744. return 0, fmt.Errorf("Result field not found in normalization response, aborting")
  1745. }
  1746. if len(results) > 0 {
  1747. dataPoint := results[0].(map[string]interface{})["value"].([]interface{})
  1748. if len(dataPoint) == 2 {
  1749. strNorm := dataPoint[1].(string)
  1750. val, _ := strconv.ParseFloat(strNorm, 64)
  1751. return val, nil
  1752. }
  1753. return 0, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1754. }
  1755. return 0, fmt.Errorf("Normalization data is empty, kube-state-metrics or node-exporter may not be running")
  1756. }
  1757. type ContainerMetric struct {
  1758. Namespace string
  1759. PodName string
  1760. ContainerName string
  1761. NodeName string
  1762. }
  1763. func (c *ContainerMetric) Key() string {
  1764. return c.Namespace + "," + c.PodName + "," + c.ContainerName + "," + c.NodeName
  1765. }
  1766. func NewContainerMetricFromKey(key string) (*ContainerMetric, error) {
  1767. s := strings.Split(key, ",")
  1768. if len(s) == 4 {
  1769. return &ContainerMetric{
  1770. Namespace: s[0],
  1771. PodName: s[1],
  1772. ContainerName: s[2],
  1773. NodeName: s[3],
  1774. }, nil
  1775. }
  1776. return nil, fmt.Errorf("Not a valid key")
  1777. }
  1778. func newContainerMetricFromValues(ns string, podName string, containerName string, nodeName string) *ContainerMetric {
  1779. return &ContainerMetric{
  1780. Namespace: ns,
  1781. PodName: podName,
  1782. ContainerName: containerName,
  1783. NodeName: nodeName,
  1784. }
  1785. }
  1786. func newContainerMetricsFromPod(pod v1.Pod) ([]*ContainerMetric, error) {
  1787. podName := pod.GetObjectMeta().GetName()
  1788. ns := pod.GetObjectMeta().GetNamespace()
  1789. node := pod.Spec.NodeName
  1790. var cs []*ContainerMetric
  1791. for _, container := range pod.Spec.Containers {
  1792. containerName := container.Name
  1793. cs = append(cs, &ContainerMetric{
  1794. Namespace: ns,
  1795. PodName: podName,
  1796. ContainerName: containerName,
  1797. NodeName: node,
  1798. })
  1799. }
  1800. return cs, nil
  1801. }
  1802. func newContainerMetricFromPrometheus(metrics map[string]interface{}) (*ContainerMetric, error) {
  1803. cName, ok := metrics["container_name"]
  1804. if !ok {
  1805. return nil, fmt.Errorf("Prometheus vector does not have container name")
  1806. }
  1807. containerName, ok := cName.(string)
  1808. if !ok {
  1809. return nil, fmt.Errorf("Prometheus vector does not have string container name")
  1810. }
  1811. pName, ok := metrics["pod_name"]
  1812. if !ok {
  1813. return nil, fmt.Errorf("Prometheus vector does not have pod name")
  1814. }
  1815. podName, ok := pName.(string)
  1816. if !ok {
  1817. return nil, fmt.Errorf("Prometheus vector does not have string pod name")
  1818. }
  1819. ns, ok := metrics["namespace"]
  1820. if !ok {
  1821. return nil, fmt.Errorf("Prometheus vector does not have namespace")
  1822. }
  1823. namespace, ok := ns.(string)
  1824. if !ok {
  1825. return nil, fmt.Errorf("Prometheus vector does not have string namespace")
  1826. }
  1827. node, ok := metrics["node"]
  1828. if !ok {
  1829. klog.V(4).Info("Prometheus vector does not have node name")
  1830. node = ""
  1831. }
  1832. nodeName, ok := node.(string)
  1833. if !ok {
  1834. return nil, fmt.Errorf("Prometheus vector does not have string node")
  1835. }
  1836. return &ContainerMetric{
  1837. ContainerName: containerName,
  1838. PodName: podName,
  1839. Namespace: namespace,
  1840. NodeName: nodeName,
  1841. }, nil
  1842. }
  1843. func GetContainerMetricVector(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
  1844. data, ok := qr.(map[string]interface{})["data"]
  1845. if !ok {
  1846. e, err := wrapPrometheusError(qr)
  1847. if err != nil {
  1848. return nil, err
  1849. }
  1850. return nil, fmt.Errorf(e)
  1851. }
  1852. r, ok := data.(map[string]interface{})["result"]
  1853. if !ok {
  1854. return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  1855. }
  1856. results, ok := r.([]interface{})
  1857. if !ok {
  1858. return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  1859. }
  1860. containerData := make(map[string][]*Vector)
  1861. for _, val := range results {
  1862. metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  1863. if !ok {
  1864. return nil, fmt.Errorf("Prometheus vector does not have metric labels")
  1865. }
  1866. containerMetric, err := newContainerMetricFromPrometheus(metric)
  1867. if err != nil {
  1868. return nil, err
  1869. }
  1870. value, ok := val.(map[string]interface{})["value"]
  1871. if !ok {
  1872. return nil, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
  1873. }
  1874. dataPoint, ok := value.([]interface{})
  1875. if !ok || len(dataPoint) != 2 {
  1876. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1877. }
  1878. strVal := dataPoint[1].(string)
  1879. v, _ := strconv.ParseFloat(strVal, 64)
  1880. if normalize && normalizationValue != 0 {
  1881. v = v / normalizationValue
  1882. }
  1883. toReturn := &Vector{
  1884. Timestamp: dataPoint[0].(float64),
  1885. Value: v,
  1886. }
  1887. klog.V(4).Info("key: " + containerMetric.Key())
  1888. containerData[containerMetric.Key()] = []*Vector{toReturn}
  1889. }
  1890. return containerData, nil
  1891. }
  1892. func GetContainerMetricVectors(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
  1893. data, ok := qr.(map[string]interface{})["data"]
  1894. if !ok {
  1895. e, err := wrapPrometheusError(qr)
  1896. if err != nil {
  1897. return nil, err
  1898. }
  1899. return nil, fmt.Errorf(e)
  1900. }
  1901. r, ok := data.(map[string]interface{})["result"]
  1902. if !ok {
  1903. return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  1904. }
  1905. results, ok := r.([]interface{})
  1906. if !ok {
  1907. return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  1908. }
  1909. containerData := make(map[string][]*Vector)
  1910. for _, val := range results {
  1911. metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  1912. if !ok {
  1913. return nil, fmt.Errorf("Prometheus vector does not have metric labels")
  1914. }
  1915. containerMetric, err := newContainerMetricFromPrometheus(metric)
  1916. if err != nil {
  1917. return nil, err
  1918. }
  1919. vs, ok := val.(map[string]interface{})["values"]
  1920. if !ok {
  1921. return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a field in the vector")
  1922. }
  1923. values, ok := vs.([]interface{})
  1924. if !ok {
  1925. return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a slice")
  1926. }
  1927. var vectors []*Vector
  1928. for _, value := range values {
  1929. dataPoint, ok := value.([]interface{})
  1930. if !ok || len(dataPoint) != 2 {
  1931. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1932. }
  1933. strVal := dataPoint[1].(string)
  1934. v, _ := strconv.ParseFloat(strVal, 64)
  1935. if normalize && normalizationValue != 0 {
  1936. v = v / normalizationValue
  1937. }
  1938. vectors = append(vectors, &Vector{
  1939. Timestamp: math.Round(dataPoint[0].(float64)/10) * 10,
  1940. Value: v,
  1941. })
  1942. }
  1943. containerData[containerMetric.Key()] = vectors
  1944. }
  1945. return containerData, nil
  1946. }
  1947. func wrapPrometheusError(qr interface{}) (string, error) {
  1948. e, ok := qr.(map[string]interface{})["error"]
  1949. if !ok {
  1950. return "", fmt.Errorf("Unexpected response from Prometheus")
  1951. }
  1952. eStr, ok := e.(string)
  1953. return eStr, nil
  1954. }