router.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "math"
  8. "net"
  9. "net/http"
  10. "os"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "k8s.io/klog"
  16. "github.com/julienschmidt/httprouter"
  17. costAnalyzerCloud "github.com/kubecost/cost-model/pkg/cloud"
  18. "github.com/kubecost/cost-model/pkg/clustercache"
  19. cm "github.com/kubecost/cost-model/pkg/clustermanager"
  20. prometheusClient "github.com/prometheus/client_golang/api"
  21. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "github.com/patrickmn/go-cache"
  25. "github.com/prometheus/client_golang/prometheus"
  26. "k8s.io/client-go/kubernetes"
  27. "k8s.io/client-go/rest"
  28. )
  29. const (
  30. prometheusServerEndpointEnvVar = "PROMETHEUS_SERVER_ENDPOINT"
  31. prometheusTroubleshootingEp = "http://docs.kubecost.com/custom-prom#troubleshoot"
  32. RFC3339Milli = "2006-01-02T15:04:05.000Z"
  33. )
  34. var (
  35. // gitCommit is set by the build system
  36. gitCommit string
  37. )
  38. var Router = httprouter.New()
  39. var A Accesses
  40. type Accesses struct {
  41. PrometheusClient prometheusClient.Client
  42. ThanosClient prometheusClient.Client
  43. KubeClientSet kubernetes.Interface
  44. ClusterManager *cm.ClusterManager
  45. Cloud costAnalyzerCloud.Provider
  46. CPUPriceRecorder *prometheus.GaugeVec
  47. RAMPriceRecorder *prometheus.GaugeVec
  48. PersistentVolumePriceRecorder *prometheus.GaugeVec
  49. GPUPriceRecorder *prometheus.GaugeVec
  50. NodeTotalPriceRecorder *prometheus.GaugeVec
  51. RAMAllocationRecorder *prometheus.GaugeVec
  52. CPUAllocationRecorder *prometheus.GaugeVec
  53. GPUAllocationRecorder *prometheus.GaugeVec
  54. PVAllocationRecorder *prometheus.GaugeVec
  55. NetworkZoneEgressRecorder prometheus.Gauge
  56. NetworkRegionEgressRecorder prometheus.Gauge
  57. NetworkInternetEgressRecorder prometheus.Gauge
  58. ServiceSelectorRecorder *prometheus.GaugeVec
  59. DeploymentSelectorRecorder *prometheus.GaugeVec
  60. Model *CostModel
  61. OutOfClusterCache *cache.Cache
  62. }
  63. type DataEnvelope struct {
  64. Code int `json:"code"`
  65. Status string `json:"status"`
  66. Data interface{} `json:"data"`
  67. Message string `json:"message,omitempty"`
  68. }
  69. // FilterFunc is a filter that returns true iff the given CostData should be filtered out, and the environment that was used as the filter criteria, if it was an aggregate
  70. type FilterFunc func(*CostData) (bool, string)
  71. // FilterCostData allows through only CostData that matches all the given filter functions
  72. func FilterCostData(data map[string]*CostData, retains []FilterFunc, filters []FilterFunc) (map[string]*CostData, int, map[string]int) {
  73. result := make(map[string]*CostData)
  74. filteredEnvironments := make(map[string]int)
  75. filteredContainers := 0
  76. DataLoop:
  77. for key, datum := range data {
  78. for _, rf := range retains {
  79. if ok, _ := rf(datum); ok {
  80. result[key] = datum
  81. // if any retain function passes, the data is retained and move on
  82. continue DataLoop
  83. }
  84. }
  85. for _, ff := range filters {
  86. if ok, environment := ff(datum); !ok {
  87. if environment != "" {
  88. filteredEnvironments[environment]++
  89. }
  90. filteredContainers++
  91. // if any filter function check fails, move on to the next datum
  92. continue DataLoop
  93. }
  94. }
  95. result[key] = datum
  96. }
  97. return result, filteredContainers, filteredEnvironments
  98. }
  99. func filterFields(fields string, data map[string]*CostData) map[string]CostData {
  100. fs := strings.Split(fields, ",")
  101. fmap := make(map[string]bool)
  102. for _, f := range fs {
  103. fieldNameLower := strings.ToLower(f) // convert to go struct name by uppercasing first letter
  104. klog.V(1).Infof("to delete: %s", fieldNameLower)
  105. fmap[fieldNameLower] = true
  106. }
  107. filteredData := make(map[string]CostData)
  108. for cname, costdata := range data {
  109. s := reflect.TypeOf(*costdata)
  110. val := reflect.ValueOf(*costdata)
  111. costdata2 := CostData{}
  112. cd2 := reflect.New(reflect.Indirect(reflect.ValueOf(costdata2)).Type()).Elem()
  113. n := s.NumField()
  114. for i := 0; i < n; i++ {
  115. field := s.Field(i)
  116. value := val.Field(i)
  117. value2 := cd2.Field(i)
  118. if _, ok := fmap[strings.ToLower(field.Name)]; !ok {
  119. value2.Set(reflect.Value(value))
  120. }
  121. }
  122. filteredData[cname] = cd2.Interface().(CostData)
  123. }
  124. return filteredData
  125. }
  126. func normalizeTimeParam(param string) (string, error) {
  127. // convert days to hours
  128. if param[len(param)-1:] == "d" {
  129. count := param[:len(param)-1]
  130. val, err := strconv.ParseInt(count, 10, 64)
  131. if err != nil {
  132. return "", err
  133. }
  134. val = val * 24
  135. param = fmt.Sprintf("%dh", val)
  136. }
  137. return param, nil
  138. }
  139. // parsePercentString takes a string of expected format "N%" and returns a floating point 0.0N.
  140. // If the "%" symbol is missing, it just returns 0.0N. Empty string is interpreted as "0%" and
  141. // return 0.0.
  142. func ParsePercentString(percentStr string) (float64, error) {
  143. if len(percentStr) == 0 {
  144. return 0.0, nil
  145. }
  146. if percentStr[len(percentStr)-1:] == "%" {
  147. percentStr = percentStr[:len(percentStr)-1]
  148. }
  149. discount, err := strconv.ParseFloat(percentStr, 64)
  150. if err != nil {
  151. return 0.0, err
  152. }
  153. discount *= 0.01
  154. return discount, nil
  155. }
  156. // parseDuration converts a Prometheus-style duration string into a Duration
  157. func ParseDuration(duration string) (*time.Duration, error) {
  158. unitStr := duration[len(duration)-1:]
  159. var unit time.Duration
  160. switch unitStr {
  161. case "s":
  162. unit = time.Second
  163. case "m":
  164. unit = time.Minute
  165. case "h":
  166. unit = time.Hour
  167. case "d":
  168. unit = 24.0 * time.Hour
  169. default:
  170. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  171. }
  172. amountStr := duration[:len(duration)-1]
  173. amount, err := strconv.ParseInt(amountStr, 10, 64)
  174. if err != nil {
  175. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  176. }
  177. dur := time.Duration(amount) * unit
  178. return &dur, nil
  179. }
  180. // ParseTimeRange returns a start and end time, respectively, which are converted from
  181. // a duration and offset, defined as strings with Prometheus-style syntax.
  182. func ParseTimeRange(duration, offset string) (*time.Time, *time.Time, error) {
  183. // endTime defaults to the current time, unless an offset is explicity declared,
  184. // in which case it shifts endTime back by given duration
  185. endTime := time.Now()
  186. if offset != "" {
  187. o, err := ParseDuration(offset)
  188. if err != nil {
  189. return nil, nil, fmt.Errorf("error parsing offset (%s): %s", offset, err)
  190. }
  191. endTime = endTime.Add(-1 * *o)
  192. }
  193. // if duration is defined in terms of days, convert to hours
  194. // e.g. convert "2d" to "48h"
  195. durationNorm, err := normalizeTimeParam(duration)
  196. if err != nil {
  197. return nil, nil, fmt.Errorf("error parsing duration (%s): %s", duration, err)
  198. }
  199. // convert time duration into start and end times, formatted
  200. // as ISO datetime strings
  201. dur, err := time.ParseDuration(durationNorm)
  202. if err != nil {
  203. return nil, nil, fmt.Errorf("errorf parsing duration (%s): %s", durationNorm, err)
  204. }
  205. startTime := endTime.Add(-1 * dur)
  206. return &startTime, &endTime, nil
  207. }
  208. func WrapDataWithMessage(data interface{}, err error, message string) []byte {
  209. var resp []byte
  210. if err != nil {
  211. klog.V(1).Infof("Error returned to client: %s", err.Error())
  212. resp, _ = json.Marshal(&DataEnvelope{
  213. Code: http.StatusInternalServerError,
  214. Status: "error",
  215. Message: err.Error(),
  216. Data: data,
  217. })
  218. } else {
  219. resp, _ = json.Marshal(&DataEnvelope{
  220. Code: http.StatusOK,
  221. Status: "success",
  222. Data: data,
  223. Message: message,
  224. })
  225. }
  226. return resp
  227. }
  228. func WrapData(data interface{}, err error) []byte {
  229. var resp []byte
  230. if err != nil {
  231. klog.V(1).Infof("Error returned to client: %s", err.Error())
  232. resp, _ = json.Marshal(&DataEnvelope{
  233. Code: http.StatusInternalServerError,
  234. Status: "error",
  235. Message: err.Error(),
  236. Data: data,
  237. })
  238. } else {
  239. resp, _ = json.Marshal(&DataEnvelope{
  240. Code: http.StatusOK,
  241. Status: "success",
  242. Data: data,
  243. })
  244. }
  245. return resp
  246. }
  247. // RefreshPricingData needs to be called when a new node joins the fleet, since we cache the relevant subsets of pricing data to avoid storing the whole thing.
  248. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  249. w.Header().Set("Content-Type", "application/json")
  250. w.Header().Set("Access-Control-Allow-Origin", "*")
  251. err := a.Cloud.DownloadPricingData()
  252. w.Write(WrapData(nil, err))
  253. }
  254. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  255. w.Header().Set("Content-Type", "application/json")
  256. w.Header().Set("Access-Control-Allow-Origin", "*")
  257. window := r.URL.Query().Get("timeWindow")
  258. offset := r.URL.Query().Get("offset")
  259. fields := r.URL.Query().Get("filterFields")
  260. namespace := r.URL.Query().Get("namespace")
  261. if offset != "" {
  262. offset = "offset " + offset
  263. }
  264. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, window, offset, namespace)
  265. if fields != "" {
  266. filteredData := filterFields(fields, data)
  267. w.Write(WrapData(filteredData, err))
  268. } else {
  269. w.Write(WrapData(data, err))
  270. }
  271. }
  272. func (a *Accesses) ClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  273. w.Header().Set("Content-Type", "application/json")
  274. w.Header().Set("Access-Control-Allow-Origin", "*")
  275. window := r.URL.Query().Get("window")
  276. offset := r.URL.Query().Get("offset")
  277. data, err := ComputeClusterCosts(a.PrometheusClient, a.Cloud, window, offset)
  278. w.Write(WrapData(data, err))
  279. }
  280. func (a *Accesses) ClusterCostsOverTime(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  281. w.Header().Set("Content-Type", "application/json")
  282. w.Header().Set("Access-Control-Allow-Origin", "*")
  283. start := r.URL.Query().Get("start")
  284. end := r.URL.Query().Get("end")
  285. window := r.URL.Query().Get("window")
  286. offset := r.URL.Query().Get("offset")
  287. data, err := ClusterCostsOverTime(a.PrometheusClient, a.Cloud, start, end, window, offset)
  288. w.Write(WrapData(data, err))
  289. }
  290. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  291. w.Header().Set("Content-Type", "application/json")
  292. w.Header().Set("Access-Control-Allow-Origin", "*")
  293. start := r.URL.Query().Get("start")
  294. end := r.URL.Query().Get("end")
  295. window := r.URL.Query().Get("window")
  296. fields := r.URL.Query().Get("filterFields")
  297. namespace := r.URL.Query().Get("namespace")
  298. cluster := r.URL.Query().Get("cluster")
  299. remote := r.URL.Query().Get("remote")
  300. remoteAvailable := os.Getenv(remoteEnabled)
  301. remoteEnabled := false
  302. if remoteAvailable == "true" && remote != "false" {
  303. remoteEnabled = true
  304. }
  305. // Use Thanos Client if it exists (enabled) and remote flag set
  306. var pClient prometheusClient.Client
  307. if remote != "false" && a.ThanosClient != nil {
  308. pClient = a.ThanosClient
  309. } else {
  310. pClient = a.PrometheusClient
  311. }
  312. resolutionHours := 1.0
  313. data, err := a.Model.ComputeCostDataRange(pClient, a.KubeClientSet, a.Cloud, start, end, window, resolutionHours, namespace, cluster, remoteEnabled)
  314. if err != nil {
  315. w.Write(WrapData(nil, err))
  316. }
  317. if fields != "" {
  318. filteredData := filterFields(fields, data)
  319. w.Write(WrapData(filteredData, err))
  320. } else {
  321. w.Write(WrapData(data, err))
  322. }
  323. }
  324. // CostDataModelRangeLarge is experimental multi-cluster and long-term data storage in SQL support.
  325. func (a *Accesses) CostDataModelRangeLarge(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  326. w.Header().Set("Content-Type", "application/json")
  327. w.Header().Set("Access-Control-Allow-Origin", "*")
  328. startString := r.URL.Query().Get("start")
  329. endString := r.URL.Query().Get("end")
  330. windowString := r.URL.Query().Get("window")
  331. var start time.Time
  332. var end time.Time
  333. var err error
  334. if windowString == "" {
  335. windowString = "1h"
  336. }
  337. if startString != "" {
  338. start, err = time.Parse(RFC3339Milli, startString)
  339. if err != nil {
  340. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  341. w.Write(WrapData(nil, err))
  342. }
  343. } else {
  344. window, err := time.ParseDuration(windowString)
  345. if err != nil {
  346. w.Write(WrapData(nil, fmt.Errorf("Invalid duration '%s'", windowString)))
  347. }
  348. start = time.Now().Add(-2 * window)
  349. }
  350. if endString != "" {
  351. end, err = time.Parse(RFC3339Milli, endString)
  352. if err != nil {
  353. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  354. w.Write(WrapData(nil, err))
  355. }
  356. } else {
  357. end = time.Now()
  358. }
  359. remoteLayout := "2006-01-02T15:04:05Z"
  360. remoteStartStr := start.Format(remoteLayout)
  361. remoteEndStr := end.Format(remoteLayout)
  362. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  363. data, err := CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  364. w.Write(WrapData(data, err))
  365. }
  366. func parseAggregations(customAggregation, aggregator, filterType string) (string, []string, string) {
  367. var key string
  368. var filter string
  369. var val []string
  370. if customAggregation != "" {
  371. key = customAggregation
  372. filter = filterType
  373. val = strings.Split(customAggregation, ",")
  374. } else {
  375. aggregations := strings.Split(aggregator, ",")
  376. for i, agg := range aggregations {
  377. aggregations[i] = "kubernetes_" + agg
  378. }
  379. key = strings.Join(aggregations, ",")
  380. filter = "kubernetes_" + filterType
  381. val = aggregations
  382. }
  383. return key, val, filter
  384. }
  385. func (a *Accesses) OutofClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  386. w.Header().Set("Content-Type", "application/json")
  387. w.Header().Set("Access-Control-Allow-Origin", "*")
  388. start := r.URL.Query().Get("start")
  389. end := r.URL.Query().Get("end")
  390. aggregator := r.URL.Query().Get("aggregator")
  391. customAggregation := r.URL.Query().Get("customAggregation")
  392. filterType := r.URL.Query().Get("filterType")
  393. filterValue := r.URL.Query().Get("filterValue")
  394. var data []*costAnalyzerCloud.OutOfClusterAllocation
  395. var err error
  396. _, aggregations, filter := parseAggregations(customAggregation, aggregator, filterType)
  397. data, err = a.Cloud.ExternalAllocations(start, end, aggregations, filter, filterValue, false)
  398. w.Write(WrapData(data, err))
  399. }
  400. func (a *Accesses) OutOfClusterCostsWithCache(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  401. w.Header().Set("Content-Type", "application/json")
  402. w.Header().Set("Access-Control-Allow-Origin", "*")
  403. // start date for which to query costs, inclusive; format YYYY-MM-DD
  404. start := r.URL.Query().Get("start")
  405. // end date for which to query costs, inclusive; format YYYY-MM-DD
  406. end := r.URL.Query().Get("end")
  407. // aggregator sets the field by which to aggregate; default, prepended by "kubernetes_"
  408. kubernetesAggregation := r.URL.Query().Get("aggregator")
  409. // customAggregation allows full customization of aggregator w/o prepending
  410. customAggregation := r.URL.Query().Get("customAggregation")
  411. // disableCache, if set to "true", tells this function to recompute and
  412. // cache the requested data
  413. disableCache := r.URL.Query().Get("disableCache") == "true"
  414. // clearCache, if set to "true", tells this function to flush the cache,
  415. // then recompute and cache the requested data
  416. clearCache := r.URL.Query().Get("clearCache") == "true"
  417. filterType := r.URL.Query().Get("filterType")
  418. filterValue := r.URL.Query().Get("filterValue")
  419. aggregationkey, aggregation, filter := parseAggregations(customAggregation, kubernetesAggregation, filterType)
  420. // clear cache prior to checking the cache so that a clearCache=true
  421. // request always returns a freshly computed value
  422. if clearCache {
  423. a.OutOfClusterCache.Flush()
  424. }
  425. // attempt to retrieve cost data from cache
  426. key := fmt.Sprintf(`%s:%s:%s:%s:%s`, start, end, aggregationkey, filter, filterValue)
  427. if value, found := a.OutOfClusterCache.Get(key); found && !disableCache {
  428. if data, ok := value.([]*costAnalyzerCloud.OutOfClusterAllocation); ok {
  429. w.Write(WrapDataWithMessage(data, nil, fmt.Sprintf("out of cluster cache hit: %s", key)))
  430. return
  431. }
  432. klog.Errorf("caching error: failed to type cast data: %s", key)
  433. }
  434. data, err := a.Cloud.ExternalAllocations(start, end, aggregation, filter, filterValue, false)
  435. if err == nil {
  436. a.OutOfClusterCache.Set(key, data, cache.DefaultExpiration)
  437. }
  438. w.Write(WrapDataWithMessage(data, err, fmt.Sprintf("out of cluser cache miss: %s", key)))
  439. }
  440. func (p *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  441. w.Header().Set("Content-Type", "application/json")
  442. w.Header().Set("Access-Control-Allow-Origin", "*")
  443. data, err := p.Cloud.AllNodePricing()
  444. w.Write(WrapData(data, err))
  445. }
  446. func (p *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  447. w.Header().Set("Content-Type", "application/json")
  448. w.Header().Set("Access-Control-Allow-Origin", "*")
  449. data, err := p.Cloud.GetConfig()
  450. w.Write(WrapData(data, err))
  451. }
  452. func (p *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  453. w.Header().Set("Content-Type", "application/json")
  454. w.Header().Set("Access-Control-Allow-Origin", "*")
  455. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.SpotInfoUpdateType)
  456. if err != nil {
  457. w.Write(WrapData(data, err))
  458. return
  459. }
  460. w.Write(WrapData(data, err))
  461. err = p.Cloud.DownloadPricingData()
  462. if err != nil {
  463. klog.V(1).Infof("Error redownloading data on config update: %s", err.Error())
  464. }
  465. return
  466. }
  467. func (p *Accesses) UpdateAthenaInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  468. w.Header().Set("Content-Type", "application/json")
  469. w.Header().Set("Access-Control-Allow-Origin", "*")
  470. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.AthenaInfoUpdateType)
  471. if err != nil {
  472. w.Write(WrapData(data, err))
  473. return
  474. }
  475. w.Write(WrapData(data, err))
  476. return
  477. }
  478. func (p *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  479. w.Header().Set("Content-Type", "application/json")
  480. w.Header().Set("Access-Control-Allow-Origin", "*")
  481. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.BigqueryUpdateType)
  482. if err != nil {
  483. w.Write(WrapData(data, err))
  484. return
  485. }
  486. w.Write(WrapData(data, err))
  487. return
  488. }
  489. func (p *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  490. w.Header().Set("Content-Type", "application/json")
  491. w.Header().Set("Access-Control-Allow-Origin", "*")
  492. data, err := p.Cloud.UpdateConfig(r.Body, "")
  493. if err != nil {
  494. w.Write(WrapData(data, err))
  495. return
  496. }
  497. w.Write(WrapData(data, err))
  498. return
  499. }
  500. func (p *Accesses) ManagementPlatform(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  501. w.Header().Set("Content-Type", "application/json")
  502. w.Header().Set("Access-Control-Allow-Origin", "*")
  503. data, err := p.Cloud.GetManagementPlatform()
  504. if err != nil {
  505. w.Write(WrapData(data, err))
  506. return
  507. }
  508. w.Write(WrapData(data, err))
  509. return
  510. }
  511. func (p *Accesses) ClusterInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  512. w.Header().Set("Content-Type", "application/json")
  513. w.Header().Set("Access-Control-Allow-Origin", "*")
  514. data, err := p.Cloud.ClusterInfo()
  515. kc, ok := p.KubeClientSet.(*kubernetes.Clientset)
  516. if ok && data != nil {
  517. v, err := kc.ServerVersion()
  518. if err != nil {
  519. klog.Infof("Could not get k8s version info: %s", err.Error())
  520. } else if v != nil {
  521. data["version"] = v.Major + "." + v.Minor
  522. }
  523. } else {
  524. klog.Infof("Could not get k8s version info: %s", err.Error())
  525. }
  526. w.Write(WrapData(data, err))
  527. }
  528. func (p *Accesses) GetPrometheusMetadata(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  529. w.Header().Set("Content-Type", "application/json")
  530. w.Header().Set("Access-Control-Allow-Origin", "*")
  531. w.Write(WrapData(ValidatePrometheus(p.PrometheusClient, false)))
  532. }
  533. func (a *Accesses) recordPrices() {
  534. go func() {
  535. containerSeen := make(map[string]bool)
  536. nodeSeen := make(map[string]bool)
  537. pvSeen := make(map[string]bool)
  538. pvcSeen := make(map[string]bool)
  539. getKeyFromLabelStrings := func(labels ...string) string {
  540. return strings.Join(labels, ",")
  541. }
  542. getLabelStringsFromKey := func(key string) []string {
  543. return strings.Split(key, ",")
  544. }
  545. var defaultRegion string = ""
  546. nodeList := a.Model.Cache.GetAllNodes()
  547. if len(nodeList) > 0 {
  548. defaultRegion = nodeList[0].Labels[v1.LabelZoneRegion]
  549. }
  550. for {
  551. klog.V(4).Info("Recording prices...")
  552. podlist := a.Model.Cache.GetAllPods()
  553. podStatus := make(map[string]v1.PodPhase)
  554. for _, pod := range podlist {
  555. podStatus[pod.Name] = pod.Status.Phase
  556. }
  557. cfg, _ := a.Cloud.GetConfig()
  558. // Record network pricing at global scope
  559. networkCosts, err := a.Cloud.NetworkPricing()
  560. if err != nil {
  561. klog.V(4).Infof("Failed to retrieve network costs: %s", err.Error())
  562. } else {
  563. a.NetworkZoneEgressRecorder.Set(networkCosts.ZoneNetworkEgressCost)
  564. a.NetworkRegionEgressRecorder.Set(networkCosts.RegionNetworkEgressCost)
  565. a.NetworkInternetEgressRecorder.Set(networkCosts.InternetNetworkEgressCost)
  566. }
  567. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "2m", "", "")
  568. if err != nil {
  569. klog.V(1).Info("Error in price recording: " + err.Error())
  570. // zero the for loop so the time.Sleep will still work
  571. data = map[string]*CostData{}
  572. }
  573. nodes, err := a.Model.GetNodeCost(a.Cloud)
  574. for nodeName, node := range nodes {
  575. // Emit costs, guarding against NaN inputs for custom pricing.
  576. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  577. if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  578. cpuCost, _ = strconv.ParseFloat(cfg.CPU, 64)
  579. if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  580. cpuCost = 0
  581. }
  582. }
  583. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  584. if math.IsNaN(cpu) || math.IsInf(cpu, 0) {
  585. cpu = 1 // Assume 1 CPU
  586. }
  587. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  588. if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  589. ramCost, _ = strconv.ParseFloat(cfg.RAM, 64)
  590. if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  591. ramCost = 0
  592. }
  593. }
  594. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  595. if math.IsNaN(ram) || math.IsInf(ram, 0) {
  596. ram = 0
  597. }
  598. gpu, _ := strconv.ParseFloat(node.GPU, 64)
  599. if math.IsNaN(gpu) || math.IsInf(gpu, 0) {
  600. gpu = 0
  601. }
  602. gpuCost, _ := strconv.ParseFloat(node.GPUCost, 64)
  603. if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  604. gpuCost, _ = strconv.ParseFloat(cfg.GPU, 64)
  605. if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  606. gpuCost = 0
  607. }
  608. }
  609. nodeType := node.InstanceType
  610. nodeRegion := node.Region
  611. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024) + gpu*gpuCost
  612. a.CPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(cpuCost)
  613. a.RAMPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(ramCost)
  614. a.GPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(gpuCost)
  615. a.NodeTotalPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(totalCost)
  616. labelKey := getKeyFromLabelStrings(nodeName, nodeName)
  617. nodeSeen[labelKey] = true
  618. }
  619. for _, costs := range data {
  620. nodeName := costs.NodeName
  621. namespace := costs.Namespace
  622. podName := costs.PodName
  623. containerName := costs.Name
  624. if costs.PVCData != nil {
  625. for _, pvc := range costs.PVCData {
  626. if pvc.Volume != nil {
  627. a.PVAllocationRecorder.WithLabelValues(namespace, podName, pvc.Claim, pvc.VolumeName).Set(pvc.Values[0].Value)
  628. labelKey := getKeyFromLabelStrings(namespace, podName, pvc.Claim, pvc.VolumeName)
  629. pvcSeen[labelKey] = true
  630. }
  631. }
  632. }
  633. if len(costs.RAMAllocation) > 0 {
  634. a.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.RAMAllocation[0].Value)
  635. }
  636. if len(costs.CPUAllocation) > 0 {
  637. a.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.CPUAllocation[0].Value)
  638. }
  639. if len(costs.GPUReq) > 0 {
  640. // allocation here is set to the request because shared GPU usage not yet supported.
  641. a.GPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.GPUReq[0].Value)
  642. }
  643. labelKey := getKeyFromLabelStrings(namespace, podName, containerName, nodeName, nodeName)
  644. if podStatus[podName] == v1.PodRunning { // Only report data for current pods
  645. containerSeen[labelKey] = true
  646. } else {
  647. containerSeen[labelKey] = false
  648. }
  649. storageClasses := a.Model.Cache.GetAllStorageClasses()
  650. storageClassMap := make(map[string]map[string]string)
  651. for _, storageClass := range storageClasses {
  652. params := storageClass.Parameters
  653. storageClassMap[storageClass.ObjectMeta.Name] = params
  654. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  655. storageClassMap["default"] = params
  656. storageClassMap[""] = params
  657. }
  658. }
  659. pvs := a.Model.Cache.GetAllPersistentVolumes()
  660. for _, pv := range pvs {
  661. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  662. if !ok {
  663. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  664. }
  665. var region string
  666. if r, ok := pv.Labels[v1.LabelZoneRegion]; ok {
  667. region = r
  668. } else {
  669. region = defaultRegion
  670. }
  671. cacPv := &costAnalyzerCloud.PV{
  672. Class: pv.Spec.StorageClassName,
  673. Region: region,
  674. Parameters: parameters,
  675. }
  676. GetPVCost(cacPv, pv, a.Cloud, region)
  677. c, _ := strconv.ParseFloat(cacPv.Cost, 64)
  678. a.PersistentVolumePriceRecorder.WithLabelValues(pv.Name, pv.Name).Set(c)
  679. labelKey := getKeyFromLabelStrings(pv.Name, pv.Name)
  680. pvSeen[labelKey] = true
  681. }
  682. }
  683. for labelString, seen := range nodeSeen {
  684. if !seen {
  685. labels := getLabelStringsFromKey(labelString)
  686. a.NodeTotalPriceRecorder.DeleteLabelValues(labels...)
  687. a.CPUPriceRecorder.DeleteLabelValues(labels...)
  688. a.GPUPriceRecorder.DeleteLabelValues(labels...)
  689. a.RAMPriceRecorder.DeleteLabelValues(labels...)
  690. delete(nodeSeen, labelString)
  691. }
  692. nodeSeen[labelString] = false
  693. }
  694. for labelString, seen := range containerSeen {
  695. if !seen {
  696. labels := getLabelStringsFromKey(labelString)
  697. a.RAMAllocationRecorder.DeleteLabelValues(labels...)
  698. a.CPUAllocationRecorder.DeleteLabelValues(labels...)
  699. a.GPUAllocationRecorder.DeleteLabelValues(labels...)
  700. delete(containerSeen, labelString)
  701. }
  702. containerSeen[labelString] = false
  703. }
  704. for labelString, seen := range pvSeen {
  705. if !seen {
  706. labels := getLabelStringsFromKey(labelString)
  707. a.PersistentVolumePriceRecorder.DeleteLabelValues(labels...)
  708. delete(pvSeen, labelString)
  709. }
  710. pvSeen[labelString] = false
  711. }
  712. for labelString, seen := range pvcSeen {
  713. if !seen {
  714. labels := getLabelStringsFromKey(labelString)
  715. a.PVAllocationRecorder.DeleteLabelValues(labels...)
  716. delete(pvcSeen, labelString)
  717. }
  718. pvcSeen[labelString] = false
  719. }
  720. time.Sleep(time.Minute)
  721. }
  722. }()
  723. }
  724. // Creates a new ClusterManager instance using a boltdb storage. If that fails,
  725. // then we fall back to a memory-only storage.
  726. func newClusterManager() *cm.ClusterManager {
  727. clustersConfigFile := "/var/configs/clusters/default-clusters.yaml"
  728. // Return a memory-backed cluster manager populated by configmap
  729. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  730. // NOTE: The following should be used with a persistent disk store. Since the
  731. // NOTE: configmap approach is currently the "persistent" source (entries are read-only
  732. // NOTE: on the backend), we don't currently need to store on disk.
  733. /*
  734. path := os.Getenv("CONFIG_PATH")
  735. db, err := bolt.Open(path+"costmodel.db", 0600, nil)
  736. if err != nil {
  737. klog.V(1).Infof("[Error] Failed to create costmodel.db: %s", err.Error())
  738. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  739. }
  740. store, err := cm.NewBoltDBClusterStorage("clusters", db)
  741. if err != nil {
  742. klog.V(1).Infof("[Error] Failed to Create Cluster Storage: %s", err.Error())
  743. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  744. }
  745. return cm.NewConfiguredClusterManager(store, clustersConfigFile)
  746. */
  747. }
  748. type ConfigWatchers struct {
  749. ConfigmapName string
  750. WatchFunc func(string, map[string]string) error
  751. }
  752. func Initialize(additionalConfigWatchers ...ConfigWatchers) {
  753. klog.InitFlags(nil)
  754. flag.Set("v", "3")
  755. flag.Parse()
  756. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  757. address := os.Getenv(prometheusServerEndpointEnvVar)
  758. if address == "" {
  759. klog.Fatalf("No address for prometheus set in $%s. Aborting.", prometheusServerEndpointEnvVar)
  760. }
  761. var LongTimeoutRoundTripper http.RoundTripper = &http.Transport{ // may be necessary for long prometheus queries. TODO: make this configurable
  762. Proxy: http.ProxyFromEnvironment,
  763. DialContext: (&net.Dialer{
  764. Timeout: 120 * time.Second,
  765. KeepAlive: 120 * time.Second,
  766. }).DialContext,
  767. TLSHandshakeTimeout: 10 * time.Second,
  768. }
  769. pc := prometheusClient.Config{
  770. Address: address,
  771. RoundTripper: LongTimeoutRoundTripper,
  772. }
  773. promCli, _ := prometheusClient.NewClient(pc)
  774. api := prometheusAPI.NewAPI(promCli)
  775. _, err := api.Config(context.Background())
  776. if err != nil {
  777. klog.Fatalf("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  778. }
  779. klog.V(1).Info("Success: retrieved a prometheus config file from: " + address)
  780. _, err = ValidatePrometheus(promCli, false)
  781. if err != nil {
  782. klog.Fatalf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  783. }
  784. klog.V(1).Info("Success: retrieved the 'up' query against prometheus at: " + address)
  785. // Kubernetes API setup
  786. kc, err := rest.InClusterConfig()
  787. if err != nil {
  788. panic(err.Error())
  789. }
  790. kubeClientset, err := kubernetes.NewForConfig(kc)
  791. if err != nil {
  792. panic(err.Error())
  793. }
  794. // Create Kubernetes Cluster Cache + Watchers
  795. k8sCache := clustercache.NewKubernetesClusterCache(kubeClientset)
  796. k8sCache.Run()
  797. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  798. cloudProvider, err := costAnalyzerCloud.NewProvider(k8sCache, cloudProviderKey)
  799. if err != nil {
  800. panic(err.Error())
  801. }
  802. watchConfigFunc := func(c interface{}) {
  803. conf := c.(*v1.ConfigMap)
  804. if conf.GetName() == "pricing-configs" {
  805. _, err := cloudProvider.UpdateConfigFromConfigMap(conf.Data)
  806. if err != nil {
  807. klog.Infof("ERROR UPDATING %s CONFIG: %s", "pricing-configs", err.Error())
  808. }
  809. }
  810. for _, cw := range additionalConfigWatchers {
  811. if conf.GetName() == cw.ConfigmapName {
  812. err := cw.WatchFunc(conf.GetName(), conf.Data)
  813. if err != nil {
  814. klog.Infof("ERROR UPDATING %s CONFIG: %s", cw.ConfigmapName, err.Error())
  815. }
  816. }
  817. }
  818. }
  819. kubecostNamespace := os.Getenv("KUBECOST_NAMESPACE")
  820. // We need an initial invocation because the init of the cache has happened before we had access to the provider.
  821. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get("pricing-configs", metav1.GetOptions{})
  822. if err != nil {
  823. klog.Infof("No %s configmap found at installtime, using existing configs: %s", "pricing-configs", err.Error())
  824. } else {
  825. watchConfigFunc(configs)
  826. }
  827. for _, cw := range additionalConfigWatchers {
  828. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get(cw.ConfigmapName, metav1.GetOptions{})
  829. if err != nil {
  830. klog.Infof("No %s configmap found at installtime, using existing configs: %s", cw.ConfigmapName, err.Error())
  831. } else {
  832. watchConfigFunc(configs)
  833. }
  834. }
  835. k8sCache.SetConfigMapUpdateFunc(watchConfigFunc)
  836. // TODO: General Architecture Note: Several passes have been made to modularize a lot of
  837. // TODO: our code, but the router still continues to be the obvious entry point for new \
  838. // TODO: features. We should look to spliting out the actual "router" functionality and
  839. // TODO: implement a builder -> controller for stitching new features and other dependencies.
  840. clusterManager := newClusterManager()
  841. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  842. Name: "node_cpu_hourly_cost",
  843. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  844. }, []string{"instance", "node", "instance_type", "region"})
  845. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  846. Name: "node_ram_hourly_cost",
  847. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  848. }, []string{"instance", "node", "instance_type", "region"})
  849. gpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  850. Name: "node_gpu_hourly_cost",
  851. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  852. }, []string{"instance", "node", "instance_type", "region"})
  853. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  854. Name: "node_total_hourly_cost",
  855. Help: "node_total_hourly_cost Total node cost per hour",
  856. }, []string{"instance", "node", "instance_type", "region"})
  857. pvGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  858. Name: "pv_hourly_cost",
  859. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  860. }, []string{"volumename", "persistentvolume"})
  861. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  862. Name: "container_memory_allocation_bytes",
  863. Help: "container_memory_allocation_bytes Bytes of RAM used",
  864. }, []string{"namespace", "pod", "container", "instance", "node"})
  865. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  866. Name: "container_cpu_allocation",
  867. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  868. }, []string{"namespace", "pod", "container", "instance", "node"})
  869. GPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  870. Name: "container_gpu_allocation",
  871. Help: "container_gpu_allocation GPU used",
  872. }, []string{"namespace", "pod", "container", "instance", "node"})
  873. PVAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  874. Name: "pod_pvc_allocation",
  875. Help: "pod_pvc_allocation Bytes used by a PVC attached to a pod",
  876. }, []string{"namespace", "pod", "persistentvolumeclaim", "persistentvolume"})
  877. NetworkZoneEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  878. Name: "kubecost_network_zone_egress_cost",
  879. Help: "kubecost_network_zone_egress_cost Total cost per GB egress across zones",
  880. })
  881. NetworkRegionEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  882. Name: "kubecost_network_region_egress_cost",
  883. Help: "kubecost_network_region_egress_cost Total cost per GB egress across regions",
  884. })
  885. NetworkInternetEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  886. Name: "kubecost_network_internet_egress_cost",
  887. Help: "kubecost_network_internet_egress_cost Total cost per GB of internet egress.",
  888. })
  889. prometheus.MustRegister(cpuGv)
  890. prometheus.MustRegister(ramGv)
  891. prometheus.MustRegister(gpuGv)
  892. prometheus.MustRegister(totalGv)
  893. prometheus.MustRegister(pvGv)
  894. prometheus.MustRegister(RAMAllocation)
  895. prometheus.MustRegister(CPUAllocation)
  896. prometheus.MustRegister(PVAllocation)
  897. prometheus.MustRegister(GPUAllocation)
  898. prometheus.MustRegister(NetworkZoneEgressRecorder, NetworkRegionEgressRecorder, NetworkInternetEgressRecorder)
  899. prometheus.MustRegister(ServiceCollector{
  900. KubeClientSet: kubeClientset,
  901. })
  902. prometheus.MustRegister(DeploymentCollector{
  903. KubeClientSet: kubeClientset,
  904. })
  905. prometheus.MustRegister(StatefulsetCollector{
  906. KubeClientSet: kubeClientset,
  907. })
  908. // cache responses from model for a default of 5 minutes; clear expired responses every 10 minutes
  909. outOfClusterCache := cache.New(time.Minute*5, time.Minute*10)
  910. A = Accesses{
  911. PrometheusClient: promCli,
  912. KubeClientSet: kubeClientset,
  913. ClusterManager: clusterManager,
  914. Cloud: cloudProvider,
  915. CPUPriceRecorder: cpuGv,
  916. RAMPriceRecorder: ramGv,
  917. GPUPriceRecorder: gpuGv,
  918. NodeTotalPriceRecorder: totalGv,
  919. RAMAllocationRecorder: RAMAllocation,
  920. CPUAllocationRecorder: CPUAllocation,
  921. GPUAllocationRecorder: GPUAllocation,
  922. PVAllocationRecorder: PVAllocation,
  923. NetworkZoneEgressRecorder: NetworkZoneEgressRecorder,
  924. NetworkRegionEgressRecorder: NetworkRegionEgressRecorder,
  925. NetworkInternetEgressRecorder: NetworkInternetEgressRecorder,
  926. PersistentVolumePriceRecorder: pvGv,
  927. Model: NewCostModel(k8sCache),
  928. OutOfClusterCache: outOfClusterCache,
  929. }
  930. remoteEnabled := os.Getenv(remoteEnabled)
  931. if remoteEnabled == "true" {
  932. info, err := cloudProvider.ClusterInfo()
  933. klog.Infof("Saving cluster with id:'%s', and name:'%s' to durable storage", info["id"], info["name"])
  934. if err != nil {
  935. klog.Infof("Error saving cluster id %s", err.Error())
  936. }
  937. _, _, err = costAnalyzerCloud.GetOrCreateClusterMeta(info["id"], info["name"])
  938. if err != nil {
  939. klog.Infof("Unable to set cluster id '%s' for cluster '%s', %s", info["id"], info["name"], err.Error())
  940. }
  941. }
  942. // Thanos Client
  943. if os.Getenv(thanosEnabled) == "true" {
  944. thanosUrl := os.Getenv(thanosQueryUrl)
  945. if thanosUrl != "" {
  946. var thanosRT http.RoundTripper = &http.Transport{
  947. Proxy: http.ProxyFromEnvironment,
  948. DialContext: (&net.Dialer{
  949. Timeout: 120 * time.Second,
  950. KeepAlive: 120 * time.Second,
  951. }).DialContext,
  952. TLSHandshakeTimeout: 10 * time.Second,
  953. }
  954. thanosConfig := prometheusClient.Config{
  955. Address: thanosUrl,
  956. RoundTripper: thanosRT,
  957. }
  958. thanosCli, _ := prometheusClient.NewClient(thanosConfig)
  959. _, err = ValidatePrometheus(thanosCli, true)
  960. if err != nil {
  961. klog.V(1).Infof("[Warning] Failed to query Thanos at %s. Error: %s.", thanosUrl, err.Error())
  962. A.ThanosClient = thanosCli
  963. } else {
  964. klog.V(1).Info("Success: retrieved the 'up' query against Thanos at: " + thanosUrl)
  965. A.ThanosClient = thanosCli
  966. }
  967. } else {
  968. klog.Infof("Error resolving environment variable: $%s", thanosQueryUrl)
  969. }
  970. }
  971. err = A.Cloud.DownloadPricingData()
  972. if err != nil {
  973. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  974. }
  975. A.recordPrices()
  976. managerEndpoints := cm.NewClusterManagerEndpoints(A.ClusterManager)
  977. Router.GET("/costDataModel", A.CostDataModel)
  978. Router.GET("/costDataModelRange", A.CostDataModelRange)
  979. Router.GET("/costDataModelRangeLarge", A.CostDataModelRangeLarge)
  980. Router.GET("/outOfClusterCosts", A.OutOfClusterCostsWithCache)
  981. Router.GET("/allNodePricing", A.GetAllNodePricing)
  982. Router.POST("/refreshPricing", A.RefreshPricingData)
  983. Router.GET("/clusterCostsOverTime", A.ClusterCostsOverTime)
  984. Router.GET("/clusterCosts", A.ClusterCosts)
  985. Router.GET("/validatePrometheus", A.GetPrometheusMetadata)
  986. Router.GET("/managementPlatform", A.ManagementPlatform)
  987. Router.GET("/clusterInfo", A.ClusterInfo)
  988. Router.GET("/clusters", managerEndpoints.GetAllClusters)
  989. Router.PUT("/clusters", managerEndpoints.PutCluster)
  990. Router.DELETE("/clusters/:id", managerEndpoints.DeleteCluster)
  991. }