costmodel.go 92 KB

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