costmodel.go 88 KB

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