costmodel.go 93 KB

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