costmodel.go 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798
  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. var cpu float64
  1029. if newCnode.VCPU == "" {
  1030. cpu = float64(n.Status.Capacity.Cpu().Value())
  1031. newCnode.VCPU = n.Status.Capacity.Cpu().String()
  1032. } else {
  1033. cpu, err = strconv.ParseFloat(newCnode.VCPU, 64)
  1034. if err != nil {
  1035. klog.V(1).Infof("[Warning] parsing VCPU value: \"%s\" as float64", newCnode.VCPU)
  1036. }
  1037. }
  1038. if math.IsNaN(cpu) {
  1039. klog.V(1).Infof("[Warning] cpu parsed as NaN. Setting to 0.")
  1040. cpu = 0
  1041. }
  1042. var ram float64
  1043. if newCnode.RAM == "" {
  1044. newCnode.RAM = n.Status.Capacity.Memory().String()
  1045. }
  1046. ram = float64(n.Status.Capacity.Memory().Value())
  1047. if math.IsNaN(ram) {
  1048. klog.V(1).Infof("[Warning] ram parsed as NaN. Setting to 0.")
  1049. ram = 0
  1050. }
  1051. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1052. // Azure does not seem to provide a GPU count in its pricing API. GKE supports attaching multiple GPUs
  1053. // 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
  1054. // 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
  1055. gpuc := 0.0
  1056. q, ok := n.Status.Capacity["nvidia.com/gpu"]
  1057. if ok {
  1058. gpuCount := q.Value()
  1059. if gpuCount != 0 {
  1060. newCnode.GPU = fmt.Sprintf("%d", q.Value())
  1061. gpuc = float64(gpuCount)
  1062. }
  1063. } else {
  1064. gpuc, err = strconv.ParseFloat(newCnode.GPU, 64)
  1065. if err != nil {
  1066. gpuc = 0.0
  1067. }
  1068. }
  1069. if math.IsNaN(gpuc) {
  1070. klog.V(1).Infof("[Warning] gpu count parsed as NaN. Setting to 0.")
  1071. gpuc = 0.0
  1072. }
  1073. if newCnode.GPU != "" && newCnode.GPUCost == "" {
  1074. // We couldn't find a gpu cost, so fix cpu and ram, then accordingly
  1075. klog.V(4).Infof("GPU without cost found for %s, calculating...", cp.GetKey(nodeLabels).Features())
  1076. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1077. if err != nil {
  1078. klog.V(3).Infof("Could not parse default cpu price")
  1079. return nil, err
  1080. }
  1081. if math.IsNaN(defaultCPU) {
  1082. klog.V(1).Infof("[Warning] defaultCPU parsed as NaN. Setting to 0.")
  1083. defaultCPU = 0
  1084. }
  1085. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1086. if err != nil {
  1087. klog.V(3).Infof("Could not parse default ram price")
  1088. return nil, err
  1089. }
  1090. if math.IsNaN(defaultRAM) {
  1091. klog.V(1).Infof("[Warning] defaultRAM parsed as NaN. Setting to 0.")
  1092. defaultRAM = 0
  1093. }
  1094. defaultGPU, err := strconv.ParseFloat(cfg.GPU, 64)
  1095. if err != nil {
  1096. klog.V(3).Infof("Could not parse default gpu price")
  1097. return nil, err
  1098. }
  1099. if math.IsNaN(defaultGPU) {
  1100. klog.V(1).Infof("[Warning] defaultGPU parsed as NaN. Setting to 0.")
  1101. defaultGPU = 0
  1102. }
  1103. cpuToRAMRatio := defaultCPU / defaultRAM
  1104. if math.IsNaN(cpuToRAMRatio) {
  1105. klog.V(1).Infof("[Warning] cpuToRAMRatio[defaultCPU: %f / defaultRam: %f] is NaN. Setting to 0.", defaultCPU, defaultRAM)
  1106. cpuToRAMRatio = 0
  1107. }
  1108. gpuToRAMRatio := defaultGPU / defaultRAM
  1109. if math.IsNaN(gpuToRAMRatio) {
  1110. klog.V(1).Infof("[Warning] gpuToRAMRatio is NaN. Setting to 0.")
  1111. gpuToRAMRatio = 0
  1112. }
  1113. ramGB := ram / 1024 / 1024 / 1024
  1114. if math.IsNaN(ramGB) {
  1115. klog.V(1).Infof("[Warning] ramGB is NaN. Setting to 0.")
  1116. ramGB = 0
  1117. }
  1118. ramMultiple := gpuc*gpuToRAMRatio + cpu*cpuToRAMRatio + ramGB
  1119. if math.IsNaN(ramMultiple) {
  1120. klog.V(1).Infof("[Warning] ramMultiple is NaN. Setting to 0.")
  1121. ramMultiple = 0
  1122. }
  1123. var nodePrice float64
  1124. if newCnode.Cost != "" {
  1125. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1126. if err != nil {
  1127. klog.V(3).Infof("Could not parse total node price")
  1128. return nil, err
  1129. }
  1130. } else {
  1131. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  1132. if err != nil {
  1133. klog.V(3).Infof("Could not parse node vcpu price")
  1134. return nil, err
  1135. }
  1136. }
  1137. if math.IsNaN(nodePrice) {
  1138. klog.V(1).Infof("[Warning] nodePrice parsed as NaN. Setting to 0.")
  1139. nodePrice = 0
  1140. }
  1141. ramPrice := (nodePrice / ramMultiple)
  1142. if math.IsNaN(ramPrice) {
  1143. klog.V(1).Infof("[Warning] ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1144. ramPrice = 0
  1145. }
  1146. cpuPrice := ramPrice * cpuToRAMRatio
  1147. gpuPrice := ramPrice * gpuToRAMRatio
  1148. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1149. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1150. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1151. newCnode.GPUCost = fmt.Sprintf("%f", gpuPrice)
  1152. } else if newCnode.RAMCost == "" {
  1153. // We couldn't find a ramcost, so fix cpu and allocate ram accordingly
  1154. klog.V(4).Infof("No RAM cost found for %s, calculating...", cp.GetKey(nodeLabels).Features())
  1155. defaultCPU, err := strconv.ParseFloat(cfg.CPU, 64)
  1156. if err != nil {
  1157. klog.V(3).Infof("Could not parse default cpu price")
  1158. return nil, err
  1159. }
  1160. if math.IsNaN(defaultCPU) {
  1161. klog.V(1).Infof("[Warning] defaultCPU parsed as NaN. Setting to 0.")
  1162. defaultCPU = 0
  1163. }
  1164. defaultRAM, err := strconv.ParseFloat(cfg.RAM, 64)
  1165. if err != nil {
  1166. klog.V(3).Infof("Could not parse default ram price")
  1167. return nil, err
  1168. }
  1169. if math.IsNaN(defaultRAM) {
  1170. klog.V(1).Infof("[Warning] defaultRAM parsed as NaN. Setting to 0.")
  1171. defaultRAM = 0
  1172. }
  1173. cpuToRAMRatio := defaultCPU / defaultRAM
  1174. if math.IsNaN(cpuToRAMRatio) {
  1175. klog.V(1).Infof("[Warning] cpuToRAMRatio[defaultCPU: %f / defaultRam: %f] is NaN. Setting to 0.", defaultCPU, defaultRAM)
  1176. cpuToRAMRatio = 0
  1177. }
  1178. ramGB := ram / 1024 / 1024 / 1024
  1179. if math.IsNaN(ramGB) {
  1180. klog.V(1).Infof("[Warning] ramGB is NaN. Setting to 0.")
  1181. ramGB = 0
  1182. }
  1183. ramMultiple := cpu*cpuToRAMRatio + ramGB
  1184. if math.IsNaN(ramMultiple) {
  1185. klog.V(1).Infof("[Warning] ramMultiple is NaN. Setting to 0.")
  1186. ramMultiple = 0
  1187. }
  1188. var nodePrice float64
  1189. if newCnode.Cost != "" {
  1190. nodePrice, err = strconv.ParseFloat(newCnode.Cost, 64)
  1191. if err != nil {
  1192. klog.V(3).Infof("Could not parse total node price")
  1193. return nil, err
  1194. }
  1195. } else {
  1196. nodePrice, err = strconv.ParseFloat(newCnode.VCPUCost, 64) // all the price was allocated the the CPU
  1197. if err != nil {
  1198. klog.V(3).Infof("Could not parse node vcpu price")
  1199. return nil, err
  1200. }
  1201. }
  1202. if math.IsNaN(nodePrice) {
  1203. klog.V(1).Infof("[Warning] nodePrice parsed as NaN. Setting to 0.")
  1204. nodePrice = 0
  1205. }
  1206. ramPrice := (nodePrice / ramMultiple)
  1207. if math.IsNaN(ramPrice) {
  1208. klog.V(1).Infof("[Warning] ramPrice[nodePrice: %f / ramMultiple: %f] parsed as NaN. Setting to 0.", nodePrice, ramMultiple)
  1209. ramPrice = 0
  1210. }
  1211. cpuPrice := ramPrice * cpuToRAMRatio
  1212. if defaultRAM != 0 {
  1213. newCnode.VCPUCost = fmt.Sprintf("%f", cpuPrice)
  1214. newCnode.RAMCost = fmt.Sprintf("%f", ramPrice)
  1215. } else { // just assign the full price to CPU
  1216. if cpu != 0 {
  1217. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice/cpu)
  1218. } else {
  1219. newCnode.VCPUCost = fmt.Sprintf("%f", nodePrice)
  1220. }
  1221. }
  1222. newCnode.RAMBytes = fmt.Sprintf("%f", ram)
  1223. klog.V(4).Infof("Computed \"%s\" RAM Cost := %v", name, newCnode.RAMCost)
  1224. }
  1225. nodes[name] = &newCnode
  1226. }
  1227. cp.ApplyReservedInstancePricing(nodes)
  1228. return nodes, nil
  1229. }
  1230. func getPodServices(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1231. servicesList := cache.GetAllServices()
  1232. podServicesMapping := make(map[string]map[string][]string)
  1233. for _, service := range servicesList {
  1234. namespace := service.GetObjectMeta().GetNamespace()
  1235. name := service.GetObjectMeta().GetName()
  1236. key := namespace + "," + clusterID
  1237. if _, ok := podServicesMapping[key]; !ok {
  1238. podServicesMapping[key] = make(map[string][]string)
  1239. }
  1240. s := labels.Nothing()
  1241. if service.Spec.Selector != nil && len(service.Spec.Selector) > 0 {
  1242. s = labels.Set(service.Spec.Selector).AsSelectorPreValidated()
  1243. }
  1244. for _, pod := range podList {
  1245. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1246. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1247. services, ok := podServicesMapping[key][pod.GetObjectMeta().GetName()]
  1248. if ok {
  1249. podServicesMapping[key][pod.GetObjectMeta().GetName()] = append(services, name)
  1250. } else {
  1251. podServicesMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1252. }
  1253. }
  1254. }
  1255. }
  1256. return podServicesMapping, nil
  1257. }
  1258. func getPodStatefulsets(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1259. ssList := cache.GetAllStatefulSets()
  1260. podSSMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1261. for _, ss := range ssList {
  1262. namespace := ss.GetObjectMeta().GetNamespace()
  1263. name := ss.GetObjectMeta().GetName()
  1264. key := namespace + "," + clusterID
  1265. if _, ok := podSSMapping[key]; !ok {
  1266. podSSMapping[key] = make(map[string][]string)
  1267. }
  1268. s, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)
  1269. if err != nil {
  1270. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  1271. }
  1272. for _, pod := range podList {
  1273. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1274. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1275. sss, ok := podSSMapping[key][pod.GetObjectMeta().GetName()]
  1276. if ok {
  1277. podSSMapping[key][pod.GetObjectMeta().GetName()] = append(sss, name)
  1278. } else {
  1279. podSSMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return podSSMapping, nil
  1285. }
  1286. func getPodDeployments(cache clustercache.ClusterCache, podList []*v1.Pod, clusterID string) (map[string]map[string][]string, error) {
  1287. deploymentsList := cache.GetAllDeployments()
  1288. podDeploymentsMapping := make(map[string]map[string][]string) // namespace: podName: [deploymentNames]
  1289. for _, deployment := range deploymentsList {
  1290. namespace := deployment.GetObjectMeta().GetNamespace()
  1291. name := deployment.GetObjectMeta().GetName()
  1292. key := namespace + "," + clusterID
  1293. if _, ok := podDeploymentsMapping[key]; !ok {
  1294. podDeploymentsMapping[key] = make(map[string][]string)
  1295. }
  1296. s, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
  1297. if err != nil {
  1298. klog.V(2).Infof("Error doing deployment label conversion: " + err.Error())
  1299. }
  1300. for _, pod := range podList {
  1301. labelSet := labels.Set(pod.GetObjectMeta().GetLabels())
  1302. if s.Matches(labelSet) && pod.GetObjectMeta().GetNamespace() == namespace {
  1303. deployments, ok := podDeploymentsMapping[key][pod.GetObjectMeta().GetName()]
  1304. if ok {
  1305. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = append(deployments, name)
  1306. } else {
  1307. podDeploymentsMapping[key][pod.GetObjectMeta().GetName()] = []string{name}
  1308. }
  1309. }
  1310. }
  1311. }
  1312. return podDeploymentsMapping, nil
  1313. }
  1314. func getPodDeploymentsWithMetrics(deploymentLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1315. podDeploymentsMapping := make(map[string]map[string][]string)
  1316. for depKey, depLabels := range deploymentLabels {
  1317. kt, err := NewKeyTuple(depKey)
  1318. if err != nil {
  1319. continue
  1320. }
  1321. namespace := kt.Namespace
  1322. name := kt.Key
  1323. clusterID := kt.ClusterID
  1324. key := namespace + "," + clusterID
  1325. if _, ok := podDeploymentsMapping[key]; !ok {
  1326. podDeploymentsMapping[key] = make(map[string][]string)
  1327. }
  1328. s := labels.Set(depLabels).AsSelectorPreValidated()
  1329. for podKey, pLabels := range podLabels {
  1330. pkey, err := NewKeyTuple(podKey)
  1331. if err != nil {
  1332. continue
  1333. }
  1334. podNamespace := pkey.Namespace
  1335. podName := pkey.Key
  1336. podClusterID := pkey.ClusterID
  1337. labelSet := labels.Set(pLabels)
  1338. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1339. deployments, ok := podDeploymentsMapping[key][podName]
  1340. if ok {
  1341. podDeploymentsMapping[key][podName] = append(deployments, name)
  1342. } else {
  1343. podDeploymentsMapping[key][podName] = []string{name}
  1344. }
  1345. }
  1346. }
  1347. }
  1348. // Remove any duplicate data created by metric names
  1349. pruneDuplicateData(podDeploymentsMapping)
  1350. return podDeploymentsMapping, nil
  1351. }
  1352. func getPodServicesWithMetrics(serviceLabels map[string]map[string]string, podLabels map[string]map[string]string) (map[string]map[string][]string, error) {
  1353. podServicesMapping := make(map[string]map[string][]string)
  1354. for servKey, servLabels := range serviceLabels {
  1355. kt, err := NewKeyTuple(servKey)
  1356. if err != nil {
  1357. continue
  1358. }
  1359. namespace := kt.Namespace
  1360. name := kt.Key
  1361. clusterID := kt.ClusterID
  1362. key := namespace + "," + clusterID
  1363. if _, ok := podServicesMapping[key]; !ok {
  1364. podServicesMapping[key] = make(map[string][]string)
  1365. }
  1366. s := labels.Nothing()
  1367. if servLabels != nil && len(servLabels) > 0 {
  1368. s = labels.Set(servLabels).AsSelectorPreValidated()
  1369. }
  1370. for podKey, pLabels := range podLabels {
  1371. pkey, err := NewKeyTuple(podKey)
  1372. if err != nil {
  1373. continue
  1374. }
  1375. podNamespace := pkey.Namespace
  1376. podName := pkey.Key
  1377. podClusterID := pkey.ClusterID
  1378. labelSet := labels.Set(pLabels)
  1379. if s.Matches(labelSet) && podNamespace == namespace && podClusterID == clusterID {
  1380. services, ok := podServicesMapping[key][podName]
  1381. if ok {
  1382. podServicesMapping[key][podName] = append(services, name)
  1383. } else {
  1384. podServicesMapping[key][podName] = []string{name}
  1385. }
  1386. }
  1387. }
  1388. }
  1389. // Remove any duplicate data created by metric names
  1390. pruneDuplicateData(podServicesMapping)
  1391. return podServicesMapping, nil
  1392. }
  1393. // This method alleviates an issue with metrics that used a '_' to replace '-' in deployment
  1394. // and service names. To avoid counting these as multiple deployments/services, we'll remove
  1395. // the '_' version. Not optimal, but takes care of the issue
  1396. func pruneDuplicateData(data map[string]map[string][]string) {
  1397. for _, podMap := range data {
  1398. for podName, values := range podMap {
  1399. podMap[podName] = pruneDuplicates(values)
  1400. }
  1401. }
  1402. }
  1403. // Determine if there is an underscore in the value of a slice. If so, replace _ with -, and then
  1404. // check to see if the result exists in the slice. If both are true, then we DO NOT include that
  1405. // original value in the new slice.
  1406. func pruneDuplicates(s []string) []string {
  1407. m := sliceToSet(s)
  1408. for _, v := range s {
  1409. if strings.Contains(v, "_") {
  1410. name := strings.Replace(v, "_", "-", -1)
  1411. if !m[name] {
  1412. m[name] = true
  1413. }
  1414. delete(m, v)
  1415. }
  1416. }
  1417. return setToSlice(m)
  1418. }
  1419. // Creates a map[string]bool containing the slice values as keys
  1420. func sliceToSet(s []string) map[string]bool {
  1421. m := make(map[string]bool)
  1422. for _, v := range s {
  1423. m[v] = true
  1424. }
  1425. return m
  1426. }
  1427. func setToSlice(m map[string]bool) []string {
  1428. var result []string
  1429. for k, _ := range m {
  1430. result = append(result, k)
  1431. }
  1432. return result
  1433. }
  1434. func costDataPassesFilters(costs *CostData, namespace string, cluster string) bool {
  1435. passesNamespace := namespace == "" || costs.Namespace == namespace
  1436. passesCluster := cluster == "" || costs.ClusterID == cluster
  1437. return passesNamespace && passesCluster
  1438. }
  1439. // Finds the a closest multiple less than value
  1440. func floorMultiple(value int64, multiple int64) int64 {
  1441. return (value / multiple) * multiple
  1442. }
  1443. // Attempt to create a key for the request. Reduce the times to minutes in order to more easily group requests based on
  1444. // real time ranges. If for any reason, the key generation fails, return a uuid to ensure uniqueness.
  1445. func requestKeyFor(startString string, endString string, windowString string, filterNamespace string, filterCluster string, remoteEnabled bool) string {
  1446. fullLayout := "2006-01-02T15:04:05.000Z"
  1447. keyLayout := "2006-01-02T15:04Z"
  1448. sTime, err := time.Parse(fullLayout, startString)
  1449. if err != nil {
  1450. klog.V(1).Infof("[Warning] Start=%s failed to parse when generating request key: %s", startString, err.Error())
  1451. return uuid.New().String()
  1452. }
  1453. eTime, err := time.Parse(fullLayout, endString)
  1454. if err != nil {
  1455. klog.V(1).Infof("[Warning] End=%s failed to parse when generating request key: %s", endString, err.Error())
  1456. return uuid.New().String()
  1457. }
  1458. // We "snap" start time and duration to their closest 5 min multiple less than itself, by
  1459. // applying a snapped duration to a snapped start time.
  1460. durMins := int64(eTime.Sub(sTime).Minutes())
  1461. durMins = floorMultiple(durMins, 5)
  1462. sMins := int64(sTime.Minute())
  1463. sOffset := sMins - floorMultiple(sMins, 5)
  1464. sTime = sTime.Add(-time.Duration(sOffset) * time.Minute)
  1465. eTime = sTime.Add(time.Duration(durMins) * time.Minute)
  1466. startKey := sTime.Format(keyLayout)
  1467. endKey := eTime.Format(keyLayout)
  1468. return fmt.Sprintf("%s,%s,%s,%s,%s,%t", startKey, endKey, windowString, filterNamespace, filterCluster, remoteEnabled)
  1469. }
  1470. // Executes a range query for cost data
  1471. func (cm *CostModel) ComputeCostDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cp costAnalyzerCloud.Provider,
  1472. startString, endString, windowString string, resolutionHours float64, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1473. // Create a request key for request grouping. This key will be used to represent the cost-model result
  1474. // for the specific inputs to prevent multiple queries for identical data.
  1475. key := requestKeyFor(startString, endString, windowString, filterNamespace, filterCluster, remoteEnabled)
  1476. klog.V(4).Infof("ComputeCostDataRange with Key: %s", key)
  1477. // If there is already a request out that uses the same data, wait for it to return to share the results.
  1478. // Otherwise, start executing.
  1479. result, err, _ := cm.RequestGroup.Do(key, func() (interface{}, error) {
  1480. return cm.costDataRange(cli, clientset, cp, startString, endString, windowString, resolutionHours, filterNamespace, filterCluster, remoteEnabled)
  1481. })
  1482. data, ok := result.(map[string]*CostData)
  1483. if !ok {
  1484. return nil, fmt.Errorf("Failed to cast result as map[string]*CostData")
  1485. }
  1486. return data, err
  1487. }
  1488. func (cm *CostModel) costDataRange(cli prometheusClient.Client, clientset kubernetes.Interface, cp costAnalyzerCloud.Provider,
  1489. startString, endString, windowString string, resolutionHours float64, filterNamespace string, filterCluster string, remoteEnabled bool) (map[string]*CostData, error) {
  1490. // Use a heuristic to tell the difference between missed scrapes and an incomplete window
  1491. // of data due to fresh install, etc.
  1492. minimumExpectedScrapeRate := 0.95
  1493. queryRAMAlloc := fmt.Sprintf(queryRAMAllocationByteHours, windowString, windowString, resolutionHours, windowString, minimumExpectedScrapeRate)
  1494. queryCPUAlloc := fmt.Sprintf(queryCPUAllocationVCPUHours, windowString, windowString, resolutionHours, windowString, minimumExpectedScrapeRate)
  1495. queryRAMRequests := fmt.Sprintf(queryRAMRequestsStr, windowString, "", windowString, "")
  1496. queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, windowString, "", windowString, "")
  1497. queryCPURequests := fmt.Sprintf(queryCPURequestsStr, windowString, "", windowString, "")
  1498. queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, windowString, "")
  1499. queryGPURequests := fmt.Sprintf(queryGPURequestsStr, windowString, "", windowString, "", resolutionHours, windowString, "")
  1500. queryPVRequests := fmt.Sprintf(queryPVRequestsStr)
  1501. queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, windowString, "")
  1502. queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, windowString, "")
  1503. queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, windowString, "")
  1504. normalization := fmt.Sprintf(normalizationStr, windowString, "")
  1505. layout := "2006-01-02T15:04:05.000Z"
  1506. start, err := time.Parse(layout, startString)
  1507. if err != nil {
  1508. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1509. return nil, err
  1510. }
  1511. end, err := time.Parse(layout, endString)
  1512. if err != nil {
  1513. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1514. return nil, err
  1515. }
  1516. window, err := time.ParseDuration(windowString)
  1517. if err != nil {
  1518. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1519. return nil, err
  1520. }
  1521. clusterID := os.Getenv(clusterIDKey)
  1522. durHrs := end.Sub(start).Hours() + 1
  1523. if remoteEnabled == true {
  1524. remoteLayout := "2006-01-02T15:04:05Z"
  1525. remoteStartStr := start.Format(remoteLayout)
  1526. remoteEndStr := end.Format(remoteLayout)
  1527. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  1528. return CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  1529. }
  1530. numQueries := 21
  1531. var wg sync.WaitGroup
  1532. wg.Add(numQueries)
  1533. queryProfileStart := time.Now()
  1534. queryProfileCh := make(chan string, numQueries)
  1535. var ec ErrorCollector
  1536. var resultRAMRequests interface{}
  1537. go func() {
  1538. defer wg.Done()
  1539. defer measureTimeAsync(time.Now(), profileThreshold, "RAMRequests", queryProfileCh)
  1540. var promErr error
  1541. resultRAMRequests, promErr = QueryRange(cli, queryRAMRequests, start, end, window)
  1542. ec.Report(promErr)
  1543. }()
  1544. var resultRAMUsage interface{}
  1545. go func() {
  1546. defer wg.Done()
  1547. defer measureTimeAsync(time.Now(), profileThreshold, "RAMUsage", queryProfileCh)
  1548. var promErr error
  1549. resultRAMUsage, promErr = QueryRange(cli, queryRAMUsage, start, end, window)
  1550. ec.Report(promErr)
  1551. }()
  1552. var resultCPURequests interface{}
  1553. go func() {
  1554. defer wg.Done()
  1555. defer measureTimeAsync(time.Now(), profileThreshold, "CPURequests", queryProfileCh)
  1556. var promErr error
  1557. resultCPURequests, promErr = QueryRange(cli, queryCPURequests, start, end, window)
  1558. ec.Report(promErr)
  1559. }()
  1560. var resultCPUUsage interface{}
  1561. go func() {
  1562. defer wg.Done()
  1563. defer measureTimeAsync(time.Now(), profileThreshold, "CPUUsage", queryProfileCh)
  1564. var promErr error
  1565. resultCPUUsage, promErr = QueryRange(cli, queryCPUUsage, start, end, window)
  1566. ec.Report(promErr)
  1567. }()
  1568. var resultRAMAllocations interface{}
  1569. go func() {
  1570. defer wg.Done()
  1571. defer measureTimeAsync(time.Now(), profileThreshold, "RAMAllocations", queryProfileCh)
  1572. var promErr error
  1573. resultRAMAllocations, promErr = QueryRange(cli, queryRAMAlloc, start, end, window)
  1574. ec.Report(promErr)
  1575. }()
  1576. var resultCPUAllocations interface{}
  1577. go func() {
  1578. defer wg.Done()
  1579. defer measureTimeAsync(time.Now(), profileThreshold, "CPUAllocations", queryProfileCh)
  1580. var promErr error
  1581. resultCPUAllocations, promErr = QueryRange(cli, queryCPUAlloc, start, end, window)
  1582. ec.Report(promErr)
  1583. }()
  1584. var resultGPURequests interface{}
  1585. go func() {
  1586. defer wg.Done()
  1587. defer measureTimeAsync(time.Now(), profileThreshold, "GPURequests", queryProfileCh)
  1588. var promErr error
  1589. resultGPURequests, promErr = QueryRange(cli, queryGPURequests, start, end, window)
  1590. ec.Report(promErr)
  1591. }()
  1592. var resultPVRequests interface{}
  1593. go func() {
  1594. defer wg.Done()
  1595. defer measureTimeAsync(time.Now(), profileThreshold, "PVRequests", queryProfileCh)
  1596. var promErr error
  1597. resultPVRequests, promErr = QueryRange(cli, queryPVRequests, start, end, window)
  1598. ec.Report(promErr)
  1599. }()
  1600. var resultNetZoneRequests interface{}
  1601. go func() {
  1602. defer wg.Done()
  1603. defer measureTimeAsync(time.Now(), profileThreshold, "NetZoneRequests", queryProfileCh)
  1604. var promErr error
  1605. resultNetZoneRequests, promErr = QueryRange(cli, queryNetZoneRequests, start, end, window)
  1606. ec.Report(promErr)
  1607. }()
  1608. var resultNetRegionRequests interface{}
  1609. go func() {
  1610. defer wg.Done()
  1611. defer measureTimeAsync(time.Now(), profileThreshold, "NetRegionRequests", queryProfileCh)
  1612. var promErr error
  1613. resultNetRegionRequests, promErr = QueryRange(cli, queryNetRegionRequests, start, end, window)
  1614. ec.Report(promErr)
  1615. }()
  1616. var resultNetInternetRequests interface{}
  1617. go func() {
  1618. defer wg.Done()
  1619. defer measureTimeAsync(time.Now(), profileThreshold, "NetInternetRequests", queryProfileCh)
  1620. var promErr error
  1621. resultNetInternetRequests, promErr = QueryRange(cli, queryNetInternetRequests, start, end, window)
  1622. ec.Report(promErr)
  1623. }()
  1624. var pvPodAllocationResults interface{}
  1625. go func() {
  1626. defer wg.Done()
  1627. defer measureTimeAsync(time.Now(), profileThreshold, "PVPodAllocation", queryProfileCh)
  1628. var promErr error
  1629. pvPodAllocationResults, promErr = QueryRange(cli, fmt.Sprintf(queryPVCAllocation, windowString), start, end, window)
  1630. ec.Report(promErr)
  1631. }()
  1632. var pvCostResults interface{}
  1633. go func() {
  1634. defer wg.Done()
  1635. defer measureTimeAsync(time.Now(), profileThreshold, "PVCost", queryProfileCh)
  1636. var promErr error
  1637. pvCostResults, promErr = QueryRange(cli, fmt.Sprintf(queryPVHourlyCost, windowString), start, end, window)
  1638. ec.Report(promErr)
  1639. }()
  1640. var nsLabelsResults interface{}
  1641. go func() {
  1642. defer wg.Done()
  1643. defer measureTimeAsync(time.Now(), profileThreshold, "NSLabels", queryProfileCh)
  1644. var promErr error
  1645. nsLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryNSLabels, windowString), start, end, window)
  1646. ec.Report(promErr)
  1647. }()
  1648. var podLabelsResults interface{}
  1649. go func() {
  1650. defer wg.Done()
  1651. defer measureTimeAsync(time.Now(), profileThreshold, "PodLabels", queryProfileCh)
  1652. var promErr error
  1653. podLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryPodLabels, windowString), start, end, window)
  1654. ec.Report(promErr)
  1655. }()
  1656. var serviceLabelsResults interface{}
  1657. go func() {
  1658. defer wg.Done()
  1659. defer measureTimeAsync(time.Now(), profileThreshold, "ServiceLabels", queryProfileCh)
  1660. var promErr error
  1661. serviceLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryServiceLabels, windowString), start, end, window)
  1662. ec.Report(promErr)
  1663. }()
  1664. var deploymentLabelsResults interface{}
  1665. go func() {
  1666. defer wg.Done()
  1667. defer measureTimeAsync(time.Now(), profileThreshold, "DeploymentLabels", queryProfileCh)
  1668. var promErr error
  1669. deploymentLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryDeploymentLabels, windowString), start, end, window)
  1670. ec.Report(promErr)
  1671. }()
  1672. var daemonsetResults interface{}
  1673. go func() {
  1674. defer wg.Done()
  1675. defer measureTimeAsync(time.Now(), profileThreshold, "Daemonsets", queryProfileCh)
  1676. var promErr error
  1677. daemonsetResults, promErr = QueryRange(cli, fmt.Sprintf(queryPodDaemonsets), start, end, window)
  1678. ec.Report(promErr)
  1679. }()
  1680. var statefulsetLabelsResults interface{}
  1681. go func() {
  1682. defer wg.Done()
  1683. defer measureTimeAsync(time.Now(), profileThreshold, "StatefulSetLabels", queryProfileCh)
  1684. var promErr error
  1685. statefulsetLabelsResults, promErr = QueryRange(cli, fmt.Sprintf(queryStatefulsetLabels, windowString), start, end, window)
  1686. ec.Report(promErr)
  1687. }()
  1688. var normalizationResults interface{}
  1689. go func() {
  1690. defer wg.Done()
  1691. defer measureTimeAsync(time.Now(), profileThreshold, "Normalization", queryProfileCh)
  1692. var promErr error
  1693. normalizationResults, promErr = QueryRange(cli, normalization, start, end, window)
  1694. ec.Report(promErr)
  1695. }()
  1696. podDeploymentsMapping := make(map[string]map[string][]string)
  1697. podStatefulsetsMapping := make(map[string]map[string][]string)
  1698. podServicesMapping := make(map[string]map[string][]string)
  1699. namespaceLabelsMapping := make(map[string]map[string]string)
  1700. podlist := cm.Cache.GetAllPods()
  1701. var k8sErr error
  1702. go func() {
  1703. defer wg.Done()
  1704. podDeploymentsMapping, k8sErr = getPodDeployments(cm.Cache, podlist, clusterID)
  1705. if k8sErr != nil {
  1706. return
  1707. }
  1708. podStatefulsetsMapping, k8sErr = getPodStatefulsets(cm.Cache, podlist, clusterID)
  1709. if k8sErr != nil {
  1710. return
  1711. }
  1712. podServicesMapping, k8sErr = getPodServices(cm.Cache, podlist, clusterID)
  1713. if k8sErr != nil {
  1714. return
  1715. }
  1716. namespaceLabelsMapping, k8sErr = getNamespaceLabels(cm.Cache, clusterID)
  1717. if k8sErr != nil {
  1718. return
  1719. }
  1720. }()
  1721. wg.Wait()
  1722. // collect all query profiling messages
  1723. close(queryProfileCh)
  1724. queryProfileBreakdown := ""
  1725. for msg := range queryProfileCh {
  1726. queryProfileBreakdown += "\n - " + msg
  1727. }
  1728. measureTime(queryProfileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): Prom/k8s Queries: %s", durHrs, queryProfileBreakdown))
  1729. defer measureTime(time.Now(), profileThreshold, fmt.Sprintf("costDataRange(%fh): Processing Query Data", durHrs))
  1730. if ec.IsError() {
  1731. for _, promErr := range ec.Errors() {
  1732. klog.V(1).Infof("[Warning] Query Error: %s", promErr.Error())
  1733. }
  1734. // TODO: Categorize fatal prometheus query failures
  1735. // return nil, fmt.Errorf("Error querying prometheus: %s", promErr.Error())
  1736. }
  1737. if k8sErr != nil {
  1738. return nil, fmt.Errorf("Error querying the kubernetes api: %s", k8sErr.Error())
  1739. }
  1740. profileStart := time.Now()
  1741. normalizationValue, err := getNormalizations(normalizationResults)
  1742. if err != nil {
  1743. return nil, fmt.Errorf("error computing normalization %s for start=%s, end=%s, window=%s, res=%f: %s", normalization,
  1744. start, end, window, resolutionHours*60*60, err.Error())
  1745. }
  1746. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): compute normalizations", durHrs))
  1747. profileStart = time.Now()
  1748. pvClaimMapping, err := GetPVInfo(resultPVRequests, clusterID)
  1749. if err != nil {
  1750. // Just log for compatibility with KSM less than 1.6
  1751. klog.Infof("Unable to get PV Data: %s", err.Error())
  1752. }
  1753. if pvClaimMapping != nil {
  1754. err = addPVData(cm.Cache, pvClaimMapping, cp)
  1755. if err != nil {
  1756. return nil, err
  1757. }
  1758. }
  1759. pvCostMapping, err := GetPVCostMetrics(pvCostResults, clusterID)
  1760. if err != nil {
  1761. klog.V(1).Infof("Unable to get PV Hourly Cost Data: %s", err.Error())
  1762. }
  1763. unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
  1764. pvAllocationMapping, err := GetPVAllocationMetrics(pvPodAllocationResults, clusterID)
  1765. if err != nil {
  1766. klog.V(1).Infof("Unable to get PV Allocation Cost Data: %s", err.Error())
  1767. }
  1768. if pvAllocationMapping != nil {
  1769. addMetricPVData(pvAllocationMapping, pvCostMapping, cp)
  1770. for k, v := range pvAllocationMapping {
  1771. unmountedPVs[k] = v
  1772. }
  1773. }
  1774. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): process PV data", durHrs))
  1775. profileStart = time.Now()
  1776. nsLabels, err := GetNamespaceLabelsMetrics(nsLabelsResults, clusterID)
  1777. if err != nil {
  1778. klog.V(1).Infof("Unable to get Namespace Labels for Metrics: %s", err.Error())
  1779. }
  1780. if nsLabels != nil {
  1781. appendNamespaceLabels(namespaceLabelsMapping, nsLabels)
  1782. }
  1783. podLabels, err := GetPodLabelsMetrics(podLabelsResults, clusterID)
  1784. if err != nil {
  1785. klog.V(1).Infof("Unable to get Pod Labels for Metrics: %s", err.Error())
  1786. }
  1787. serviceLabels, err := GetServiceSelectorLabelsMetrics(serviceLabelsResults, clusterID)
  1788. if err != nil {
  1789. klog.V(1).Infof("Unable to get Service Selector Labels for Metrics: %s", err.Error())
  1790. }
  1791. deploymentLabels, err := GetDeploymentMatchLabelsMetrics(deploymentLabelsResults, clusterID)
  1792. if err != nil {
  1793. klog.V(1).Infof("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1794. }
  1795. statefulsetLabels, err := GetStatefulsetMatchLabelsMetrics(statefulsetLabelsResults, clusterID)
  1796. if err != nil {
  1797. klog.V(1).Infof("Unable to get Deployment Match Labels for Metrics: %s", err.Error())
  1798. }
  1799. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): process labels", durHrs))
  1800. profileStart = time.Now()
  1801. podStatefulsetMetricsMapping, err := getPodDeploymentsWithMetrics(statefulsetLabels, podLabels)
  1802. if err != nil {
  1803. klog.V(1).Infof("Unable to get match Statefulset Labels Metrics to Pods: %s", err.Error())
  1804. }
  1805. appendLabelsList(podStatefulsetsMapping, podStatefulsetMetricsMapping)
  1806. podDeploymentsMetricsMapping, err := getPodDeploymentsWithMetrics(deploymentLabels, podLabels)
  1807. if err != nil {
  1808. klog.V(1).Infof("Unable to get match Deployment Labels Metrics to Pods: %s", err.Error())
  1809. }
  1810. appendLabelsList(podDeploymentsMapping, podDeploymentsMetricsMapping)
  1811. podDaemonsets, err := GetPodDaemonsetsWithMetrics(daemonsetResults, clusterID)
  1812. if err != nil {
  1813. klog.V(1).Infof("Unable to get Pod Daemonsets for Metrics: %s", err.Error())
  1814. }
  1815. podServicesMetricsMapping, err := getPodServicesWithMetrics(serviceLabels, podLabels)
  1816. if err != nil {
  1817. klog.V(1).Infof("Unable to get match Service Labels Metrics to Pods: %s", err.Error())
  1818. }
  1819. appendLabelsList(podServicesMapping, podServicesMetricsMapping)
  1820. networkUsageMap, err := GetNetworkUsageData(resultNetZoneRequests, resultNetRegionRequests, resultNetInternetRequests, clusterID)
  1821. if err != nil {
  1822. klog.V(1).Infof("Unable to get Network Cost Data: %s", err.Error())
  1823. networkUsageMap = make(map[string]*NetworkUsageData)
  1824. }
  1825. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): process deployments, services, and network usage", durHrs))
  1826. profileStart = time.Now()
  1827. containerNameCost := make(map[string]*CostData)
  1828. containers := make(map[string]bool)
  1829. otherClusterPVRecorded := make(map[string]bool)
  1830. RAMReqMap, err := GetNormalizedContainerMetricVectors(resultRAMRequests, normalizationValue, clusterID)
  1831. if err != nil {
  1832. return nil, err
  1833. }
  1834. for key := range RAMReqMap {
  1835. containers[key] = true
  1836. }
  1837. RAMUsedMap, err := GetNormalizedContainerMetricVectors(resultRAMUsage, normalizationValue, clusterID)
  1838. if err != nil {
  1839. return nil, err
  1840. }
  1841. for key := range RAMUsedMap {
  1842. containers[key] = true
  1843. }
  1844. CPUReqMap, err := GetNormalizedContainerMetricVectors(resultCPURequests, normalizationValue, clusterID)
  1845. if err != nil {
  1846. return nil, err
  1847. }
  1848. for key := range CPUReqMap {
  1849. containers[key] = true
  1850. }
  1851. // No need to normalize here, as this comes from a counter, namely:
  1852. // rate(container_cpu_usage_seconds_total) which properly accounts for normalized rates
  1853. CPUUsedMap, err := GetContainerMetricVectors(resultCPUUsage, clusterID)
  1854. if err != nil {
  1855. return nil, err
  1856. }
  1857. for key := range CPUUsedMap {
  1858. containers[key] = true
  1859. }
  1860. RAMAllocMap, err := GetContainerMetricVectors(resultRAMAllocations, clusterID)
  1861. if err != nil {
  1862. return nil, err
  1863. }
  1864. for key := range RAMAllocMap {
  1865. containers[key] = true
  1866. }
  1867. CPUAllocMap, err := GetContainerMetricVectors(resultCPUAllocations, clusterID)
  1868. if err != nil {
  1869. return nil, err
  1870. }
  1871. for key := range CPUAllocMap {
  1872. containers[key] = true
  1873. }
  1874. GPUReqMap, err := GetNormalizedContainerMetricVectors(resultGPURequests, normalizationValue, clusterID)
  1875. if err != nil {
  1876. return nil, err
  1877. }
  1878. for key := range GPUReqMap {
  1879. containers[key] = true
  1880. }
  1881. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): GetContainerMetricVectors", durHrs))
  1882. profileStart = time.Now()
  1883. // Request metrics can show up after pod eviction and completion.
  1884. // This method synchronizes requests to allocations such that when
  1885. // allocation is 0, so are requests
  1886. applyAllocationToRequests(RAMAllocMap, RAMReqMap)
  1887. applyAllocationToRequests(CPUAllocMap, CPUReqMap)
  1888. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): applyAllocationToRequests", durHrs))
  1889. profileStart = time.Now()
  1890. missingNodes := make(map[string]*costAnalyzerCloud.Node)
  1891. missingContainers := make(map[string]*CostData)
  1892. for key := range containers {
  1893. if _, ok := containerNameCost[key]; ok {
  1894. continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
  1895. }
  1896. c, _ := NewContainerMetricFromKey(key)
  1897. RAMReqV, ok := RAMReqMap[key]
  1898. if !ok {
  1899. klog.V(4).Info("no RAM requests for " + key)
  1900. RAMReqV = []*util.Vector{}
  1901. }
  1902. RAMUsedV, ok := RAMUsedMap[key]
  1903. if !ok {
  1904. klog.V(4).Info("no RAM usage for " + key)
  1905. RAMUsedV = []*util.Vector{}
  1906. }
  1907. CPUReqV, ok := CPUReqMap[key]
  1908. if !ok {
  1909. klog.V(4).Info("no CPU requests for " + key)
  1910. CPUReqV = []*util.Vector{}
  1911. }
  1912. CPUUsedV, ok := CPUUsedMap[key]
  1913. if !ok {
  1914. klog.V(4).Info("no CPU usage for " + key)
  1915. CPUUsedV = []*util.Vector{}
  1916. }
  1917. RAMAllocsV, ok := RAMAllocMap[key]
  1918. if !ok {
  1919. klog.V(4).Info("no RAM allocation for " + key)
  1920. RAMAllocsV = []*util.Vector{}
  1921. }
  1922. CPUAllocsV, ok := CPUAllocMap[key]
  1923. if !ok {
  1924. klog.V(4).Info("no CPU allocation for " + key)
  1925. CPUAllocsV = []*util.Vector{}
  1926. }
  1927. GPUReqV, ok := GPUReqMap[key]
  1928. if !ok {
  1929. klog.V(4).Info("no GPU requests for " + key)
  1930. GPUReqV = []*util.Vector{}
  1931. }
  1932. var node *costAnalyzerCloud.Node
  1933. if n, ok := missingNodes[c.NodeName]; ok {
  1934. node = n
  1935. } else {
  1936. node = &costAnalyzerCloud.Node{}
  1937. missingNodes[c.NodeName] = node
  1938. }
  1939. nsKey := c.Namespace + "," + c.ClusterID
  1940. podKey := c.Namespace + "," + c.PodName + "," + c.ClusterID
  1941. namespaceLabels, ok := namespaceLabelsMapping[nsKey]
  1942. if !ok {
  1943. klog.V(3).Infof("Missing data for namespace %s", c.Namespace)
  1944. }
  1945. pLabels := podLabels[podKey]
  1946. if pLabels == nil {
  1947. pLabels = make(map[string]string)
  1948. }
  1949. for k, v := range namespaceLabels {
  1950. pLabels[k] = v
  1951. }
  1952. var podDeployments []string
  1953. if _, ok := podDeploymentsMapping[nsKey]; ok {
  1954. if ds, ok := podDeploymentsMapping[nsKey][c.PodName]; ok {
  1955. podDeployments = ds
  1956. } else {
  1957. podDeployments = []string{}
  1958. }
  1959. }
  1960. var podStatefulSets []string
  1961. if _, ok := podStatefulsetsMapping[nsKey]; ok {
  1962. if ss, ok := podStatefulsetsMapping[nsKey][c.PodName]; ok {
  1963. podStatefulSets = ss
  1964. } else {
  1965. podStatefulSets = []string{}
  1966. }
  1967. }
  1968. var podServices []string
  1969. if _, ok := podServicesMapping[nsKey]; ok {
  1970. if svcs, ok := podServicesMapping[nsKey][c.PodName]; ok {
  1971. podServices = svcs
  1972. } else {
  1973. podServices = []string{}
  1974. }
  1975. }
  1976. var podPVs []*PersistentVolumeClaimData
  1977. var podNetCosts []*util.Vector
  1978. // For PVC data, we'll need to find the claim mapping and cost data. Will need to append
  1979. // cost data since that was populated by cluster data previously. We do this with
  1980. // the pod_pvc_allocation metric
  1981. podPVData, ok := pvAllocationMapping[podKey]
  1982. if !ok {
  1983. klog.V(4).Infof("Failed to locate pv allocation mapping for missing pod.")
  1984. }
  1985. // Delete the current pod key from potentially unmounted pvs
  1986. delete(unmountedPVs, podKey)
  1987. // For network costs, we'll use existing map since it should still contain the
  1988. // correct data.
  1989. var podNetworkCosts []*util.Vector
  1990. if usage, ok := networkUsageMap[podKey]; ok {
  1991. netCosts, err := GetNetworkCost(usage, cp)
  1992. if err != nil {
  1993. klog.V(3).Infof("Error pulling network costs: %s", err.Error())
  1994. } else {
  1995. podNetworkCosts = netCosts
  1996. }
  1997. }
  1998. // Check to see if any other data has been recorded for this namespace, pod, clusterId
  1999. // Follow the pattern of only allowing claims data per pod
  2000. if !otherClusterPVRecorded[podKey] {
  2001. otherClusterPVRecorded[podKey] = true
  2002. podPVs = podPVData
  2003. podNetCosts = podNetworkCosts
  2004. }
  2005. pds := []string{}
  2006. if ds, ok := podDaemonsets[podKey]; ok {
  2007. pds = []string{ds}
  2008. }
  2009. costs := &CostData{
  2010. Name: c.ContainerName,
  2011. PodName: c.PodName,
  2012. NodeName: c.NodeName,
  2013. NodeData: node,
  2014. Namespace: c.Namespace,
  2015. Services: podServices,
  2016. Deployments: podDeployments,
  2017. Daemonsets: pds,
  2018. Statefulsets: podStatefulSets,
  2019. RAMReq: RAMReqV,
  2020. RAMUsed: RAMUsedV,
  2021. CPUReq: CPUReqV,
  2022. CPUUsed: CPUUsedV,
  2023. RAMAllocation: RAMAllocsV,
  2024. CPUAllocation: CPUAllocsV,
  2025. GPUReq: GPUReqV,
  2026. Labels: pLabels,
  2027. NamespaceLabels: namespaceLabels,
  2028. PVCData: podPVs,
  2029. NetworkData: podNetCosts,
  2030. ClusterID: c.ClusterID,
  2031. }
  2032. if costDataPassesFilters(costs, filterNamespace, filterCluster) {
  2033. containerNameCost[key] = costs
  2034. missingContainers[key] = costs
  2035. }
  2036. }
  2037. measureTime(profileStart, profileThreshold, fmt.Sprintf("costDataRange(%fh): build CostData map", durHrs))
  2038. unmounted := findUnmountedPVCostData(unmountedPVs, namespaceLabelsMapping)
  2039. for k, costs := range unmounted {
  2040. klog.V(3).Infof("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
  2041. if costDataPassesFilters(costs, filterNamespace, filterCluster) {
  2042. containerNameCost[k] = costs
  2043. }
  2044. }
  2045. w := end.Sub(start)
  2046. w += window
  2047. if w.Minutes() > 0 {
  2048. wStr := fmt.Sprintf("%dm", int(w.Minutes()))
  2049. err = findDeletedNodeInfo(cli, missingNodes, wStr)
  2050. if err != nil {
  2051. klog.V(1).Infof("Error fetching historical node data: %s", err.Error())
  2052. }
  2053. }
  2054. return containerNameCost, err
  2055. }
  2056. func applyAllocationToRequests(allocationMap map[string][]*util.Vector, requestMap map[string][]*util.Vector) {
  2057. // The result of the normalize operation will be a new []*util.Vector to replace the requests
  2058. normalizeOp := func(r *util.Vector, x *float64, y *float64) bool {
  2059. // Omit data (return false) if both x and y inputs don't exist
  2060. if x == nil || y == nil {
  2061. return false
  2062. }
  2063. // If the allocation value is 0, 0 out request value
  2064. if *x == 0 {
  2065. r.Value = 0
  2066. } else {
  2067. r.Value = *y
  2068. }
  2069. return true
  2070. }
  2071. // Run normalization on all request vectors in the mapping
  2072. for k, requests := range requestMap {
  2073. // Only run normalization where there are valid allocations
  2074. allocations, ok := allocationMap[k]
  2075. if !ok {
  2076. delete(requestMap, k)
  2077. continue
  2078. }
  2079. // Replace request map with normalized
  2080. requestMap[k] = util.ApplyVectorOp(allocations, requests, normalizeOp)
  2081. }
  2082. }
  2083. func addMetricPVData(pvAllocationMap map[string][]*PersistentVolumeClaimData, pvCostMap map[string]*costAnalyzerCloud.PV, cp costAnalyzerCloud.Provider) {
  2084. cfg, err := cp.GetConfig()
  2085. if err != nil {
  2086. klog.V(1).Infof("Failed to get provider config while adding pv metrics data.")
  2087. return
  2088. }
  2089. for _, pvcDataArray := range pvAllocationMap {
  2090. for _, pvcData := range pvcDataArray {
  2091. costKey := fmt.Sprintf("%s,%s", pvcData.VolumeName, pvcData.ClusterID)
  2092. pvCost, ok := pvCostMap[costKey]
  2093. if !ok {
  2094. pvcData.Volume = &costAnalyzerCloud.PV{
  2095. Cost: cfg.Storage,
  2096. }
  2097. continue
  2098. }
  2099. pvcData.Volume = pvCost
  2100. }
  2101. }
  2102. }
  2103. // Append labels into nsLabels iff the ns key doesn't already exist
  2104. func appendNamespaceLabels(nsLabels map[string]map[string]string, labels map[string]map[string]string) {
  2105. for k, v := range labels {
  2106. if _, ok := nsLabels[k]; !ok {
  2107. nsLabels[k] = v
  2108. }
  2109. }
  2110. }
  2111. func appendLabelsList(mainLabels map[string]map[string][]string, labels map[string]map[string][]string) {
  2112. for k, v := range labels {
  2113. mainLabels[k] = v
  2114. }
  2115. }
  2116. func getNamespaceLabels(cache clustercache.ClusterCache, clusterID string) (map[string]map[string]string, error) {
  2117. nsToLabels := make(map[string]map[string]string)
  2118. nss := cache.GetAllNamespaces()
  2119. for _, ns := range nss {
  2120. nsToLabels[ns.Name+","+clusterID] = ns.Labels
  2121. }
  2122. return nsToLabels, nil
  2123. }
  2124. func getDaemonsetsOfPod(pod v1.Pod) []string {
  2125. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2126. if ownerReference.Kind == "DaemonSet" {
  2127. return []string{ownerReference.Name}
  2128. }
  2129. }
  2130. return []string{}
  2131. }
  2132. func getJobsOfPod(pod v1.Pod) []string {
  2133. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2134. if ownerReference.Kind == "Job" {
  2135. return []string{ownerReference.Name}
  2136. }
  2137. }
  2138. return []string{}
  2139. }
  2140. func getStatefulSetsOfPod(pod v1.Pod) []string {
  2141. for _, ownerReference := range pod.ObjectMeta.OwnerReferences {
  2142. if ownerReference.Kind == "StatefulSet" {
  2143. return []string{ownerReference.Name}
  2144. }
  2145. }
  2146. return []string{}
  2147. }
  2148. type PersistentVolumeClaimData struct {
  2149. Class string `json:"class"`
  2150. Claim string `json:"claim"`
  2151. Namespace string `json:"namespace"`
  2152. ClusterID string `json:"clusterId"`
  2153. VolumeName string `json:"volumeName"`
  2154. Volume *costAnalyzerCloud.PV `json:"persistentVolume"`
  2155. Values []*util.Vector `json:"values"`
  2156. }
  2157. func getCost(qr interface{}) (map[string][]*util.Vector, error) {
  2158. toReturn := make(map[string][]*util.Vector)
  2159. result, err := NewQueryResults(qr)
  2160. if err != nil {
  2161. return toReturn, err
  2162. }
  2163. for _, val := range result {
  2164. instance, err := val.GetString("instance")
  2165. if err != nil {
  2166. return toReturn, err
  2167. }
  2168. toReturn[instance] = val.Values
  2169. }
  2170. return toReturn, nil
  2171. }
  2172. func QueryRange(cli prometheusClient.Client, query string, start, end time.Time, step time.Duration) (interface{}, error) {
  2173. u := cli.URL(epQueryRange, nil)
  2174. q := u.Query()
  2175. q.Set("query", query)
  2176. q.Set("start", start.Format(time.RFC3339Nano))
  2177. q.Set("end", end.Format(time.RFC3339Nano))
  2178. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  2179. u.RawQuery = q.Encode()
  2180. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  2181. if err != nil {
  2182. return nil, err
  2183. }
  2184. resp, body, warnings, err := cli.Do(context.Background(), req)
  2185. for _, w := range warnings {
  2186. klog.V(3).Infof("[Warning] '%s' fetching query '%s'", w, query)
  2187. }
  2188. if err != nil {
  2189. return nil, fmt.Errorf("[Error] %s fetching query %s", err.Error(), query)
  2190. }
  2191. var toReturn interface{}
  2192. err = json.Unmarshal(body, &toReturn)
  2193. if err != nil {
  2194. return nil, fmt.Errorf("[Error] %d %s fetching query %s", resp.StatusCode, err.Error(), query)
  2195. }
  2196. return toReturn, err
  2197. }
  2198. func Query(cli prometheusClient.Client, query string) (interface{}, error) {
  2199. u := cli.URL(epQuery, nil)
  2200. q := u.Query()
  2201. q.Set("query", query)
  2202. u.RawQuery = q.Encode()
  2203. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  2204. if err != nil {
  2205. return nil, err
  2206. }
  2207. resp, body, warnings, err := cli.Do(context.Background(), req)
  2208. for _, w := range warnings {
  2209. klog.V(3).Infof("Warning '%s' fetching query '%s'", w, query)
  2210. }
  2211. if err != nil {
  2212. if resp == nil {
  2213. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  2214. }
  2215. return nil, fmt.Errorf("%d Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  2216. }
  2217. var toReturn interface{}
  2218. err = json.Unmarshal(body, &toReturn)
  2219. if err != nil {
  2220. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  2221. }
  2222. return toReturn, nil
  2223. }
  2224. //todo: don't cast, implement unmarshaler interface
  2225. func getNormalization(qr interface{}) (float64, error) {
  2226. queryResults, err := NewQueryResults(qr)
  2227. if err != nil {
  2228. return 0, err
  2229. }
  2230. if len(queryResults) > 0 {
  2231. values := queryResults[0].Values
  2232. if len(values) > 0 {
  2233. return values[0].Value, nil
  2234. }
  2235. return 0, fmt.Errorf("Improperly formatted datapoint from Prometheus")
  2236. }
  2237. return 0, fmt.Errorf("Normalization data is empty, kube-state-metrics or node-exporter may not be running")
  2238. }
  2239. //todo: don't cast, implement unmarshaler interface
  2240. func getNormalizations(qr interface{}) ([]*util.Vector, error) {
  2241. queryResults, err := NewQueryResults(qr)
  2242. if err != nil {
  2243. return nil, err
  2244. }
  2245. if len(queryResults) > 0 {
  2246. vectors := []*util.Vector{}
  2247. for _, value := range queryResults {
  2248. vectors = append(vectors, value.Values...)
  2249. }
  2250. return vectors, nil
  2251. }
  2252. return nil, fmt.Errorf("normalization data is empty: time window may be invalid or kube-state-metrics or node-exporter may not be running")
  2253. }
  2254. type ContainerMetric struct {
  2255. Namespace string
  2256. PodName string
  2257. ContainerName string
  2258. NodeName string
  2259. ClusterID string
  2260. }
  2261. func (c *ContainerMetric) Key() string {
  2262. return c.Namespace + "," + c.PodName + "," + c.ContainerName + "," + c.NodeName + "," + c.ClusterID
  2263. }
  2264. func NewContainerMetricFromKey(key string) (*ContainerMetric, error) {
  2265. s := strings.Split(key, ",")
  2266. if len(s) == 5 {
  2267. return &ContainerMetric{
  2268. Namespace: s[0],
  2269. PodName: s[1],
  2270. ContainerName: s[2],
  2271. NodeName: s[3],
  2272. ClusterID: s[4],
  2273. }, nil
  2274. }
  2275. return nil, fmt.Errorf("Not a valid key")
  2276. }
  2277. func newContainerMetricFromValues(ns string, podName string, containerName string, nodeName string, clusterId string) *ContainerMetric {
  2278. return &ContainerMetric{
  2279. Namespace: ns,
  2280. PodName: podName,
  2281. ContainerName: containerName,
  2282. NodeName: nodeName,
  2283. ClusterID: clusterId,
  2284. }
  2285. }
  2286. func newContainerMetricsFromPod(pod v1.Pod, clusterID string) ([]*ContainerMetric, error) {
  2287. podName := pod.GetObjectMeta().GetName()
  2288. ns := pod.GetObjectMeta().GetNamespace()
  2289. node := pod.Spec.NodeName
  2290. var cs []*ContainerMetric
  2291. for _, container := range pod.Spec.Containers {
  2292. containerName := container.Name
  2293. cs = append(cs, &ContainerMetric{
  2294. Namespace: ns,
  2295. PodName: podName,
  2296. ContainerName: containerName,
  2297. NodeName: node,
  2298. ClusterID: clusterID,
  2299. })
  2300. }
  2301. return cs, nil
  2302. }
  2303. func newContainerMetricFromPrometheus(metrics map[string]interface{}, defaultClusterID string) (*ContainerMetric, error) {
  2304. cName, ok := metrics["container_name"]
  2305. if !ok {
  2306. return nil, fmt.Errorf("Prometheus vector does not have container name")
  2307. }
  2308. containerName, ok := cName.(string)
  2309. if !ok {
  2310. return nil, fmt.Errorf("Prometheus vector does not have string container name")
  2311. }
  2312. pName, ok := metrics["pod_name"]
  2313. if !ok {
  2314. return nil, fmt.Errorf("Prometheus vector does not have pod name")
  2315. }
  2316. podName, ok := pName.(string)
  2317. if !ok {
  2318. return nil, fmt.Errorf("Prometheus vector does not have string pod name")
  2319. }
  2320. ns, ok := metrics["namespace"]
  2321. if !ok {
  2322. return nil, fmt.Errorf("Prometheus vector does not have namespace")
  2323. }
  2324. namespace, ok := ns.(string)
  2325. if !ok {
  2326. return nil, fmt.Errorf("Prometheus vector does not have string namespace")
  2327. }
  2328. node, ok := metrics["node"]
  2329. if !ok {
  2330. klog.V(4).Info("Prometheus vector does not have node name")
  2331. node = ""
  2332. }
  2333. nodeName, ok := node.(string)
  2334. if !ok {
  2335. return nil, fmt.Errorf("Prometheus vector does not have string node")
  2336. }
  2337. cid, ok := metrics["cluster_id"]
  2338. if !ok {
  2339. klog.V(4).Info("Prometheus vector does not have cluster id")
  2340. cid = defaultClusterID
  2341. }
  2342. clusterID, ok := cid.(string)
  2343. if !ok {
  2344. return nil, fmt.Errorf("Prometheus vector does not have string cluster_id")
  2345. }
  2346. return &ContainerMetric{
  2347. ContainerName: containerName,
  2348. PodName: podName,
  2349. Namespace: namespace,
  2350. NodeName: nodeName,
  2351. ClusterID: clusterID,
  2352. }, nil
  2353. }
  2354. type KeyTuple struct {
  2355. Namespace string
  2356. Key string
  2357. ClusterID string
  2358. }
  2359. func NewKeyTuple(key string) (*KeyTuple, error) {
  2360. r := strings.Split(key, ",")
  2361. if len(r) != 3 {
  2362. return nil, fmt.Errorf("NewKeyTuple() Provided key not containing exactly 3 components.")
  2363. }
  2364. return &KeyTuple{
  2365. Namespace: r[0],
  2366. Key: r[1],
  2367. ClusterID: r[2],
  2368. }, nil
  2369. }
  2370. func GetContainerMetricVector(qr interface{}, normalize bool, normalizationValue float64, defaultClusterID string) (map[string][]*util.Vector, error) {
  2371. result, err := NewQueryResults(qr)
  2372. if err != nil {
  2373. return nil, err
  2374. }
  2375. containerData := make(map[string][]*util.Vector)
  2376. for _, val := range result {
  2377. containerMetric, err := newContainerMetricFromPrometheus(val.Metric, defaultClusterID)
  2378. if err != nil {
  2379. return nil, err
  2380. }
  2381. if normalize && normalizationValue != 0 {
  2382. for _, v := range val.Values {
  2383. v.Value = v.Value / normalizationValue
  2384. }
  2385. }
  2386. containerData[containerMetric.Key()] = val.Values
  2387. }
  2388. return containerData, nil
  2389. }
  2390. func GetContainerMetricVectors(qr interface{}, defaultClusterID string) (map[string][]*util.Vector, error) {
  2391. result, err := NewQueryResults(qr)
  2392. if err != nil {
  2393. return nil, err
  2394. }
  2395. containerData := make(map[string][]*util.Vector)
  2396. for _, val := range result {
  2397. containerMetric, err := newContainerMetricFromPrometheus(val.Metric, defaultClusterID)
  2398. if err != nil {
  2399. return nil, err
  2400. }
  2401. containerData[containerMetric.Key()] = val.Values
  2402. }
  2403. return containerData, nil
  2404. }
  2405. func GetNormalizedContainerMetricVectors(qr interface{}, normalizationValues []*util.Vector, defaultClusterID string) (map[string][]*util.Vector, error) {
  2406. result, err := NewQueryResults(qr)
  2407. if err != nil {
  2408. return nil, err
  2409. }
  2410. containerData := make(map[string][]*util.Vector)
  2411. for _, val := range result {
  2412. containerMetric, err := newContainerMetricFromPrometheus(val.Metric, defaultClusterID)
  2413. if err != nil {
  2414. return nil, err
  2415. }
  2416. containerData[containerMetric.Key()] = util.NormalizeVectorByVector(val.Values, normalizationValues)
  2417. }
  2418. return containerData, nil
  2419. }
  2420. func wrapPrometheusError(qr interface{}) (string, error) {
  2421. e, ok := qr.(map[string]interface{})["error"]
  2422. if !ok {
  2423. return "", fmt.Errorf("Unexpected response from Prometheus")
  2424. }
  2425. eStr, ok := e.(string)
  2426. return eStr, nil
  2427. }
  2428. func measureTime(start time.Time, threshold time.Duration, name string) {
  2429. elapsed := time.Since(start)
  2430. if elapsed > threshold {
  2431. klog.V(3).Infof("[Profiler] %s: %s", elapsed, name)
  2432. }
  2433. }
  2434. func measureTimeAsync(start time.Time, threshold time.Duration, name string, ch chan string) {
  2435. elapsed := time.Since(start)
  2436. if elapsed > threshold {
  2437. ch <- fmt.Sprintf("%s took %s", name, time.Since(start))
  2438. }
  2439. }