costmodel.go 68 KB

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