| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184 |
- package costmodel
- import (
- "context"
- "encoding/json"
- "fmt"
- "math"
- "net/http"
- "sort"
- "strconv"
- "strings"
- "time"
- costAnalyzerCloud "github.com/kubecost/cost-model/cloud"
- prometheusClient "github.com/prometheus/client_golang/api"
- v1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/labels"
- "k8s.io/client-go/kubernetes"
- "k8s.io/klog"
- )
- const (
- statusAPIError = 422
- apiPrefix = "/api/v1"
- epAlertManagers = apiPrefix + "/alertmanagers"
- epQuery = apiPrefix + "/query"
- epQueryRange = apiPrefix + "/query_range"
- epLabelValues = apiPrefix + "/label/:name/values"
- epSeries = apiPrefix + "/series"
- epTargets = apiPrefix + "/targets"
- epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
- epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
- epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
- epConfig = apiPrefix + "/status/config"
- epFlags = apiPrefix + "/status/flags"
- )
- type CostData struct {
- Name string `json:"name"`
- PodName string `json:"podName"`
- NodeName string `json:"nodeName"`
- NodeData *costAnalyzerCloud.Node `json:"node"`
- Namespace string `json:"namespace"`
- Deployments []string `json:"deployments"`
- Services []string `json:"services"`
- Daemonsets []string `json:"daemonsets"`
- Statefulsets []string `json:"statefulsets"`
- Jobs []string `json:"jobs"`
- RAMReq []*Vector `json:"ramreq"`
- RAMUsed []*Vector `json:"ramused"`
- CPUReq []*Vector `json:"cpureq"`
- CPUUsed []*Vector `json:"cpuused"`
- RAMAllocation []*Vector `json:"ramallocated"`
- CPUAllocation []*Vector `json:"cpuallocated"`
- GPUReq []*Vector `json:"gpureq"`
- PVData []*PersistentVolumeData `json:"pvData"`
- Labels map[string]string `json:"labels"`
- NamespaceLabels map[string]string `json:"namespaceLabels"`
- }
- type Vector struct {
- Timestamp float64 `json:"timestamp"`
- Value float64 `json:"value"`
- }
- func ComputeCostData(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider, window string) (map[string]*CostData, error) {
- queryRAMRequests := `avg(label_replace(label_replace(avg((count_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD"}[` + window + `]) * avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD"}[` + window + `]))) by (namespace,container,pod) , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)") ) by (namespace,container_name, pod_name)`
- queryRAMUsage := `sort_desc(avg(count_over_time(container_memory_usage_bytes{container_name!="",container_name!="POD"}[` + window + `]) * avg_over_time(container_memory_usage_bytes{container_name!="",container_name!="POD"}[` + window + `])) by (namespace,container_name,pod_name,instance))`
- queryCPURequests := `avg(label_replace(label_replace(avg((count_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD"}[` + window + `]) * avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD"}[` + window + `]))) by (namespace,container,pod) , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)") ) by (namespace,container_name, pod_name)`
- queryCPUUsage := `avg(rate(container_cpu_usage_seconds_total{container_name!="",container_name!="POD"}[` + window + `])) by (namespace,container_name,pod_name,instance)`
- queryGPURequests := `avg(label_replace(label_replace(avg((count_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD"}[` + window + `]) * avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD"}[` + window + `]))) by (namespace,container,pod) , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)") ) by (namespace,container_name, pod_name)`
- queryPVRequests := `avg(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass, namespace)
- *
- on (persistentvolumeclaim, namespace) group_right(storageclass)
- sum(kube_persistentvolumeclaim_resource_requests_storage_bytes) by (persistentvolumeclaim, namespace)`
- normalization := `max(count_over_time(kube_pod_container_resource_requests_memory_bytes{}[` + window + `]))`
- resultRAMRequests, err := query(cli, queryRAMRequests)
- if err != nil {
- return nil, fmt.Errorf("Error fetching RAM requests: " + err.Error())
- }
- resultRAMUsage, err := query(cli, queryRAMUsage)
- if err != nil {
- return nil, fmt.Errorf("Error fetching RAM usage: " + err.Error())
- }
- resultCPURequests, err := query(cli, queryCPURequests)
- if err != nil {
- return nil, fmt.Errorf("Error fetching CPU requests: " + err.Error())
- }
- resultCPUUsage, err := query(cli, queryCPUUsage)
- if err != nil {
- return nil, fmt.Errorf("Error fetching CPUUsage requests: " + err.Error())
- }
- resultGPURequests, err := query(cli, queryGPURequests)
- if err != nil {
- return nil, fmt.Errorf("Error fetching GPU requests: " + err.Error())
- }
- resultPVRequests, err := query(cli, queryPVRequests)
- if err != nil {
- return nil, fmt.Errorf("Error fetching PV requests: " + err.Error())
- }
- normalizationResult, err := query(cli, normalization)
- if err != nil {
- return nil, fmt.Errorf("Error fetching normalization data: " + err.Error())
- }
- normalizationValue, err := getNormalization(normalizationResult)
- if err != nil {
- return nil, err
- }
- nodes, err := getNodeCost(clientset, cloud)
- if err != nil {
- klog.V(1).Infof("Warning, no Node cost model available: " + err.Error())
- return nil, err
- }
- podlist, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
- if err != nil {
- return nil, err
- }
- podDeploymentsMapping, err := getPodDeployments(clientset, podlist)
- if err != nil {
- return nil, err
- }
- podServicesMapping, err := getPodServices(clientset, podlist)
- if err != nil {
- return nil, err
- }
- namespaceLabelsMapping, err := getNamespaceLabels(clientset)
- if err != nil {
- return nil, err
- }
- pvClaimMapping, err := getPVInfoVector(resultPVRequests)
- if err != nil {
- return nil, err
- }
- containerNameCost := make(map[string]*CostData)
- containers := make(map[string]bool)
- RAMReqMap, err := getContainerMetricVector(resultRAMRequests, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range RAMReqMap {
- containers[key] = true
- }
- RAMUsedMap, err := getContainerMetricVector(resultRAMUsage, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range RAMUsedMap {
- containers[key] = true
- }
- CPUReqMap, err := getContainerMetricVector(resultCPURequests, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range CPUReqMap {
- containers[key] = true
- }
- GPUReqMap, err := getContainerMetricVector(resultGPURequests, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range GPUReqMap {
- containers[key] = true
- }
- CPUUsedMap, err := getContainerMetricVector(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
- if err != nil {
- return nil, err
- }
- for key := range CPUUsedMap {
- containers[key] = true
- }
- currentContainers := make(map[string]v1.Pod)
- for _, pod := range podlist.Items {
- cs, err := newContainerMetricsFromPod(pod)
- if err != nil {
- return nil, err
- }
- for _, c := range cs {
- 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.
- currentContainers[c.Key()] = pod
- }
- }
- for key := range containers {
- if _, ok := containerNameCost[key]; ok {
- continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
- }
- if pod, ok := currentContainers[key]; ok {
- podName := pod.GetObjectMeta().GetName()
- ns := pod.GetObjectMeta().GetNamespace()
- nsLabels := namespaceLabelsMapping[ns]
- podLabels := pod.GetObjectMeta().GetLabels()
- nodeName := pod.Spec.NodeName
- var nodeData *costAnalyzerCloud.Node
- if _, ok := nodes[nodeName]; ok {
- nodeData = nodes[nodeName]
- }
- var podDeployments []string
- if _, ok := podDeploymentsMapping[ns]; ok {
- if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
- podDeployments = ds
- } else {
- podDeployments = []string{}
- }
- }
- var podPVs []*PersistentVolumeData
- podClaims := pod.Spec.Volumes
- for _, vol := range podClaims {
- if vol.PersistentVolumeClaim != nil {
- name := vol.PersistentVolumeClaim.ClaimName
- if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
- podPVs = append(podPVs, pvClaim)
- }
- }
- }
- var podServices []string
- if _, ok := podServicesMapping[ns]; ok {
- if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
- podServices = svcs
- } else {
- podServices = []string{}
- }
- }
- for i, container := range pod.Spec.Containers {
- containerName := container.Name
- // recreate the key and look up data for this container
- newKey := ns + "," + podName + "," + containerName
- RAMReqV, ok := RAMReqMap[newKey]
- if !ok {
- klog.V(2).Info("no RAM requests for " + newKey)
- RAMReqV = []*Vector{&Vector{}}
- }
- RAMUsedV, ok := RAMUsedMap[newKey]
- if !ok {
- klog.V(2).Info("no RAM usage for " + newKey)
- RAMUsedV = []*Vector{&Vector{}}
- }
- CPUReqV, ok := CPUReqMap[newKey]
- if !ok {
- klog.V(2).Info("no CPU requests for " + newKey)
- CPUReqV = []*Vector{&Vector{}}
- }
- GPUReqV, ok := GPUReqMap[newKey]
- if !ok {
- klog.V(2).Info("no GPU requests for " + newKey)
- GPUReqV = []*Vector{&Vector{}}
- }
- CPUUsedV, ok := CPUUsedMap[newKey]
- if !ok {
- klog.V(2).Info("no CPU usage for " + newKey)
- CPUUsedV = []*Vector{&Vector{}}
- }
- var pvReq []*PersistentVolumeData
- if i == 0 { // avoid duplicating by just assigning all claims to the first container.
- pvReq = podPVs
- }
- costs := &CostData{
- Name: containerName,
- PodName: podName,
- NodeName: nodeName,
- Namespace: ns,
- Deployments: podDeployments,
- Services: podServices,
- Daemonsets: getDaemonsetsOfPod(pod),
- Jobs: getJobsOfPod(pod),
- Statefulsets: getStatefulSetsOfPod(pod),
- NodeData: nodeData,
- RAMReq: RAMReqV,
- RAMUsed: RAMUsedV,
- CPUReq: CPUReqV,
- CPUUsed: CPUUsedV,
- GPUReq: GPUReqV,
- PVData: pvReq,
- Labels: podLabels,
- NamespaceLabels: nsLabels,
- }
- costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
- costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
- containerNameCost[newKey] = costs
- }
- } else {
- // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
- // TODO: The nodename should be available from the prometheus query. Check if that node still exists and use that price
- klog.V(3).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
- c, _ := newContainerMetricFromKey(key)
- RAMReqV, ok := RAMReqMap[key]
- if !ok {
- klog.V(2).Info("no RAM requests for " + key)
- RAMReqV = []*Vector{&Vector{}}
- }
- RAMUsedV, ok := RAMUsedMap[key]
- if !ok {
- klog.V(2).Info("no RAM usage for " + key)
- RAMUsedV = []*Vector{&Vector{}}
- }
- CPUReqV, ok := CPUReqMap[key]
- if !ok {
- klog.V(2).Info("no CPU requests for " + key)
- CPUReqV = []*Vector{&Vector{}}
- }
- GPUReqV, ok := GPUReqMap[key]
- if !ok {
- klog.V(2).Info("no GPU requests for " + key)
- GPUReqV = []*Vector{&Vector{}}
- }
- CPUUsedV, ok := CPUUsedMap[key]
- if !ok {
- klog.V(2).Info("no CPU usage for " + key)
- CPUUsedV = []*Vector{&Vector{}}
- }
- costs := &CostData{ // TODO: Expand the prometheus query/use prometheus to query for more data here if it exists.
- Name: c.ContainerName,
- PodName: c.PodName,
- Namespace: c.Namespace,
- RAMReq: RAMReqV,
- RAMUsed: RAMUsedV,
- CPUReq: CPUReqV,
- CPUUsed: CPUUsedV,
- GPUReq: GPUReqV,
- }
- costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
- costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
- containerNameCost[key] = costs
- }
- }
- return containerNameCost, err
- }
- func getContainerAllocation(req []*Vector, used []*Vector) []*Vector {
- if req == nil || len(req) == 0 {
- return used
- }
- if used == nil || len(used) == 0 {
- return req
- }
- var allocation []*Vector
- var timestamps []float64
- reqMap := make(map[float64]float64)
- for _, reqV := range req {
- if reqV.Timestamp == 0 {
- continue
- }
- reqV.Timestamp = math.Round(reqV.Timestamp/10) * 10
- reqMap[reqV.Timestamp] = reqV.Value
- timestamps = append(timestamps, reqV.Timestamp)
- }
- usedMap := make(map[float64]float64)
- for _, usedV := range used {
- if usedV.Timestamp == 0 {
- continue
- }
- usedV.Timestamp = math.Round(usedV.Timestamp/10) * 10
- usedMap[usedV.Timestamp] = usedV.Value
- if _, ok := reqMap[usedV.Timestamp]; !ok { // no need to double add, since we'll range over sorted timestamps and check.
- timestamps = append(timestamps, usedV.Timestamp)
- }
- }
- sort.Float64s(timestamps)
- for _, t := range timestamps {
- rv, okR := reqMap[t]
- uv, okU := usedMap[t]
- allocationVector := &Vector{
- Timestamp: t,
- }
- if okR && okU {
- allocationVector.Value = math.Max(rv, uv)
- } else if okR {
- allocationVector.Value = rv
- } else if okU {
- allocationVector.Value = uv
- }
- allocation = append(allocation, allocationVector)
- }
- return allocation
- }
- func getNodeCost(clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider) (map[string]*costAnalyzerCloud.Node, error) {
- nodeList, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
- if err != nil {
- return nil, err
- }
- nodes := make(map[string]*costAnalyzerCloud.Node)
- for _, n := range nodeList.Items {
- name := n.GetObjectMeta().GetName()
- nodeLabels := n.GetObjectMeta().GetLabels()
- nodeLabels["providerID"] = n.Spec.ProviderID
- cnode, err := cloud.NodePricing(cloud.GetKey(nodeLabels))
- if err != nil {
- klog.V(1).Infof("Error getting node. Error: " + err.Error())
- continue
- }
- var cpu float64
- if cnode.VCPU == "" {
- cpu = float64(n.Status.Capacity.Cpu().Value())
- cnode.VCPU = n.Status.Capacity.Cpu().String()
- } else {
- cpu, _ = strconv.ParseFloat(cnode.VCPU, 64)
- }
- var ram float64
- if cnode.RAM == "" {
- cnode.RAM = n.Status.Capacity.Memory().String()
- }
- ram = float64(n.Status.Capacity.Memory().Value())
- if cnode.RAMCost == "" { // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
- basePrice, _ := strconv.ParseFloat(cnode.BaseCPUPrice, 64)
- totalCPUPrice := basePrice * cpu
- var nodePrice float64
- if cnode.Cost != "" {
- klog.V(3).Infof("Use given nodeprice as whole node price")
- nodePrice, _ = strconv.ParseFloat(cnode.Cost, 64)
- } else {
- klog.V(3).Infof("Use cpuprice as whole node price")
- nodePrice, _ = strconv.ParseFloat(cnode.VCPUCost, 64) // all the price was allocated the the CPU
- }
- if totalCPUPrice >= nodePrice {
- totalCPUPrice = 0.9 * nodePrice // just allocate RAM costs to 10% of the node price here to avoid 0 or negative in the numerator
- }
- ramPrice := (nodePrice - totalCPUPrice) / (ram / 1024 / 1024 / 1024)
- cpuPrice := totalCPUPrice / cpu
- cnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
- cnode.RAMCost = fmt.Sprintf("%f", ramPrice)
- cnode.RAMBytes = fmt.Sprintf("%f", ram)
- klog.V(2).Infof("Node \"%s\" RAM Cost := %v", name, cnode.RAMCost)
- }
- nodes[name] = cnode
- }
- return nodes, nil
- }
- func getPodServices(clientset kubernetes.Interface, podList *v1.PodList) (map[string]map[string][]string, error) {
- servicesList, err := clientset.CoreV1().Services("").List(metav1.ListOptions{})
- if err != nil {
- return nil, err
- }
- podServicesMapping := make(map[string]map[string][]string)
- for _, service := range servicesList.Items {
- namespace := service.GetObjectMeta().GetNamespace()
- name := service.GetObjectMeta().GetName()
- if _, ok := podServicesMapping[namespace]; !ok {
- podServicesMapping[namespace] = make(map[string][]string)
- }
- s := labels.Set(service.Spec.Selector).AsSelectorPreValidated()
- if err != nil {
- klog.V(2).Infof("Error doing service label conversion: " + err.Error())
- }
- for _, pod := range podList.Items {
- labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
- if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
- services, ok := podServicesMapping[namespace][pod.GetObjectMeta().GetName()]
- if ok {
- podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = append(services, name)
- } else {
- podServicesMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
- }
- }
- }
- }
- return podServicesMapping, nil
- }
- func getPodDeployments(clientset kubernetes.Interface, podList *v1.PodList) (map[string]map[string][]string, error) {
- deploymentsList, err := clientset.AppsV1().Deployments("").List(metav1.ListOptions{})
- if err != nil {
- return nil, err
- }
- podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
- for _, deployment := range deploymentsList.Items {
- namespace := deployment.GetObjectMeta().GetNamespace()
- name := deployment.GetObjectMeta().GetName()
- if _, ok := podDeploymentsMapping[namespace]; !ok {
- podDeploymentsMapping[namespace] = make(map[string][]string)
- }
- s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
- if err != nil {
- klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
- }
- for _, pod := range podList.Items {
- labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
- if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
- deployments, ok := podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()]
- if ok {
- podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = append(deployments, name)
- } else {
- podDeploymentsMapping[namespace][pod.GetObjectMeta().GetName()] = []string{name}
- }
- }
- }
- }
- return podDeploymentsMapping, nil
- }
- func ComputeCostDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cloud costAnalyzerCloud.Provider,
- startString, endString, windowString string) (map[string]*CostData, error) {
- queryRAMRequests := `avg(label_replace(label_replace(avg((count_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD"}[` + windowString + `]) * avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="",container!="POD"}[` + windowString + `]))) by (namespace,container,pod) , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)") ) by (namespace,container_name, pod_name)`
- queryRAMUsage := `sort_desc(avg(count_over_time(container_memory_usage_bytes{container_name!="",container_name!="POD"}[` + windowString + `]) * avg_over_time(container_memory_usage_bytes{container_name!="",container_name!="POD"}[` + windowString + `])) by (namespace,container_name,pod_name,instance))`
- queryCPURequests := `avg(label_replace(label_replace(avg((count_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD"}[` + windowString + `]) * avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="",container!="POD"}[` + windowString + `]))) by (namespace,container,pod) , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)") ) by (namespace,container_name, pod_name)`
- queryCPUUsage := `avg(rate(container_cpu_usage_seconds_total{container_name!="",container_name!="POD"}[` + windowString + `])) by (namespace,container_name,pod_name,instance)`
- queryGPURequests := `avg(label_replace(label_replace(avg((count_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD"}[` + windowString + `]) * avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD"}[` + windowString + `]))) by (namespace,container,pod) , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)") ) by (namespace,container_name, pod_name)`
- queryPVRequests := `avg(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass, namespace)
- *
- on (persistentvolumeclaim, namespace) group_right(storageclass)
- sum(kube_persistentvolumeclaim_resource_requests_storage_bytes) by (persistentvolumeclaim, namespace)`
- normalization := `max(count_over_time(kube_pod_container_resource_requests_memory_bytes{}[` + windowString + `]))`
- layout := "2006-01-02T15:04:05.000Z"
- start, err := time.Parse(layout, startString)
- if err != nil {
- klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
- return nil, err
- }
- end, err := time.Parse(layout, endString)
- if err != nil {
- klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
- return nil, err
- }
- window, err := time.ParseDuration(windowString)
- if err != nil {
- klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
- return nil, err
- }
- resultRAMRequests, err := queryRange(cli, queryRAMRequests, start, end, window)
- if err != nil {
- return nil, fmt.Errorf("Error fetching RAM requests: " + err.Error())
- }
- resultRAMUsage, err := queryRange(cli, queryRAMUsage, start, end, window)
- if err != nil {
- return nil, fmt.Errorf("Error fetching RAM usage: " + err.Error())
- }
- resultCPURequests, err := queryRange(cli, queryCPURequests, start, end, window)
- if err != nil {
- return nil, fmt.Errorf("Error fetching CPU requests: " + err.Error())
- }
- resultCPUUsage, err := queryRange(cli, queryCPUUsage, start, end, window)
- if err != nil {
- return nil, fmt.Errorf("Error fetching CPU usage: " + err.Error())
- }
- resultGPURequests, err := queryRange(cli, queryGPURequests, start, end, window)
- if err != nil {
- return nil, fmt.Errorf("Error fetching GPU requests: " + err.Error())
- }
- resultPVRequests, err := queryRange(cli, queryPVRequests, start, end, window)
- if err != nil {
- return nil, fmt.Errorf("Error fetching PV requests: " + err.Error())
- }
- normalizationResult, err := query(cli, normalization)
- if err != nil {
- return nil, fmt.Errorf("Error fetching normalization data: " + err.Error())
- }
- normalizationValue, err := getNormalization(normalizationResult)
- if err != nil {
- return nil, err
- }
- nodes, err := getNodeCost(clientset, cloud)
- if err != nil {
- //return nil, err
- klog.V(1).Infof("Warning, no cost model available: " + err.Error())
- }
- podlist, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
- if err != nil {
- return nil, err
- }
- podDeploymentsMapping, err := getPodDeployments(clientset, podlist)
- if err != nil {
- return nil, err
- }
- podServicesMapping, err := getPodServices(clientset, podlist)
- if err != nil {
- return nil, err
- }
- namespaceLabelsMapping, err := getNamespaceLabels(clientset)
- if err != nil {
- return nil, err
- }
- pvClaimMapping, err := getPVInfoVectors(resultPVRequests)
- if err != nil {
- return nil, err
- }
- containerNameCost := make(map[string]*CostData)
- containers := make(map[string]bool)
- RAMReqMap, err := getContainerMetricVectors(resultRAMRequests, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range RAMReqMap {
- containers[key] = true
- }
- RAMUsedMap, err := getContainerMetricVectors(resultRAMUsage, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range RAMUsedMap {
- containers[key] = true
- }
- CPUReqMap, err := getContainerMetricVectors(resultCPURequests, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range CPUReqMap {
- containers[key] = true
- }
- GPUReqMap, err := getContainerMetricVectors(resultGPURequests, true, normalizationValue)
- if err != nil {
- return nil, err
- }
- for key := range GPUReqMap {
- containers[key] = true
- }
- CPUUsedMap, err := getContainerMetricVectors(resultCPUUsage, false, 0) // No need to normalize here, as this comes from a counter
- if err != nil {
- return nil, err
- }
- for key := range CPUUsedMap {
- containers[key] = true
- }
- currentContainers := make(map[string]v1.Pod)
- for _, pod := range podlist.Items {
- cs, err := newContainerMetricsFromPod(pod)
- if err != nil {
- return nil, err
- }
- for _, c := range cs {
- 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.
- currentContainers[c.Key()] = pod
- }
- }
- for key := range containers {
- if _, ok := containerNameCost[key]; ok {
- continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
- }
- if pod, ok := currentContainers[key]; ok {
- podName := pod.GetObjectMeta().GetName()
- ns := pod.GetObjectMeta().GetNamespace()
- podLabels := pod.GetObjectMeta().GetLabels()
- nodeName := pod.Spec.NodeName
- var nodeData *costAnalyzerCloud.Node
- if _, ok := nodes[nodeName]; ok {
- nodeData = nodes[nodeName]
- }
- var podDeployments []string
- if _, ok := podDeploymentsMapping[ns]; ok {
- if ds, ok := podDeploymentsMapping[ns][pod.GetObjectMeta().GetName()]; ok {
- podDeployments = ds
- } else {
- podDeployments = []string{}
- }
- }
- var podPVs []*PersistentVolumeData
- podClaims := pod.Spec.Volumes
- for _, vol := range podClaims {
- if vol.PersistentVolumeClaim != nil {
- name := vol.PersistentVolumeClaim.ClaimName
- if pvClaim, ok := pvClaimMapping[ns+","+name]; ok {
- podPVs = append(podPVs, pvClaim)
- }
- }
- }
- var podServices []string
- if _, ok := podServicesMapping[ns]; ok {
- if svcs, ok := podServicesMapping[ns][pod.GetObjectMeta().GetName()]; ok {
- podServices = svcs
- } else {
- podServices = []string{}
- }
- }
- nsLabels := namespaceLabelsMapping[ns]
- for i, container := range pod.Spec.Containers {
- containerName := container.Name
- newKey := ns + "," + podName + "," + containerName
- RAMReqV, ok := RAMReqMap[newKey]
- if !ok {
- klog.V(2).Info("no RAM requests for " + newKey)
- RAMReqV = []*Vector{}
- }
- RAMUsedV, ok := RAMUsedMap[newKey]
- if !ok {
- klog.V(2).Info("no RAM usage for " + newKey)
- RAMUsedV = []*Vector{}
- }
- CPUReqV, ok := CPUReqMap[newKey]
- if !ok {
- klog.V(2).Info("no CPU requests for " + newKey)
- CPUReqV = []*Vector{}
- }
- GPUReqV, ok := GPUReqMap[newKey]
- if !ok {
- klog.V(2).Info("no GPU requests for " + newKey)
- GPUReqV = []*Vector{}
- }
- CPUUsedV, ok := CPUUsedMap[newKey]
- if !ok {
- klog.V(2).Info("no CPU usage for " + newKey)
- CPUUsedV = []*Vector{}
- }
- var pvReq []*PersistentVolumeData
- if i == 0 { // avoid duplicating by just assigning all claims to the first container.
- pvReq = podPVs
- }
- costs := &CostData{
- Name: containerName,
- PodName: podName,
- NodeName: nodeName,
- Namespace: ns,
- Deployments: podDeployments,
- Services: podServices,
- Daemonsets: getDaemonsetsOfPod(pod),
- Jobs: getJobsOfPod(pod),
- Statefulsets: getStatefulSetsOfPod(pod),
- NodeData: nodeData,
- RAMReq: RAMReqV,
- RAMUsed: RAMUsedV,
- CPUReq: CPUReqV,
- CPUUsed: CPUUsedV,
- GPUReq: GPUReqV,
- PVData: pvReq,
- Labels: podLabels,
- NamespaceLabels: nsLabels,
- }
- costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
- costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
- containerNameCost[newKey] = costs
- }
- } else {
- // The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
- // TODO: The nodename should be available from the prometheus query. Check if that node still exists and use that price
- klog.V(3).Info("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
- c, _ := newContainerMetricFromKey(key)
- RAMReqV, ok := RAMReqMap[key]
- if !ok {
- klog.V(2).Info("no RAM requests for " + key)
- RAMReqV = []*Vector{}
- }
- RAMUsedV, ok := RAMUsedMap[key]
- if !ok {
- klog.V(2).Info("no RAM usage for " + key)
- RAMUsedV = []*Vector{}
- }
- CPUReqV, ok := CPUReqMap[key]
- if !ok {
- klog.V(2).Info("no CPU requests for " + key)
- CPUReqV = []*Vector{}
- }
- GPUReqV, ok := GPUReqMap[key]
- if !ok {
- klog.V(2).Info("no GPU requests for " + key)
- GPUReqV = []*Vector{}
- }
- CPUUsedV, ok := CPUUsedMap[key]
- if !ok {
- klog.V(2).Info("no CPU usage for " + key)
- CPUUsedV = []*Vector{}
- }
- costs := &CostData{ // TODO: Expand the prometheus query/use prometheus to query for more data here if it exists.
- Name: c.ContainerName,
- PodName: c.PodName,
- Namespace: c.Namespace,
- RAMReq: RAMReqV,
- RAMUsed: RAMUsedV,
- CPUReq: CPUReqV,
- CPUUsed: CPUUsedV,
- GPUReq: GPUReqV,
- }
- costs.CPUAllocation = getContainerAllocation(costs.CPUReq, costs.CPUUsed)
- costs.RAMAllocation = getContainerAllocation(costs.RAMReq, costs.RAMUsed)
- containerNameCost[key] = costs
- }
- }
- return containerNameCost, err
- }
- func getNamespaceLabels(clientset kubernetes.Interface) (map[string]map[string]string, error) {
- nsToLabels := make(map[string]map[string]string)
- nss, err := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})
- if err != nil {
- return nil, err
- }
- for _, ns := range nss.Items {
- nsToLabels[ns.Name] = ns.Labels
- }
- return nsToLabels, nil
- }
- func getDaemonsetsOfPod(pod v1.Pod) []string {
- for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
- if ownerReference.Kind == "DaemonSet" {
- return []string{ownerReference.Name}
- }
- }
- return []string{}
- }
- func getJobsOfPod(pod v1.Pod) []string {
- for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
- if ownerReference.Kind == "Job" {
- return []string{ownerReference.Name}
- }
- }
- return []string{}
- }
- func getStatefulSetsOfPod(pod v1.Pod) []string {
- for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
- if ownerReference.Kind == "StatefulSet" {
- return []string{ownerReference.Name}
- }
- }
- return []string{}
- }
- type PersistentVolumeData struct {
- Class string `json:"class"`
- Claim string `json:"claim"`
- Namespace string `json:"namespace"`
- Values []*Vector `json:"values"`
- }
- func getPVInfoVectors(qr interface{}) (map[string]*PersistentVolumeData, error) {
- pvmap := make(map[string]*PersistentVolumeData)
- for _, val := range qr.(map[string]interface{})["data"].(map[string]interface{})["result"].([]interface{}) {
- metricInterface, ok := val.(map[string]interface{})["metric"]
- if !ok {
- return nil, fmt.Errorf("Metric field does not exist in data result vector")
- }
- metricMap, ok := metricInterface.(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("Metric field is improperly formatted")
- }
- pvclaim := metricMap["persistentvolumeclaim"]
- pvclass := metricMap["storageclass"]
- pvnamespace := metricMap["namespace"]
- values, ok := val.(map[string]interface{})["values"].([]interface{})
- if !ok {
- return nil, fmt.Errorf("Values field is improperly formatted")
- }
- var vectors []*Vector
- for _, value := range values {
- dataPoint, ok := value.([]interface{})
- if !ok || len(dataPoint) != 2 {
- return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
- }
- strVal := dataPoint[1].(string)
- v, _ := strconv.ParseFloat(strVal, 64)
- vectors = append(vectors, &Vector{
- Timestamp: dataPoint[0].(float64),
- Value: v,
- })
- }
- key := pvnamespace.(string) + "," + pvclaim.(string)
- pvmap[key] = &PersistentVolumeData{
- Class: pvclass.(string),
- Claim: pvclaim.(string),
- Namespace: pvnamespace.(string),
- Values: vectors,
- }
- }
- return pvmap, nil
- }
- func getPVInfoVector(qr interface{}) (map[string]*PersistentVolumeData, error) {
- pvmap := make(map[string]*PersistentVolumeData)
- for _, val := range qr.(map[string]interface{})["data"].(map[string]interface{})["result"].([]interface{}) {
- metricInterface, ok := val.(map[string]interface{})["metric"]
- if !ok {
- return nil, fmt.Errorf("Metric field does not exist in data result vector")
- }
- metricMap, ok := metricInterface.(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("Metric field is improperly formatted")
- }
- pvclaim := metricMap["persistentvolumeclaim"]
- pvclass := metricMap["storageclass"]
- pvnamespace := metricMap["namespace"]
- dataPoint, ok := val.(map[string]interface{})["value"]
- if !ok {
- return nil, fmt.Errorf("Value field does not exist in data result vector")
- }
- value, ok := dataPoint.([]interface{})
- if !ok || len(value) != 2 {
- return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
- }
- var vectors []*Vector
- strVal := value[1].(string)
- v, _ := strconv.ParseFloat(strVal, 64)
- vectors = append(vectors, &Vector{
- Timestamp: value[0].(float64),
- Value: v,
- })
- key := pvclaim.(string) + "," + pvnamespace.(string)
- pvmap[key] = &PersistentVolumeData{
- Class: pvclass.(string),
- Claim: pvclaim.(string),
- Namespace: pvnamespace.(string),
- Values: vectors,
- }
- }
- return pvmap, nil
- }
- func queryRange(cli prometheusClient.Client, query string, start, end time.Time, step time.Duration) (interface{}, error) {
- u := cli.URL(epQueryRange, nil)
- q := u.Query()
- q.Set("query", query)
- q.Set("start", start.Format(time.RFC3339Nano))
- q.Set("end", end.Format(time.RFC3339Nano))
- q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
- u.RawQuery = q.Encode()
- req, err := http.NewRequest(http.MethodGet, u.String(), nil)
- if err != nil {
- return nil, err
- }
- _, body, err := cli.Do(context.Background(), req)
- if err != nil {
- klog.V(1).Infof("ERROR" + err.Error())
- }
- if err != nil {
- return nil, err
- }
- var toReturn interface{}
- err = json.Unmarshal(body, &toReturn)
- if err != nil {
- klog.V(1).Infof("ERROR" + err.Error())
- }
- return toReturn, err
- }
- func query(cli prometheusClient.Client, query string) (interface{}, error) {
- u := cli.URL(epQuery, nil)
- q := u.Query()
- q.Set("query", query)
- u.RawQuery = q.Encode()
- req, err := http.NewRequest(http.MethodGet, u.String(), nil)
- if err != nil {
- return nil, err
- }
- _, body, err := cli.Do(context.Background(), req)
- if err != nil {
- return nil, err
- }
- var toReturn interface{}
- err = json.Unmarshal(body, &toReturn)
- if err != nil {
- klog.V(1).Infof("ERROR" + err.Error())
- }
- return toReturn, err
- }
- //todo: don't cast, implement unmarshaler interface
- func getNormalization(qr interface{}) (float64, error) {
- data, ok := qr.(map[string]interface{})["data"]
- if !ok {
- return 0, fmt.Errorf("Data field not found in normalization response, aborting")
- }
- results, ok := data.(map[string]interface{})["result"].([]interface{})
- if !ok {
- return 0, fmt.Errorf("Result field not found in normalization response, aborting")
- }
- if len(results) > 0 {
- dataPoint := results[0].(map[string]interface{})["value"].([]interface{})
- if len(dataPoint) == 2 {
- strNorm := dataPoint[1].(string)
- val, _ := strconv.ParseFloat(strNorm, 64)
- return val, nil
- }
- return 0, fmt.Errorf("Improperly formatted datapoint from Prometheus")
- }
- return 0, fmt.Errorf("Normalization data is empty, kube-state-metrics or node-exporter may not be running")
- }
- type ContainerMetric struct {
- Namespace string
- PodName string
- ContainerName string
- }
- func (c *ContainerMetric) Key() string {
- return c.Namespace + "," + c.PodName + "," + c.ContainerName
- }
- func newContainerMetricFromKey(key string) (*ContainerMetric, error) {
- s := strings.Split(key, ",")
- if len(s) == 3 {
- return &ContainerMetric{
- Namespace: s[0],
- PodName: s[1],
- ContainerName: s[2],
- }, nil
- }
- return nil, fmt.Errorf("Not a valid key")
- }
- func newContainerMetricsFromPod(pod v1.Pod) ([]*ContainerMetric, error) {
- podName := pod.GetObjectMeta().GetName()
- ns := pod.GetObjectMeta().GetNamespace()
- var cs []*ContainerMetric
- for _, container := range pod.Spec.Containers {
- containerName := container.Name
- cs = append(cs, &ContainerMetric{
- Namespace: ns,
- PodName: podName,
- ContainerName: containerName,
- })
- }
- return cs, nil
- }
- func newContainerMetricFromPrometheus(metrics map[string]interface{}) (*ContainerMetric, error) {
- cName, ok := metrics["container_name"]
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have container name")
- }
- containerName, ok := cName.(string)
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have string container name")
- }
- pName, ok := metrics["pod_name"]
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have pod name")
- }
- podName, ok := pName.(string)
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have string pod name")
- }
- ns, ok := metrics["namespace"]
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have namespace")
- }
- namespace, ok := ns.(string)
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have string namespace")
- }
- return &ContainerMetric{
- ContainerName: containerName,
- PodName: podName,
- Namespace: namespace,
- }, nil
- }
- func getContainerMetricVector(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
- data, ok := qr.(map[string]interface{})["data"]
- if !ok {
- return nil, fmt.Errorf("Improperly formatted response from prometheus, response has no data field")
- }
- r, ok := data.(map[string]interface{})["result"]
- if !ok {
- return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
- }
- results, ok := r.([]interface{})
- if !ok {
- return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
- }
- containerData := make(map[string][]*Vector)
- for _, val := range results {
- metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have metric labels")
- }
- containerMetric, err := newContainerMetricFromPrometheus(metric)
- if err != nil {
- return nil, err
- }
- value, ok := val.(map[string]interface{})["value"]
- if !ok {
- return nil, fmt.Errorf("Improperly formatted results from prometheus, value is not a field in the vector")
- }
- dataPoint, ok := value.([]interface{})
- if !ok || len(dataPoint) != 2 {
- return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
- }
- strVal := dataPoint[1].(string)
- v, _ := strconv.ParseFloat(strVal, 64)
- if normalize && normalizationValue != 0 {
- v = v / normalizationValue
- }
- toReturn := &Vector{
- Timestamp: dataPoint[0].(float64),
- Value: v,
- }
- klog.V(2).Info("key: " + containerMetric.Key())
- containerData[containerMetric.Key()] = []*Vector{toReturn}
- }
- return containerData, nil
- }
- func getContainerMetricVectors(qr interface{}, normalize bool, normalizationValue float64) (map[string][]*Vector, error) {
- data, ok := qr.(map[string]interface{})["data"]
- if !ok {
- return nil, fmt.Errorf("Improperly formatted response from prometheus, response has no data field")
- }
- r, ok := data.(map[string]interface{})["result"]
- if !ok {
- return nil, fmt.Errorf("Improperly formatted data from prometheus, data has no result field")
- }
- results, ok := r.([]interface{})
- if !ok {
- return nil, fmt.Errorf("Improperly formatted results from prometheus, result field is not a slice")
- }
- containerData := make(map[string][]*Vector)
- for _, val := range results {
- metric, ok := val.(map[string]interface{})["metric"].(map[string]interface{})
- if !ok {
- return nil, fmt.Errorf("Prometheus vector does not have metric labels")
- }
- containerMetric, err := newContainerMetricFromPrometheus(metric)
- if err != nil {
- return nil, err
- }
- vs, ok := val.(map[string]interface{})["values"]
- if !ok {
- return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a field in the vector")
- }
- values, ok := vs.([]interface{})
- if !ok {
- return nil, fmt.Errorf("Improperly formatted results from prometheus, values is not a slice")
- }
- var vectors []*Vector
- for _, value := range values {
- dataPoint, ok := value.([]interface{})
- if !ok || len(dataPoint) != 2 {
- return nil, fmt.Errorf("Improperly formatted datapoint from Prometheus")
- }
- strVal := dataPoint[1].(string)
- v, _ := strconv.ParseFloat(strVal, 64)
- if normalize && normalizationValue != 0 {
- v = v / normalizationValue
- }
- vectors = append(vectors, &Vector{
- Timestamp: dataPoint[0].(float64),
- Value: v,
- })
- }
- containerData[containerMetric.Key()] = vectors
- }
- return containerData, nil
- }
|