costmodel.go 78 KB

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