costmodel.go 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  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. klog.V(1).Infof("Error fetching historical node data: %s", err.Error())
  604. }
  605. err = findDeletedPodInfo(cli, missingContainers, window)
  606. if err != nil {
  607. klog.V(1).Infof("Error fetching historical pod data: %s", err.Error())
  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. queryHistoricalPodLabels := fmt.Sprintf(`kube_pod_labels{}[%s]`, window)
  614. podLabelsResult, err := Query(cli, queryHistoricalPodLabels)
  615. if err != nil {
  616. klog.V(1).Infof("Error parsing historical labels: %s", err.Error())
  617. }
  618. podLabels := make(map[string]map[string]string)
  619. if podLabelsResult != nil {
  620. podLabels, err = labelsFromPrometheusQuery(podLabelsResult)
  621. if err != nil {
  622. klog.V(1).Infof("Error parsing historical labels: %s", err.Error())
  623. }
  624. }
  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. data, ok := qr.(map[string]interface{})["data"]
  645. if !ok {
  646. e, err := wrapPrometheusError(qr)
  647. if err != nil {
  648. return toReturn, err
  649. }
  650. return toReturn, fmt.Errorf(e)
  651. }
  652. for _, val := range data.(map[string]interface{})["result"].([]interface{}) {
  653. metricInterface, ok := val.(map[string]interface{})["metric"]
  654. if !ok {
  655. return toReturn, fmt.Errorf("Metric field does not exist in data result vector")
  656. }
  657. metricMap, ok := metricInterface.(map[string]interface{})
  658. if !ok {
  659. return toReturn, fmt.Errorf("Metric field is improperly formatted")
  660. }
  661. pod, ok := metricMap["pod"]
  662. if !ok {
  663. return toReturn, fmt.Errorf("pod field does not exist in data result vector")
  664. }
  665. podName, ok := pod.(string)
  666. if !ok {
  667. return toReturn, fmt.Errorf("pod field is improperly formatted")
  668. }
  669. for labelName, labelValue := range metricMap {
  670. parsedLabelName := labelName
  671. parsedLv, ok := labelValue.(string)
  672. if !ok {
  673. return toReturn, fmt.Errorf("label value is improperly formatted")
  674. }
  675. if strings.HasPrefix(parsedLabelName, "label_") {
  676. l := strings.Replace(parsedLabelName, "label_", "", 1)
  677. if podLabels, ok := toReturn[podName]; ok {
  678. podLabels[l] = parsedLv
  679. } else {
  680. toReturn[podName] = make(map[string]string)
  681. toReturn[podName][l] = parsedLv
  682. }
  683. }
  684. }
  685. }
  686. return toReturn, nil
  687. }
  688. func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window string) error {
  689. if len(missingNodes) > 0 {
  690. q := make([]string, 0, len(missingNodes))
  691. for nodename := range missingNodes {
  692. klog.V(3).Infof("Finding data for deleted node %v", nodename)
  693. q = append(q, nodename)
  694. }
  695. l := strings.Join(q, "|")
  696. queryHistoricalCPUCost := fmt.Sprintf(`avg_over_time(node_cpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  697. queryHistoricalRAMCost := fmt.Sprintf(`avg_over_time(node_ram_hourly_cost{instance=~"%s"}[%s])`, l, window)
  698. queryHistoricalGPUCost := fmt.Sprintf(`avg_over_time(node_gpu_hourly_cost{instance=~"%s"}[%s])`, l, window)
  699. cpuCostResult, err := Query(cli, queryHistoricalCPUCost)
  700. if err != nil {
  701. return fmt.Errorf("Error fetching cpu cost data: " + err.Error())
  702. }
  703. ramCostResult, err := Query(cli, queryHistoricalRAMCost)
  704. if err != nil {
  705. return fmt.Errorf("Error fetching ram cost data: " + err.Error())
  706. }
  707. gpuCostResult, err := Query(cli, queryHistoricalGPUCost)
  708. if err != nil {
  709. return fmt.Errorf("Error fetching gpu cost data: " + err.Error())
  710. }
  711. cpuCosts, err := getCost(cpuCostResult)
  712. if err != nil {
  713. return err
  714. }
  715. ramCosts, err := getCost(ramCostResult)
  716. if err != nil {
  717. return err
  718. }
  719. gpuCosts, err := getCost(gpuCostResult)
  720. if err != nil {
  721. return err
  722. }
  723. if len(cpuCosts) == 0 {
  724. klog.V(1).Infof("Historical data for node prices not available. Ingest this server's /metrics endpoint to get that data.")
  725. }
  726. for node, costv := range cpuCosts {
  727. if _, ok := missingNodes[node]; ok {
  728. missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
  729. }
  730. }
  731. for node, costv := range ramCosts {
  732. if _, ok := missingNodes[node]; ok {
  733. missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
  734. }
  735. }
  736. for node, costv := range gpuCosts {
  737. if _, ok := missingNodes[node]; ok {
  738. missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
  739. }
  740. }
  741. }
  742. return nil
  743. }
  744. func getContainerAllocation(req []*Vector, used []*Vector) []*Vector {
  745. if req == nil || len(req) == 0 {
  746. for _, usedV := range used {
  747. if usedV.Timestamp == 0 {
  748. continue
  749. }
  750. usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
  751. }
  752. return used
  753. }
  754. if used == nil || len(used) == 0 {
  755. for _, reqV := range req {
  756. if reqV.Timestamp == 0 {
  757. continue
  758. }
  759. reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
  760. }
  761. return req
  762. }
  763. var allocation []*Vector
  764. var timestamps []float64
  765. reqMap := make(map[float64]float64)
  766. for _, reqV := range req {
  767. if reqV.Timestamp == 0 {
  768. continue
  769. }
  770. reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
  771. reqMap[reqV.Timestamp] = reqV.Value
  772. timestamps = append(timestamps, reqV.Timestamp)
  773. }
  774. usedMap := make(map[float64]float64)
  775. for _, usedV := range used {
  776. if usedV.Timestamp == 0 {
  777. continue
  778. }
  779. usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
  780. usedMap[usedV.Timestamp] = usedV.Value
  781. if _, ok := reqMap[usedV.Timestamp]; !ok { // no need to double add, since we'll range over sorted timestamps and check.
  782. timestamps = append(timestamps, usedV.Timestamp)
  783. }
  784. }
  785. sort.Float64s(timestamps)
  786. for _, t := range timestamps {
  787. rv, okR := reqMap[t]
  788. uv, okU := usedMap[t]
  789. allocationVector := &Vector{
  790. Timestamp: t,
  791. }
  792. if okR && okU {
  793. allocationVector.Value = math.Max(rv, uv)
  794. } else if okR {
  795. allocationVector.Value = rv
  796. } else if okU {
  797. allocationVector.Value = uv
  798. }
  799. allocation = append(allocation, allocationVector)
  800. }
  801. return allocation
  802. }
  803. func addPVData(cache ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
  804. cfg, err := cloud.GetConfig()
  805. if err != nil {
  806. return err
  807. }
  808. storageClasses := cache.GetAllStorageClasses()
  809. storageClassMap := make(map[string]map[string]string)
  810. for _, storageClass := range storageClasses {
  811. params := storageClass.Parameters
  812. storageClassMap[storageClass.ObjectMeta.Name] = params
  813. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  814. storageClassMap["default"] = params
  815. storageClassMap[""] = params
  816. }
  817. }
  818. pvs := cache.GetAllPersistentVolumes()
  819. pvMap := make(map[string]*costAnalyzerCloud.PV)
  820. for _, pv := range pvs {
  821. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  822. if !ok {
  823. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  824. }
  825. cacPv := &costAnalyzerCloud.PV{
  826. Class: pv.Spec.StorageClassName,
  827. Region: pv.Labels[v1.LabelZoneRegion],
  828. Parameters: parameters,
  829. }
  830. err := GetPVCost(cacPv, pv, cloud)
  831. if err != nil {
  832. return err
  833. }
  834. pvMap[pv.Name] = cacPv
  835. }
  836. for _, pvc := range pvClaimMapping {
  837. if vol, ok := pvMap[pvc.VolumeName]; ok {
  838. pvc.Volume = vol
  839. } else {
  840. klog.V(1).Infof("PV not found, using default")
  841. pvc.Volume = &costAnalyzerCloud.PV{
  842. Cost: cfg.Storage,
  843. }
  844. }
  845. }
  846. return nil
  847. }
  848. func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cloud costAnalyzerCloud.Provider) error {
  849. cfg, err := cloud.GetConfig()
  850. if err != nil {
  851. return err
  852. }
  853. key := cloud.GetPVKey(kpv, pv.Parameters)
  854. pvWithCost, err := cloud.PVPricing(key)
  855. if err != nil {
  856. pv.Cost = cfg.Storage
  857. return err
  858. }
  859. if pvWithCost == nil || pvWithCost.Cost == "" {
  860. pv.Cost = cfg.Storage
  861. return nil // set default cost
  862. }
  863. pv.Cost = pvWithCost.Cost
  864. return nil
  865. }
  866. func getNodeCost(cache ClusterCache, cloud costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
  867. cfg, err := cloud.GetConfig()
  868. if err != nil {
  869. return nil, err
  870. }
  871. nodeList := cache.GetAllNodes()
  872. nodes := make(map[string]*costAnalyzerCloud.Node)
  873. for _, n := range nodeList {
  874. name := n.GetObjectMeta().GetName()
  875. nodeLabels := n.GetObjectMeta().GetLabels()
  876. nodeLabels["providerID"] = n.Spec.ProviderID
  877. cnode, err := cloud.NodePricing(cloud.GetKey(nodeLabels))
  878. if err != nil {
  879. klog.V(1).Infof("Error getting node. Error: " + err.Error())
  880. nodes[name] = cnode
  881. continue
  882. }
  883. newCnode := *cnode
  884. var cpu float64
  885. if newCnode.VCPU == "" {
  886. cpu = float64(n.Status.Capacity.Cpu().Value())
  887. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  888. } else {
  889. cpu, _ = strconv.ParseFloat(newCnode.VCPU, 64)
  890. }
  891. var ram float64
  892. if newCnode.RAM == "" {
  893. newCnode.RAM = n.Status.Capacity.Memory().String()
  894. }
  895. ram = float64(n.Status.Capacity.Memory().Value())
  896. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  897. if newCnode.GPU != "" && newCnode.GPUCost == "" { // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  898. klog.V(4).Infof("GPU without cost found for %s, calculating...", cloud.GetKey(nodeLabels).Features())
  899. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  900. if err != nil {
  901. klog.V(3).Infof("Could not parse default cpu price")
  902. return nil, err
  903. }
  904. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  905. if err != nil {
  906. klog.V(3).Infof("Could not parse default ram price")
  907. return nil, err
  908. }
  909. defaultGPU, err := strconv.ParseFloat(cfg.RAM, 64)
  910. if err != nil {
  911. klog.V(3).Infof("Could not parse default gpu price")
  912. return nil, err
  913. }
  914. cpuToRAMRatio := defaultCPU / defaultRAM
  915. gpuToRAMRatio := defaultGPU / defaultRAM
  916. ramGB := ram / 1024 / 1024 / 1024
  917. ramMultiple := gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  918. var nodePrice float64
  919. if newCnode.Cost != "" {
  920. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  921. if err != nil {
  922. klog.V(3).Infof("Could not parse total node price")
  923. return nil, err
  924. }
  925. } else {
  926. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  927. if err != nil {
  928. klog.V(3).Infof("Could not parse node vcpu price")
  929. return nil, err
  930. }
  931. }
  932. ramPrice := (nodePrice / ramMultiple)
  933. cpuPrice := ramPrice * cpuToRAMRatio
  934. gpuPrice := ramPrice * gpuToRAMRatio
  935. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  936. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  937. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  938. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  939. } else {
  940. if newCnode.RAMCost == "" { // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  941. klog.V(4).Infof("No RAM cost found for %s, calculating...", cloud.GetKey(nodeLabels).Features())
  942. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  943. if err != nil {
  944. klog.V(3).Infof("Could not parse default cpu price")
  945. return nil, err
  946. }
  947. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  948. if err != nil {
  949. klog.V(3).Infof("Could not parse default ram price")
  950. return nil, err
  951. }
  952. cpuToRAMRatio := defaultCPU / defaultRAM
  953. ramGB := ram / 1024 / 1024 / 1024
  954. ramMultiple := cpu*cpuToRAMRatio + ramGB
  955. var nodePrice float64
  956. if newCnode.Cost != "" {
  957. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  958. if err != nil {
  959. klog.V(3).Infof("Could not parse total node price")
  960. return nil, err
  961. }
  962. } else {
  963. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  964. if err != nil {
  965. klog.V(3).Infof("Could not parse node vcpu price")
  966. return nil, err
  967. }
  968. }
  969. ramPrice := (nodePrice / ramMultiple)
  970. cpuPrice := ramPrice * cpuToRAMRatio
  971. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  972. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  973. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  974. klog.V(4).Infof("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  975. }
  976. }
  977. nodes[name] = &newCnode
  978. }
  979. return nodes, nil
  980. }
  981. func getPodServices(cache ClusterCache, podList []*v1.Pod) (map[string]map[string][]string, error) {
  982. servicesList := cache.GetAllServices()
  983. podServicesMapping := make(map[string]map[string][]string)
  984. for _, service := range servicesList {
  985. namespace := service.GetObjectMeta().GetNamespace()
  986. name := service.GetObjectMeta().GetName()
  987. if _, ok := podServicesMapping[namespace]; !ok {
  988. podServicesMapping[namespace] = make(map[string][]string)
  989. }
  990. s := labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  991. for _, pod := range podList {
  992. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  993. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  994. services, ok := podServicesMapping[namespace][pod.GetObjectMeta().GetName()]
  995. if ok {
  996. podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = append(services, name)
  997. } else {
  998. podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
  999. }
  1000. }
  1001. }
  1002. }
  1003. return podServicesMapping, nil
  1004. }
  1005. func getPodDeployments(cache ClusterCache, podList []*v1.Pod) (map[string]map[string][]string, error) {
  1006. deploymentsList := cache.GetAllDeployments()
  1007. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1008. for _, deployment := range deploymentsList {
  1009. namespace := deployment.GetObjectMeta().GetNamespace()
  1010. name := deployment.GetObjectMeta().GetName()
  1011. if _, ok := podDeploymentsMapping[namespace]; !ok {
  1012. podDeploymentsMapping[namespace] = make(map[string][]string)
  1013. }
  1014. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1015. if err != nil {
  1016. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  1017. }
  1018. for _, pod := range podList {
  1019. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1020. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1021. deployments, ok := podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()]
  1022. if ok {
  1023. podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1024. } else {
  1025. podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
  1026. }
  1027. }
  1028. }
  1029. }
  1030. return podDeploymentsMapping, nil
  1031. }
  1032. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider,
  1033. startString, endString, windowString string, filterNamespace string, remoteEnabled bool) (map[string]*CostData, error) {
  1034. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, windowString, "", windowString, "")
  1035. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, windowString, "", windowString, "")
  1036. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, windowString, "", windowString, "")
  1037. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, windowString, "")
  1038. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, windowString, "", windowString, "")
  1039. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  1040. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, windowString, "")
  1041. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, windowString, "")
  1042. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, windowString, "")
  1043. normalization := fmt.Sprintf(normalizationStr, windowString, "")
  1044. layout := "2006-01-02T15:04:05.000Z"
  1045. start, err := time.Parse(layout, startString)
  1046. if err != nil {
  1047. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1048. return nil, err
  1049. }
  1050. end, err := time.Parse(layout, endString)
  1051. if err != nil {
  1052. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1053. return nil, err
  1054. }
  1055. window, err := time.ParseDuration(windowString)
  1056. if err != nil {
  1057. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1058. return nil, err
  1059. }
  1060. clustID := os.Getenv(CLUSTER_ID)
  1061. if remoteEnabled == true {
  1062. remoteLayout := "2006-01-02T15:04:05Z"
  1063. remoteStartStr := start.Format(remoteLayout)
  1064. remoteEndStr := end.Format(remoteLayout)
  1065. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  1066. return CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  1067. }
  1068. var wg sync.WaitGroup
  1069. wg.Add(11)
  1070. var promErr error
  1071. var resultRAMRequests interface{}
  1072. go func() {
  1073. resultRAMRequests, promErr = QueryRange(cli, queryRAMRequests, start, end, window)
  1074. defer wg.Done()
  1075. }()
  1076. var resultRAMUsage interface{}
  1077. go func() {
  1078. resultRAMUsage, promErr = QueryRange(cli, queryRAMUsage, start, end, window)
  1079. defer wg.Done()
  1080. }()
  1081. var resultCPURequests interface{}
  1082. go func() {
  1083. resultCPURequests, promErr = QueryRange(cli, queryCPURequests, start, end, window)
  1084. defer wg.Done()
  1085. }()
  1086. var resultCPUUsage interface{}
  1087. go func() {
  1088. resultCPUUsage, promErr = QueryRange(cli, queryCPUUsage, start, end, window)
  1089. defer wg.Done()
  1090. }()
  1091. var resultGPURequests interface{}
  1092. go func() {
  1093. resultGPURequests, promErr = QueryRange(cli, queryGPURequests, start, end, window)
  1094. defer wg.Done()
  1095. }()
  1096. var resultPVRequests interface{}
  1097. go func() {
  1098. resultPVRequests, promErr = QueryRange(cli, queryPVRequests, start, end, window)
  1099. defer wg.Done()
  1100. }()
  1101. var resultNetZoneRequests interface{}
  1102. go func() {
  1103. resultNetZoneRequests, promErr = QueryRange(cli, queryNetZoneRequests, start, end, window)
  1104. defer wg.Done()
  1105. }()
  1106. var resultNetRegionRequests interface{}
  1107. go func() {
  1108. resultNetRegionRequests, promErr = QueryRange(cli, queryNetRegionRequests, start, end, window)
  1109. defer wg.Done()
  1110. }()
  1111. var resultNetInternetRequests interface{}
  1112. go func() {
  1113. resultNetInternetRequests, promErr = QueryRange(cli, queryNetInternetRequests, start, end, window)
  1114. defer wg.Done()
  1115. }()
  1116. var normalizationResult interface{}
  1117. go func() {
  1118. normalizationResult, promErr = Query(cli, normalization)
  1119. defer wg.Done()
  1120. }()
  1121. podDeploymentsMapping := make(map[string]map[string][]string)
  1122. podServicesMapping := make(map[string]map[string][]string)
  1123. namespaceLabelsMapping := make(map[string]map[string]string)
  1124. podlist := cm.Cache.GetAllPods()
  1125. var k8sErr error
  1126. go func() {
  1127. podDeploymentsMapping, k8sErr = getPodDeployments(cm.Cache, podlist)
  1128. if k8sErr != nil {
  1129. return
  1130. }
  1131. podServicesMapping, k8sErr = getPodServices(cm.Cache, podlist)
  1132. if k8sErr != nil {
  1133. return
  1134. }
  1135. namespaceLabelsMapping, k8sErr = getNamespaceLabels(cm.Cache)
  1136. if k8sErr != nil {
  1137. return
  1138. }
  1139. wg.Done()
  1140. }()
  1141. wg.Wait()
  1142. if promErr != nil {
  1143. return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  1144. }
  1145. if k8sErr != nil {
  1146. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  1147. }
  1148. normalizationValue, err := getNormalization(normalizationResult)
  1149. if err != nil {
  1150. return nil, fmt.Errorf("Error parsing normalization values: " + err.Error())
  1151. }
  1152. nodes, err := getNodeCost(cm.Cache, cloud)
  1153. if err != nil {
  1154. klog.V(1).Infof("Warning, no cost model available: " + err.Error())
  1155. return nil, err
  1156. }
  1157. pvClaimMapping, err := getPVInfoVectors(resultPVRequests)
  1158. if err != nil {
  1159. // Just log for compatibility with KSM less than 1.6
  1160. klog.Infof("Unable to get PV Data: %s", err.Error())
  1161. }
  1162. if pvClaimMapping != nil {
  1163. err = addPVData(cm.Cache, pvClaimMapping, cloud)
  1164. if err != nil {
  1165. return nil, err
  1166. }
  1167. }
  1168. networkUsageMap, err := GetNetworkUsageData(resultNetZoneRequests, resultNetRegionRequests, resultNetInternetRequests, true)
  1169. if err != nil {
  1170. klog.V(1).Infof("Unable to get Network Cost Data: %s", err.Error())
  1171. networkUsageMap = make(map[string]*NetworkUsageData)
  1172. }
  1173. containerNameCost := make(map[string]*CostData)
  1174. containers := make(map[string]bool)
  1175. RAMReqMap, err := GetContainerMetricVectors(resultRAMRequests, true, normalizationValue)
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. for key := range RAMReqMap {
  1180. containers[key] = true
  1181. }
  1182. RAMUsedMap, err := GetContainerMetricVectors(resultRAMUsage, true, normalizationValue)
  1183. if err != nil {
  1184. return nil, err
  1185. }
  1186. for key := range RAMUsedMap {
  1187. containers[key] = true
  1188. }
  1189. CPUReqMap, err := GetContainerMetricVectors(resultCPURequests, true, normalizationValue)
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. for key := range CPUReqMap {
  1194. containers[key] = true
  1195. }
  1196. GPUReqMap, err := GetContainerMetricVectors(resultGPURequests, true, normalizationValue)
  1197. if err != nil {
  1198. return nil, err
  1199. }
  1200. for key := range GPUReqMap {
  1201. containers[key] = true
  1202. }
  1203. CPUUsedMap, err := GetContainerMetricVectors(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
  1204. if err != nil {
  1205. return nil, err
  1206. }
  1207. for key := range CPUUsedMap {
  1208. containers[key] = true
  1209. }
  1210. currentContainers := make(map[string]v1.Pod)
  1211. for _, pod := range podlist {
  1212. if pod.Status.Phase != v1.PodRunning {
  1213. continue
  1214. }
  1215. cs, err := newContainerMetricsFromPod(*pod)
  1216. if err != nil {
  1217. return nil, err
  1218. }
  1219. for _, c := range cs {
  1220. 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.
  1221. currentContainers[c.Key()] = *pod
  1222. }
  1223. }
  1224. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1225. missingContainers := make(map[string]*CostData)
  1226. for key := range containers {
  1227. if _, ok := containerNameCost[key]; ok {
  1228. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1229. }
  1230. if pod, ok := currentContainers[key]; ok {
  1231. podName := pod.GetObjectMeta().GetName()
  1232. ns := pod.GetObjectMeta().GetNamespace()
  1233. nodeName := pod.Spec.NodeName
  1234. var nodeData *costAnalyzerCloud.Node
  1235. if _, ok := nodes[nodeName]; ok {
  1236. nodeData = nodes[nodeName]
  1237. }
  1238. var podDeployments []string
  1239. if _, ok := podDeploymentsMapping[ns]; ok {
  1240. if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  1241. podDeployments = ds
  1242. } else {
  1243. podDeployments = []string{}
  1244. }
  1245. }
  1246. var podPVs []*PersistentVolumeClaimData
  1247. podClaims := pod.Spec.Volumes
  1248. for _, vol := range podClaims {
  1249. if vol.PersistentVolumeClaim != nil {
  1250. name := vol.PersistentVolumeClaim.ClaimName
  1251. if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
  1252. podPVs = append(podPVs, pvClaim)
  1253. }
  1254. }
  1255. }
  1256. var podNetCosts []*Vector
  1257. if usage, ok := networkUsageMap[ns+","+podName]; ok {
  1258. netCosts, err := GetNetworkCost(usage, cloud)
  1259. if err != nil {
  1260. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  1261. } else {
  1262. podNetCosts = netCosts
  1263. }
  1264. }
  1265. var podServices []string
  1266. if _, ok := podServicesMapping[ns]; ok {
  1267. if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
  1268. podServices = svcs
  1269. } else {
  1270. podServices = []string{}
  1271. }
  1272. }
  1273. nsLabels := namespaceLabelsMapping[ns]
  1274. podLabels := pod.GetObjectMeta().GetLabels()
  1275. if podLabels == nil {
  1276. podLabels = make(map[string]string)
  1277. }
  1278. for k, v := range nsLabels {
  1279. if _, ok := podLabels[k]; !ok {
  1280. podLabels[k] = v
  1281. }
  1282. }
  1283. for i, container := range pod.Spec.Containers {
  1284. containerName := container.Name
  1285. newKey := newContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName).Key()
  1286. RAMReqV, ok := RAMReqMap[newKey]
  1287. if !ok {
  1288. klog.V(4).Info("no RAM requests for " + newKey)
  1289. RAMReqV = []*Vector{}
  1290. }
  1291. RAMUsedV, ok := RAMUsedMap[newKey]
  1292. if !ok {
  1293. klog.V(4).Info("no RAM usage for " + newKey)
  1294. RAMUsedV = []*Vector{}
  1295. }
  1296. CPUReqV, ok := CPUReqMap[newKey]
  1297. if !ok {
  1298. klog.V(4).Info("no CPU requests for " + newKey)
  1299. CPUReqV = []*Vector{}
  1300. }
  1301. GPUReqV, ok := GPUReqMap[newKey]
  1302. if !ok {
  1303. klog.V(4).Info("no GPU requests for " + newKey)
  1304. GPUReqV = []*Vector{}
  1305. }
  1306. CPUUsedV, ok := CPUUsedMap[newKey]
  1307. if !ok {
  1308. klog.V(4).Info("no CPU usage for " + newKey)
  1309. CPUUsedV = []*Vector{}
  1310. }
  1311. var pvReq []*PersistentVolumeClaimData
  1312. var netReq []*Vector
  1313. if i == 0 { // avoid duplicating by just assigning all claims to the first container.
  1314. pvReq = podPVs
  1315. netReq = podNetCosts
  1316. }
  1317. costs := &CostData{
  1318. Name: containerName,
  1319. PodName: podName,
  1320. NodeName: nodeName,
  1321. Namespace: ns,
  1322. Deployments: podDeployments,
  1323. Services: podServices,
  1324. Daemonsets: getDaemonsetsOfPod(pod),
  1325. Jobs: getJobsOfPod(pod),
  1326. Statefulsets: getStatefulSetsOfPod(pod),
  1327. NodeData: nodeData,
  1328. RAMReq: RAMReqV,
  1329. RAMUsed: RAMUsedV,
  1330. CPUReq: CPUReqV,
  1331. CPUUsed: CPUUsedV,
  1332. GPUReq: GPUReqV,
  1333. PVCData: pvReq,
  1334. Labels: podLabels,
  1335. NetworkData: netReq,
  1336. NamespaceLabels: nsLabels,
  1337. ClusterID: clustID,
  1338. }
  1339. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  1340. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  1341. if filterNamespace == "" {
  1342. containerNameCost[newKey] = costs
  1343. } else if costs.Namespace == filterNamespace {
  1344. containerNameCost[newKey] = costs
  1345. }
  1346. }
  1347. } else {
  1348. // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
  1349. klog.V(4).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
  1350. c, _ := NewContainerMetricFromKey(key)
  1351. RAMReqV, ok := RAMReqMap[key]
  1352. if !ok {
  1353. klog.V(4).Info("no RAM requests for " + key)
  1354. RAMReqV = []*Vector{}
  1355. }
  1356. RAMUsedV, ok := RAMUsedMap[key]
  1357. if !ok {
  1358. klog.V(4).Info("no RAM usage for " + key)
  1359. RAMUsedV = []*Vector{}
  1360. }
  1361. CPUReqV, ok := CPUReqMap[key]
  1362. if !ok {
  1363. klog.V(4).Info("no CPU requests for " + key)
  1364. CPUReqV = []*Vector{}
  1365. }
  1366. GPUReqV, ok := GPUReqMap[key]
  1367. if !ok {
  1368. klog.V(4).Info("no GPU requests for " + key)
  1369. GPUReqV = []*Vector{}
  1370. }
  1371. CPUUsedV, ok := CPUUsedMap[key]
  1372. if !ok {
  1373. klog.V(4).Info("no CPU usage for " + key)
  1374. CPUUsedV = []*Vector{}
  1375. }
  1376. node, ok := nodes[c.NodeName]
  1377. if !ok {
  1378. klog.V(2).Infof("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
  1379. if n, ok := missingNodes[c.NodeName]; ok {
  1380. node = n
  1381. } else {
  1382. node = &costAnalyzerCloud.Node{}
  1383. missingNodes[c.NodeName] = node
  1384. }
  1385. }
  1386. namespacelabels, ok := namespaceLabelsMapping[c.Namespace]
  1387. if !ok {
  1388. klog.V(3).Infof("Missing data for namespace %s", c.Namespace)
  1389. }
  1390. costs := &CostData{
  1391. Name: c.ContainerName,
  1392. PodName: c.PodName,
  1393. NodeName: c.NodeName,
  1394. NodeData: node,
  1395. Namespace: c.Namespace,
  1396. RAMReq: RAMReqV,
  1397. RAMUsed: RAMUsedV,
  1398. CPUReq: CPUReqV,
  1399. CPUUsed: CPUUsedV,
  1400. GPUReq: GPUReqV,
  1401. NamespaceLabels: namespacelabels,
  1402. ClusterID: clustID,
  1403. }
  1404. costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
  1405. costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
  1406. if filterNamespace == "" {
  1407. containerNameCost[key] = costs
  1408. missingContainers[key] = costs
  1409. } else if costs.Namespace == filterNamespace {
  1410. containerNameCost[key] = costs
  1411. missingContainers[key] = costs
  1412. }
  1413. }
  1414. }
  1415. w := end.Sub(start)
  1416. w += window
  1417. if w.Minutes() > 0 {
  1418. wStr := fmt.Sprintf("%dm", int(w.Minutes()))
  1419. err = findDeletedNodeInfo(cli, missingNodes, wStr)
  1420. if err != nil {
  1421. klog.V(1).Infof("Error fetching historical node data: %s", err.Error())
  1422. }
  1423. err = findDeletedPodInfo(cli, missingContainers, wStr)
  1424. if err != nil {
  1425. klog.V(1).Infof("Error fetching historical pod data: %s", err.Error())
  1426. }
  1427. }
  1428. return containerNameCost, err
  1429. }
  1430. func getNamespaceLabels(cache ClusterCache) (map[string]map[string]string, error) {
  1431. nsToLabels := make(map[string]map[string]string)
  1432. nss := cache.GetAllNamespaces()
  1433. for _, ns := range nss {
  1434. nsToLabels[ns.Name] = ns.Labels
  1435. }
  1436. return nsToLabels, nil
  1437. }
  1438. func getDaemonsetsOfPod(pod v1.Pod) []string {
  1439. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1440. if ownerReference.Kind == "DaemonSet" {
  1441. return []string{ownerReference.Name}
  1442. }
  1443. }
  1444. return []string{}
  1445. }
  1446. func getJobsOfPod(pod v1.Pod) []string {
  1447. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1448. if ownerReference.Kind == "Job" {
  1449. return []string{ownerReference.Name}
  1450. }
  1451. }
  1452. return []string{}
  1453. }
  1454. func getStatefulSetsOfPod(pod v1.Pod) []string {
  1455. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  1456. if ownerReference.Kind == "StatefulSet" {
  1457. return []string{ownerReference.Name}
  1458. }
  1459. }
  1460. return []string{}
  1461. }
  1462. type PersistentVolumeClaimData struct {
  1463. Class string `json:"class"`
  1464. Claim string `json:"claim"`
  1465. Namespace string `json:"namespace"`
  1466. VolumeName string `json:"volumeName"`
  1467. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  1468. Values []*Vector `json:"values"`
  1469. }
  1470. func getCost(qr interface{}) (map[string][]*Vector, error) {
  1471. toReturn := make(map[string][]*Vector)
  1472. for _, val := range qr.(map[string]interface{})["data"].(map[string]interface{})["result"].([]interface{}) {
  1473. metricInterface, ok := val.(map[string]interface{})["metric"]
  1474. if !ok {
  1475. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1476. }
  1477. metricMap, ok := metricInterface.(map[string]interface{})
  1478. if !ok {
  1479. return nil, fmt.Errorf("Metric field is improperly formatted")
  1480. }
  1481. instance, ok := metricMap["instance"]
  1482. if !ok {
  1483. return nil, fmt.Errorf("Instance field does not exist in data result vector")
  1484. }
  1485. instanceStr, ok := instance.(string)
  1486. if !ok {
  1487. return nil, fmt.Errorf("Instance is improperly formatted")
  1488. }
  1489. dataPoint, ok := val.(map[string]interface{})["value"]
  1490. if !ok {
  1491. return nil, fmt.Errorf("Value field does not exist in data result vector")
  1492. }
  1493. value, ok := dataPoint.([]interface{})
  1494. if !ok || len(value) != 2 {
  1495. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1496. }
  1497. var vectors []*Vector
  1498. strVal := value[1].(string)
  1499. v, _ := strconv.ParseFloat(strVal, 64)
  1500. vectors = append(vectors, &Vector{
  1501. Timestamp: value[0].(float64),
  1502. Value: v,
  1503. })
  1504. toReturn[instanceStr] = vectors
  1505. }
  1506. return toReturn, nil
  1507. }
  1508. func getPVInfoVectors(qr interface{}) (map[string]*PersistentVolumeClaimData, error) {
  1509. pvmap := make(map[string]*PersistentVolumeClaimData)
  1510. data, ok := qr.(map[string]interface{})["data"]
  1511. if !ok {
  1512. e, err := wrapPrometheusError(qr)
  1513. if err != nil {
  1514. return nil, err
  1515. }
  1516. return nil, fmt.Errorf(e)
  1517. }
  1518. d, ok := data.(map[string]interface{})
  1519. if !ok {
  1520. return nil, fmt.Errorf("Data field improperly formatted in prometheus repsonse")
  1521. }
  1522. result, ok := d["result"]
  1523. if !ok {
  1524. return nil, fmt.Errorf("Result field not present in prometheus response")
  1525. }
  1526. results, ok := result.([]interface{})
  1527. if !ok {
  1528. return nil, fmt.Errorf("Result field improperly formatted in prometheus response")
  1529. }
  1530. for _, val := range results {
  1531. metricInterface, ok := val.(map[string]interface{})["metric"]
  1532. if !ok {
  1533. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1534. }
  1535. metricMap, ok := metricInterface.(map[string]interface{})
  1536. if !ok {
  1537. return nil, fmt.Errorf("Metric field is improperly formatted")
  1538. }
  1539. pvclaim, ok := metricMap["persistentvolumeclaim"]
  1540. if !ok {
  1541. return nil, fmt.Errorf("Claim field does not exist in data result vector")
  1542. }
  1543. pvclaimStr, ok := pvclaim.(string)
  1544. if !ok {
  1545. return nil, fmt.Errorf("Claim field improperly formatted")
  1546. }
  1547. pvnamespace, ok := metricMap["namespace"]
  1548. if !ok {
  1549. return nil, fmt.Errorf("Namespace field does not exist in data result vector")
  1550. }
  1551. pvnamespaceStr, ok := pvnamespace.(string)
  1552. if !ok {
  1553. return nil, fmt.Errorf("Namespace field improperly formatted")
  1554. }
  1555. pv, ok := metricMap["volumename"]
  1556. if !ok {
  1557. klog.V(3).Infof("Warning: Unfulfilled claim %s: volumename field does not exist in data result vector", pvclaimStr)
  1558. pv = ""
  1559. }
  1560. pvStr, ok := pv.(string)
  1561. if !ok {
  1562. return nil, fmt.Errorf("Volumename field improperly formatted")
  1563. }
  1564. pvclass, ok := metricMap["storageclass"]
  1565. if !ok { // TODO: We need to look up the actual PV and PV capacity. For now just proceed with "".
  1566. klog.V(2).Infof("Storage Class not found for claim \"%s/%s\".", pvnamespaceStr, pvclaimStr)
  1567. pvclass = ""
  1568. }
  1569. pvclassStr, ok := pvclass.(string)
  1570. if !ok {
  1571. return nil, fmt.Errorf("StorageClass field improperly formatted")
  1572. }
  1573. values, ok := val.(map[string]interface{})["values"].([]interface{})
  1574. if !ok {
  1575. return nil, fmt.Errorf("Values field is improperly formatted")
  1576. }
  1577. var vectors []*Vector
  1578. for _, value := range values {
  1579. dataPoint, ok := value.([]interface{})
  1580. if !ok || len(dataPoint) != 2 {
  1581. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1582. }
  1583. strVal := dataPoint[1].(string)
  1584. v, _ := strconv.ParseFloat(strVal, 64)
  1585. vectors = append(vectors, &Vector{
  1586. Timestamp: math.Round(dataPoint[0].(float64)/10) * 10,
  1587. Value: v,
  1588. })
  1589. }
  1590. key := pvnamespaceStr + "," + pvclaimStr
  1591. pvmap[key] = &PersistentVolumeClaimData{
  1592. Class: pvclassStr,
  1593. Claim: pvclaimStr,
  1594. Namespace: pvnamespaceStr,
  1595. VolumeName: pvStr,
  1596. Values: vectors,
  1597. }
  1598. }
  1599. return pvmap, nil
  1600. }
  1601. func getPVInfoVector(qr interface{}) (map[string]*PersistentVolumeClaimData, error) {
  1602. pvmap := make(map[string]*PersistentVolumeClaimData)
  1603. data, ok := qr.(map[string]interface{})["data"]
  1604. if !ok {
  1605. e, err := wrapPrometheusError(qr)
  1606. if err != nil {
  1607. return nil, err
  1608. }
  1609. return nil, fmt.Errorf(e)
  1610. }
  1611. d, ok := data.(map[string]interface{})
  1612. if !ok {
  1613. return nil, fmt.Errorf("Data field improperly formatted in prometheus repsonse")
  1614. }
  1615. result, ok := d["result"]
  1616. if !ok {
  1617. return nil, fmt.Errorf("Result field not present in prometheus response")
  1618. }
  1619. results, ok := result.([]interface{})
  1620. if !ok {
  1621. return nil, fmt.Errorf("Result field improperly formatted in prometheus response")
  1622. }
  1623. for _, val := range results {
  1624. metricInterface, ok := val.(map[string]interface{})["metric"]
  1625. if !ok {
  1626. return nil, fmt.Errorf("Metric field does not exist in data result vector")
  1627. }
  1628. metricMap, ok := metricInterface.(map[string]interface{})
  1629. if !ok {
  1630. return nil, fmt.Errorf("Metric field is improperly formatted")
  1631. }
  1632. pvclaim, ok := metricMap["persistentvolumeclaim"]
  1633. if !ok {
  1634. return nil, fmt.Errorf("Claim field does not exist in data result vector")
  1635. }
  1636. pvclaimStr, ok := pvclaim.(string)
  1637. if !ok {
  1638. return nil, fmt.Errorf("Claim field improperly formatted")
  1639. }
  1640. pvnamespace, ok := metricMap["namespace"]
  1641. if !ok {
  1642. return nil, fmt.Errorf("Namespace field does not exist in data result vector")
  1643. }
  1644. pvnamespaceStr, ok := pvnamespace.(string)
  1645. if !ok {
  1646. return nil, fmt.Errorf("Namespace field improperly formatted")
  1647. }
  1648. pv, ok := metricMap["volumename"]
  1649. if !ok {
  1650. klog.V(3).Infof("Warning: Unfulfilled claim %s: volumename field does not exist in data result vector", pvclaimStr)
  1651. pv = ""
  1652. }
  1653. pvStr, ok := pv.(string)
  1654. if !ok {
  1655. return nil, fmt.Errorf("Volumename field improperly formatted")
  1656. }
  1657. pvclass, ok := metricMap["storageclass"]
  1658. if !ok { // TODO: We need to look up the actual PV and PV capacity. For now just proceed with "".
  1659. klog.V(2).Infof("Storage Class not found for claim \"%s/%s\".", pvnamespaceStr, pvclaimStr)
  1660. pvclass = ""
  1661. }
  1662. pvclassStr, ok := pvclass.(string)
  1663. if !ok {
  1664. return nil, fmt.Errorf("StorageClass field improperly formatted")
  1665. }
  1666. dataPoint, ok := val.(map[string]interface{})["value"]
  1667. if !ok {
  1668. return nil, fmt.Errorf("Value field does not exist in data result vector")
  1669. }
  1670. value, ok := dataPoint.([]interface{})
  1671. if !ok || len(value) != 2 {
  1672. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1673. }
  1674. var vectors []*Vector
  1675. strVal := value[1].(string)
  1676. v, _ := strconv.ParseFloat(strVal, 64)
  1677. vectors = append(vectors, &Vector{
  1678. Timestamp: value[0].(float64),
  1679. Value: v,
  1680. })
  1681. key := pvnamespaceStr + "," + pvclaimStr
  1682. pvmap[key] = &PersistentVolumeClaimData{
  1683. Class: pvclassStr,
  1684. Claim: pvclaimStr,
  1685. Namespace: pvnamespaceStr,
  1686. VolumeName: pvStr,
  1687. Values: vectors,
  1688. }
  1689. }
  1690. return pvmap, nil
  1691. }
  1692. func QueryRange(cli prometheusClient.Client, query string, start, end time.Time, step time.Duration) (interface{}, error) {
  1693. u := cli.URL(epQueryRange, nil)
  1694. q := u.Query()
  1695. q.Set("query", query)
  1696. q.Set("start", start.Format(time.RFC3339Nano))
  1697. q.Set("end", end.Format(time.RFC3339Nano))
  1698. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  1699. u.RawQuery = q.Encode()
  1700. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  1701. if err != nil {
  1702. return nil, err
  1703. }
  1704. resp, body, warnings, err := cli.Do(context.Background(), req)
  1705. for _, w := range warnings {
  1706. klog.V(3).Infof("%s", w)
  1707. }
  1708. if err != nil {
  1709. return nil, fmt.Errorf("%s Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  1710. }
  1711. var toReturn interface{}
  1712. err = json.Unmarshal(body, &toReturn)
  1713. if err != nil {
  1714. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  1715. }
  1716. return toReturn, err
  1717. }
  1718. func Query(cli prometheusClient.Client, query string) (interface{}, error) {
  1719. u := cli.URL(epQuery, nil)
  1720. q := u.Query()
  1721. q.Set("query", query)
  1722. u.RawQuery = q.Encode()
  1723. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  1724. if err != nil {
  1725. return nil, err
  1726. }
  1727. resp, body, warnings, err := cli.Do(context.Background(), req)
  1728. for _, w := range warnings {
  1729. klog.V(3).Infof("%s", w)
  1730. }
  1731. if err != nil {
  1732. return nil, fmt.Errorf("%s Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  1733. }
  1734. var toReturn interface{}
  1735. err = json.Unmarshal(body, &toReturn)
  1736. if err != nil {
  1737. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  1738. }
  1739. return toReturn, nil
  1740. }
  1741. //todo: don't cast, implement unmarshaler interface
  1742. func getNormalization(qr interface{}) (float64, error) {
  1743. data, ok := qr.(map[string]interface{})["data"]
  1744. if !ok {
  1745. e, err := wrapPrometheusError(qr)
  1746. if err != nil {
  1747. return 0, err
  1748. }
  1749. return 0, fmt.Errorf(e)
  1750. }
  1751. results, ok := data.(map[string]interface{})["result"].([]interface{})
  1752. if !ok {
  1753. return 0, fmt.Errorf("Result field not found in normalization response, aborting")
  1754. }
  1755. if len(results) > 0 {
  1756. dataPoint := results[0].(map[string]interface{})["value"].([]interface{})
  1757. if len(dataPoint) == 2 {
  1758. strNorm := dataPoint[1].(string)
  1759. val, _ := strconv.ParseFloat(strNorm, 64)
  1760. return val, nil
  1761. }
  1762. return 0, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1763. }
  1764. return 0, fmt.Errorf("Normalization data is empty, kube-state-metrics or node-exporter may not be running")
  1765. }
  1766. type ContainerMetric struct {
  1767. Namespace string
  1768. PodName string
  1769. ContainerName string
  1770. NodeName string
  1771. }
  1772. func (c *ContainerMetric) Key() string {
  1773. return c.Namespace + "," + c.PodName + "," + c.ContainerName + "," + c.NodeName
  1774. }
  1775. func NewContainerMetricFromKey(key string) (*ContainerMetric, error) {
  1776. s := strings.Split(key, ",")
  1777. if len(s) == 4 {
  1778. return &ContainerMetric{
  1779. Namespace: s[0],
  1780. PodName: s[1],
  1781. ContainerName: s[2],
  1782. NodeName: s[3],
  1783. }, nil
  1784. }
  1785. return nil, fmt.Errorf("Not a valid key")
  1786. }
  1787. func newContainerMetricFromValues(ns string, podName string, containerName string, nodeName string) *ContainerMetric {
  1788. return &ContainerMetric{
  1789. Namespace: ns,
  1790. PodName: podName,
  1791. ContainerName: containerName,
  1792. NodeName: nodeName,
  1793. }
  1794. }
  1795. func newContainerMetricsFromPod(pod v1.Pod) ([]*ContainerMetric, error) {
  1796. podName := pod.GetObjectMeta().GetName()
  1797. ns := pod.GetObjectMeta().GetNamespace()
  1798. node := pod.Spec.NodeName
  1799. var cs []*ContainerMetric
  1800. for _, container := range pod.Spec.Containers {
  1801. containerName := container.Name
  1802. cs = append(cs, &ContainerMetric{
  1803. Namespace: ns,
  1804. PodName: podName,
  1805. ContainerName: containerName,
  1806. NodeName: node,
  1807. })
  1808. }
  1809. return cs, nil
  1810. }
  1811. func newContainerMetricFromPrometheus(metrics map[string]interface{}) (*ContainerMetric, error) {
  1812. cName, ok := metrics["container_name"]
  1813. if !ok {
  1814. return nil, fmt.Errorf("Prometheus vector does not have container name")
  1815. }
  1816. containerName, ok := cName.(string)
  1817. if !ok {
  1818. return nil, fmt.Errorf("Prometheus vector does not have string container name")
  1819. }
  1820. pName, ok := metrics["pod_name"]
  1821. if !ok {
  1822. return nil, fmt.Errorf("Prometheus vector does not have pod name")
  1823. }
  1824. podName, ok := pName.(string)
  1825. if !ok {
  1826. return nil, fmt.Errorf("Prometheus vector does not have string pod name")
  1827. }
  1828. ns, ok := metrics["namespace"]
  1829. if !ok {
  1830. return nil, fmt.Errorf("Prometheus vector does not have namespace")
  1831. }
  1832. namespace, ok := ns.(string)
  1833. if !ok {
  1834. return nil, fmt.Errorf("Prometheus vector does not have string namespace")
  1835. }
  1836. node, ok := metrics["node"]
  1837. if !ok {
  1838. klog.V(4).Info("Prometheus vector does not have node name")
  1839. node = ""
  1840. }
  1841. nodeName, ok := node.(string)
  1842. if !ok {
  1843. return nil, fmt.Errorf("Prometheus vector does not have string node")
  1844. }
  1845. return &ContainerMetric{
  1846. ContainerName: containerName,
  1847. PodName: podName,
  1848. Namespace: namespace,
  1849. NodeName: nodeName,
  1850. }, nil
  1851. }
  1852. func GetContainerMetricVector(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
  1853. data, ok := qr.(map[string]interface{})["data"]
  1854. if !ok {
  1855. e, err := wrapPrometheusError(qr)
  1856. if err != nil {
  1857. return nil, err
  1858. }
  1859. return nil, fmt.Errorf(e)
  1860. }
  1861. r, ok := data.(map[string]interface{})["result"]
  1862. if !ok {
  1863. return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  1864. }
  1865. results, ok := r.([]interface{})
  1866. if !ok {
  1867. return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  1868. }
  1869. containerData := make(map[string][]*Vector)
  1870. for _, val := range results {
  1871. metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  1872. if !ok {
  1873. return nil, fmt.Errorf("Prometheus vector does not have metric labels")
  1874. }
  1875. containerMetric, err := newContainerMetricFromPrometheus(metric)
  1876. if err != nil {
  1877. return nil, err
  1878. }
  1879. value, ok := val.(map[string]interface{})["value"]
  1880. if !ok {
  1881. return nil, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
  1882. }
  1883. dataPoint, ok := value.([]interface{})
  1884. if !ok || len(dataPoint) != 2 {
  1885. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1886. }
  1887. strVal := dataPoint[1].(string)
  1888. v, _ := strconv.ParseFloat(strVal, 64)
  1889. if normalize && normalizationValue != 0 {
  1890. v = v / normalizationValue
  1891. }
  1892. toReturn := &Vector{
  1893. Timestamp: dataPoint[0].(float64),
  1894. Value: v,
  1895. }
  1896. klog.V(4).Info("key: " + containerMetric.Key())
  1897. containerData[containerMetric.Key()] = []*Vector{toReturn}
  1898. }
  1899. return containerData, nil
  1900. }
  1901. func GetContainerMetricVectors(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
  1902. data, ok := qr.(map[string]interface{})["data"]
  1903. if !ok {
  1904. e, err := wrapPrometheusError(qr)
  1905. if err != nil {
  1906. return nil, err
  1907. }
  1908. return nil, fmt.Errorf(e)
  1909. }
  1910. r, ok := data.(map[string]interface{})["result"]
  1911. if !ok {
  1912. return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
  1913. }
  1914. results, ok := r.([]interface{})
  1915. if !ok {
  1916. return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
  1917. }
  1918. containerData := make(map[string][]*Vector)
  1919. for _, val := range results {
  1920. metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
  1921. if !ok {
  1922. return nil, fmt.Errorf("Prometheus vector does not have metric labels")
  1923. }
  1924. containerMetric, err := newContainerMetricFromPrometheus(metric)
  1925. if err != nil {
  1926. return nil, err
  1927. }
  1928. vs, ok := val.(map[string]interface{})["values"]
  1929. if !ok {
  1930. return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a field in the vector")
  1931. }
  1932. values, ok := vs.([]interface{})
  1933. if !ok {
  1934. return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a slice")
  1935. }
  1936. var vectors []*Vector
  1937. for _, value := range values {
  1938. dataPoint, ok := value.([]interface{})
  1939. if !ok || len(dataPoint) != 2 {
  1940. return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  1941. }
  1942. strVal := dataPoint[1].(string)
  1943. v, _ := strconv.ParseFloat(strVal, 64)
  1944. if normalize && normalizationValue != 0 {
  1945. v = v / normalizationValue
  1946. }
  1947. vectors = append(vectors, &Vector{
  1948. Timestamp: math.Round(dataPoint[0].(float64)/10) * 10,
  1949. Value: v,
  1950. })
  1951. }
  1952. containerData[containerMetric.Key()] = vectors
  1953. }
  1954. return containerData, nil
  1955. }
  1956. func wrapPrometheusError(qr interface{}) (string, error) {
  1957. e, ok := qr.(map[string]interface{})["error"]
  1958. if !ok {
  1959. return "", fmt.Errorf("Unexpected response from Prometheus")
  1960. }
  1961. eStr, ok := e.(string)
  1962. return eStr, nil
  1963. }