costmodel.go 84 KB

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