router.go 39 KB

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