costmodel.go 92 KB

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