router.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "net/http"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "k8s.io/klog"
  14. "github.com/julienschmidt/httprouter"
  15. sentry "github.com/getsentry/sentry-go"
  16. "github.com/kubecost/cost-model/pkg/cloud"
  17. "github.com/kubecost/cost-model/pkg/clustercache"
  18. cm "github.com/kubecost/cost-model/pkg/clustermanager"
  19. "github.com/kubecost/cost-model/pkg/costmodel/clusters"
  20. "github.com/kubecost/cost-model/pkg/env"
  21. "github.com/kubecost/cost-model/pkg/errors"
  22. "github.com/kubecost/cost-model/pkg/kubecost"
  23. "github.com/kubecost/cost-model/pkg/log"
  24. "github.com/kubecost/cost-model/pkg/prom"
  25. "github.com/kubecost/cost-model/pkg/thanos"
  26. prometheus "github.com/prometheus/client_golang/api"
  27. prometheusClient "github.com/prometheus/client_golang/api"
  28. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  29. v1 "k8s.io/api/core/v1"
  30. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  31. "github.com/patrickmn/go-cache"
  32. "k8s.io/client-go/kubernetes"
  33. "k8s.io/client-go/rest"
  34. "k8s.io/client-go/tools/clientcmd"
  35. )
  36. const (
  37. prometheusTroubleshootingEp = "http://docs.kubecost.com/custom-prom#troubleshoot"
  38. RFC3339Milli = "2006-01-02T15:04:05.000Z"
  39. maxCacheMinutes1d = 11
  40. maxCacheMinutes2d = 17
  41. maxCacheMinutes7d = 37
  42. maxCacheMinutes30d = 137
  43. CustomPricingSetting = "CustomPricing"
  44. DiscountSetting = "Discount"
  45. )
  46. var (
  47. // gitCommit is set by the build system
  48. gitCommit string
  49. )
  50. // Accesses defines a singleton application instance, providing access to
  51. // Prometheus, Kubernetes, the cloud provider, and caches.
  52. type Accesses struct {
  53. Router *httprouter.Router
  54. PrometheusClient prometheusClient.Client
  55. ThanosClient prometheusClient.Client
  56. KubeClientSet kubernetes.Interface
  57. ClusterManager *cm.ClusterManager
  58. ClusterMap clusters.ClusterMap
  59. CloudProvider cloud.Provider
  60. Model *CostModel
  61. MetricsEmitter *CostModelMetricsEmitter
  62. OutOfClusterCache *cache.Cache
  63. AggregateCache *cache.Cache
  64. CostDataCache *cache.Cache
  65. ClusterCostsCache *cache.Cache
  66. CacheExpiration map[time.Duration]time.Duration
  67. AggAPI Aggregator
  68. // SettingsCache stores current state of app settings
  69. SettingsCache *cache.Cache
  70. // settingsSubscribers tracks channels through which changes to different
  71. // settings will be published in a pub/sub model
  72. settingsSubscribers map[string][]chan string
  73. settingsMutex sync.Mutex
  74. }
  75. // GetPrometheusClient decides whether the default Prometheus client or the Thanos client
  76. // should be used.
  77. func (a *Accesses) GetPrometheusClient(remote bool) prometheusClient.Client {
  78. // Use Thanos Client if it exists (enabled) and remote flag set
  79. var pc prometheusClient.Client
  80. if remote && a.ThanosClient != nil {
  81. pc = a.ThanosClient
  82. } else {
  83. pc = a.PrometheusClient
  84. }
  85. return pc
  86. }
  87. // GetCacheExpiration looks up and returns custom cache expiration for the given duration.
  88. // If one does not exists, it returns the default cache expiration, which is defined by
  89. // the particular cache.
  90. func (a *Accesses) GetCacheExpiration(dur time.Duration) time.Duration {
  91. if expiration, ok := a.CacheExpiration[dur]; ok {
  92. return expiration
  93. }
  94. return cache.DefaultExpiration
  95. }
  96. // GetCacheRefresh determines how long to wait before refreshing the cache for the given duration,
  97. // which is done 1 minute before we expect the cache to expire, or 1 minute if expiration is
  98. // not found or is less than 2 minutes.
  99. func (a *Accesses) GetCacheRefresh(dur time.Duration) time.Duration {
  100. expiry := a.GetCacheExpiration(dur).Minutes()
  101. if expiry <= 2.0 {
  102. return time.Minute
  103. }
  104. mins := time.Duration(expiry/2.0) * time.Minute
  105. return mins
  106. }
  107. func (a *Accesses) ClusterCostsFromCacheHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  108. w.Header().Set("Content-Type", "application/json")
  109. durationHrs := "24h"
  110. offset := "1m"
  111. pClient := a.GetPrometheusClient(true)
  112. key := fmt.Sprintf("%s:%s", durationHrs, offset)
  113. if data, valid := a.ClusterCostsCache.Get(key); valid {
  114. clusterCosts := data.(map[string]*ClusterCosts)
  115. w.Write(WrapDataWithMessage(clusterCosts, nil, "clusterCosts cache hit"))
  116. } else {
  117. data, err := a.ComputeClusterCosts(pClient, a.CloudProvider, durationHrs, offset, true)
  118. w.Write(WrapDataWithMessage(data, err, fmt.Sprintf("clusterCosts cache miss: %s", key)))
  119. }
  120. }
  121. type Response struct {
  122. Code int `json:"code"`
  123. Status string `json:"status"`
  124. Data interface{} `json:"data"`
  125. Message string `json:"message,omitempty"`
  126. Warning string `json:"warning,omitempty"`
  127. }
  128. // 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
  129. type FilterFunc func(*CostData) (bool, string)
  130. // FilterCostData allows through only CostData that matches all the given filter functions
  131. func FilterCostData(data map[string]*CostData, retains []FilterFunc, filters []FilterFunc) (map[string]*CostData, int, map[string]int) {
  132. result := make(map[string]*CostData)
  133. filteredEnvironments := make(map[string]int)
  134. filteredContainers := 0
  135. DataLoop:
  136. for key, datum := range data {
  137. for _, rf := range retains {
  138. if ok, _ := rf(datum); ok {
  139. result[key] = datum
  140. // if any retain function passes, the data is retained and move on
  141. continue DataLoop
  142. }
  143. }
  144. for _, ff := range filters {
  145. if ok, environment := ff(datum); !ok {
  146. if environment != "" {
  147. filteredEnvironments[environment]++
  148. }
  149. filteredContainers++
  150. // if any filter function check fails, move on to the next datum
  151. continue DataLoop
  152. }
  153. }
  154. result[key] = datum
  155. }
  156. return result, filteredContainers, filteredEnvironments
  157. }
  158. func filterFields(fields string, data map[string]*CostData) map[string]CostData {
  159. fs := strings.Split(fields, ",")
  160. fmap := make(map[string]bool)
  161. for _, f := range fs {
  162. fieldNameLower := strings.ToLower(f) // convert to go struct name by uppercasing first letter
  163. klog.V(1).Infof("to delete: %s", fieldNameLower)
  164. fmap[fieldNameLower] = true
  165. }
  166. filteredData := make(map[string]CostData)
  167. for cname, costdata := range data {
  168. s := reflect.TypeOf(*costdata)
  169. val := reflect.ValueOf(*costdata)
  170. costdata2 := CostData{}
  171. cd2 := reflect.New(reflect.Indirect(reflect.ValueOf(costdata2)).Type()).Elem()
  172. n := s.NumField()
  173. for i := 0; i < n; i++ {
  174. field := s.Field(i)
  175. value := val.Field(i)
  176. value2 := cd2.Field(i)
  177. if _, ok := fmap[strings.ToLower(field.Name)]; !ok {
  178. value2.Set(reflect.Value(value))
  179. }
  180. }
  181. filteredData[cname] = cd2.Interface().(CostData)
  182. }
  183. return filteredData
  184. }
  185. func normalizeTimeParam(param string) (string, error) {
  186. if param == "" {
  187. return "", fmt.Errorf("invalid time param")
  188. }
  189. // convert days to hours
  190. if param[len(param)-1:] == "d" {
  191. count := param[:len(param)-1]
  192. val, err := strconv.ParseInt(count, 10, 64)
  193. if err != nil {
  194. return "", err
  195. }
  196. val = val * 24
  197. param = fmt.Sprintf("%dh", val)
  198. }
  199. return param, nil
  200. }
  201. // parsePercentString takes a string of expected format "N%" and returns a floating point 0.0N.
  202. // If the "%" symbol is missing, it just returns 0.0N. Empty string is interpreted as "0%" and
  203. // return 0.0.
  204. func ParsePercentString(percentStr string) (float64, error) {
  205. if len(percentStr) == 0 {
  206. return 0.0, nil
  207. }
  208. if percentStr[len(percentStr)-1:] == "%" {
  209. percentStr = percentStr[:len(percentStr)-1]
  210. }
  211. discount, err := strconv.ParseFloat(percentStr, 64)
  212. if err != nil {
  213. return 0.0, err
  214. }
  215. discount *= 0.01
  216. return discount, nil
  217. }
  218. // parseDuration converts a Prometheus-style duration string into a Duration
  219. func ParseDuration(duration string) (*time.Duration, error) {
  220. unitStr := duration[len(duration)-1:]
  221. var unit time.Duration
  222. switch unitStr {
  223. case "s":
  224. unit = time.Second
  225. case "m":
  226. unit = time.Minute
  227. case "h":
  228. unit = time.Hour
  229. case "d":
  230. unit = 24.0 * time.Hour
  231. default:
  232. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  233. }
  234. amountStr := duration[:len(duration)-1]
  235. amount, err := strconv.ParseInt(amountStr, 10, 64)
  236. if err != nil {
  237. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  238. }
  239. dur := time.Duration(amount) * unit
  240. return &dur, nil
  241. }
  242. // ParseTimeRange returns a start and end time, respectively, which are converted from
  243. // a duration and offset, defined as strings with Prometheus-style syntax.
  244. func ParseTimeRange(duration, offset string) (*time.Time, *time.Time, error) {
  245. // endTime defaults to the current time, unless an offset is explicity declared,
  246. // in which case it shifts endTime back by given duration
  247. endTime := time.Now()
  248. if offset != "" {
  249. o, err := ParseDuration(offset)
  250. if err != nil {
  251. return nil, nil, fmt.Errorf("error parsing offset (%s): %s", offset, err)
  252. }
  253. endTime = endTime.Add(-1 * *o)
  254. }
  255. // if duration is defined in terms of days, convert to hours
  256. // e.g. convert "2d" to "48h"
  257. durationNorm, err := normalizeTimeParam(duration)
  258. if err != nil {
  259. return nil, nil, fmt.Errorf("error parsing duration (%s): %s", duration, err)
  260. }
  261. // convert time duration into start and end times, formatted
  262. // as ISO datetime strings
  263. dur, err := time.ParseDuration(durationNorm)
  264. if err != nil {
  265. return nil, nil, fmt.Errorf("errorf parsing duration (%s): %s", durationNorm, err)
  266. }
  267. startTime := endTime.Add(-1 * dur)
  268. return &startTime, &endTime, nil
  269. }
  270. func WrapData(data interface{}, err error) []byte {
  271. var resp []byte
  272. if err != nil {
  273. klog.V(1).Infof("Error returned to client: %s", err.Error())
  274. resp, _ = json.Marshal(&Response{
  275. Code: http.StatusInternalServerError,
  276. Status: "error",
  277. Message: err.Error(),
  278. Data: data,
  279. })
  280. } else {
  281. resp, _ = json.Marshal(&Response{
  282. Code: http.StatusOK,
  283. Status: "success",
  284. Data: data,
  285. })
  286. }
  287. return resp
  288. }
  289. func WrapDataWithMessage(data interface{}, err error, message string) []byte {
  290. var resp []byte
  291. if err != nil {
  292. klog.V(1).Infof("Error returned to client: %s", err.Error())
  293. resp, _ = json.Marshal(&Response{
  294. Code: http.StatusInternalServerError,
  295. Status: "error",
  296. Message: err.Error(),
  297. Data: data,
  298. })
  299. } else {
  300. resp, _ = json.Marshal(&Response{
  301. Code: http.StatusOK,
  302. Status: "success",
  303. Data: data,
  304. Message: message,
  305. })
  306. }
  307. return resp
  308. }
  309. func WrapDataWithWarning(data interface{}, err error, warning string) []byte {
  310. var resp []byte
  311. if err != nil {
  312. klog.V(1).Infof("Error returned to client: %s", err.Error())
  313. resp, _ = json.Marshal(&Response{
  314. Code: http.StatusInternalServerError,
  315. Status: "error",
  316. Message: err.Error(),
  317. Warning: warning,
  318. Data: data,
  319. })
  320. } else {
  321. resp, _ = json.Marshal(&Response{
  322. Code: http.StatusOK,
  323. Status: "success",
  324. Data: data,
  325. Warning: warning,
  326. })
  327. }
  328. return resp
  329. }
  330. func WrapDataWithMessageAndWarning(data interface{}, err error, message, warning string) []byte {
  331. var resp []byte
  332. if err != nil {
  333. klog.V(1).Infof("Error returned to client: %s", err.Error())
  334. resp, _ = json.Marshal(&Response{
  335. Code: http.StatusInternalServerError,
  336. Status: "error",
  337. Message: err.Error(),
  338. Warning: warning,
  339. Data: data,
  340. })
  341. } else {
  342. resp, _ = json.Marshal(&Response{
  343. Code: http.StatusOK,
  344. Status: "success",
  345. Data: data,
  346. Message: message,
  347. Warning: warning,
  348. })
  349. }
  350. return resp
  351. }
  352. // 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.
  353. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  354. w.Header().Set("Content-Type", "application/json")
  355. w.Header().Set("Access-Control-Allow-Origin", "*")
  356. err := a.CloudProvider.DownloadPricingData()
  357. w.Write(WrapData(nil, err))
  358. }
  359. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  360. w.Header().Set("Content-Type", "application/json")
  361. w.Header().Set("Access-Control-Allow-Origin", "*")
  362. window := r.URL.Query().Get("timeWindow")
  363. offset := r.URL.Query().Get("offset")
  364. fields := r.URL.Query().Get("filterFields")
  365. namespace := r.URL.Query().Get("namespace")
  366. if offset != "" {
  367. offset = "offset " + offset
  368. }
  369. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.CloudProvider, window, offset, namespace)
  370. if fields != "" {
  371. filteredData := filterFields(fields, data)
  372. w.Write(WrapData(filteredData, err))
  373. } else {
  374. w.Write(WrapData(data, err))
  375. }
  376. }
  377. func (a *Accesses) ClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  378. w.Header().Set("Content-Type", "application/json")
  379. w.Header().Set("Access-Control-Allow-Origin", "*")
  380. window := r.URL.Query().Get("window")
  381. offset := r.URL.Query().Get("offset")
  382. useThanos, _ := strconv.ParseBool(r.URL.Query().Get("multi"))
  383. if useThanos && !thanos.IsEnabled() {
  384. w.Write(WrapData(nil, fmt.Errorf("Multi=true while Thanos is not enabled.")))
  385. return
  386. }
  387. var client prometheusClient.Client
  388. if useThanos {
  389. client = a.ThanosClient
  390. offset = thanos.Offset()
  391. } else {
  392. client = a.PrometheusClient
  393. }
  394. data, err := a.ComputeClusterCosts(client, a.CloudProvider, window, offset, true)
  395. w.Write(WrapData(data, err))
  396. }
  397. func (a *Accesses) ClusterCostsOverTime(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. window := r.URL.Query().Get("window")
  403. offset := r.URL.Query().Get("offset")
  404. data, err := ClusterCostsOverTime(a.PrometheusClient, a.CloudProvider, start, end, window, offset)
  405. w.Write(WrapData(data, err))
  406. }
  407. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  408. w.Header().Set("Content-Type", "application/json")
  409. w.Header().Set("Access-Control-Allow-Origin", "*")
  410. startStr := r.URL.Query().Get("start")
  411. endStr := r.URL.Query().Get("end")
  412. windowStr := r.URL.Query().Get("window")
  413. fields := r.URL.Query().Get("filterFields")
  414. namespace := r.URL.Query().Get("namespace")
  415. cluster := r.URL.Query().Get("cluster")
  416. remote := r.URL.Query().Get("remote")
  417. remoteEnabled := env.IsRemoteEnabled() && remote != "false"
  418. layout := "2006-01-02T15:04:05.000Z"
  419. start, err := time.Parse(layout, startStr)
  420. if err != nil {
  421. w.Write(WrapDataWithMessage(nil, fmt.Errorf("invalid start date: %s", startStr), fmt.Sprintf("invalid start date: %s", startStr)))
  422. return
  423. }
  424. end, err := time.Parse(layout, endStr)
  425. if err != nil {
  426. w.Write(WrapDataWithMessage(nil, fmt.Errorf("invalid end date: %s", endStr), fmt.Sprintf("invalid end date: %s", endStr)))
  427. return
  428. }
  429. window := kubecost.NewWindow(&start, &end)
  430. if window.IsOpen() || window.IsEmpty() || window.IsNegative() {
  431. w.Write(WrapDataWithMessage(nil, fmt.Errorf("invalid date range: %s", window), fmt.Sprintf("invalid date range: %s", window)))
  432. return
  433. }
  434. resolution := time.Hour
  435. if resDur, err := time.ParseDuration(windowStr); err == nil {
  436. resolution = resDur
  437. }
  438. // Use Thanos Client if it exists (enabled) and remote flag set
  439. var pClient prometheusClient.Client
  440. if remote != "false" && a.ThanosClient != nil {
  441. pClient = a.ThanosClient
  442. } else {
  443. pClient = a.PrometheusClient
  444. }
  445. data, err := a.Model.ComputeCostDataRange(pClient, a.CloudProvider, window, resolution, namespace, cluster, remoteEnabled)
  446. if err != nil {
  447. w.Write(WrapData(nil, err))
  448. }
  449. if fields != "" {
  450. filteredData := filterFields(fields, data)
  451. w.Write(WrapData(filteredData, err))
  452. } else {
  453. w.Write(WrapData(data, err))
  454. }
  455. }
  456. func parseAggregations(customAggregation, aggregator, filterType string) (string, []string, string) {
  457. var key string
  458. var filter string
  459. var val []string
  460. if customAggregation != "" {
  461. key = customAggregation
  462. filter = filterType
  463. val = strings.Split(customAggregation, ",")
  464. } else {
  465. aggregations := strings.Split(aggregator, ",")
  466. for i, agg := range aggregations {
  467. aggregations[i] = "kubernetes_" + agg
  468. }
  469. key = strings.Join(aggregations, ",")
  470. filter = "kubernetes_" + filterType
  471. val = aggregations
  472. }
  473. return key, val, filter
  474. }
  475. func (a *Accesses) OutofClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  476. w.Header().Set("Content-Type", "application/json")
  477. w.Header().Set("Access-Control-Allow-Origin", "*")
  478. start := r.URL.Query().Get("start")
  479. end := r.URL.Query().Get("end")
  480. aggregator := r.URL.Query().Get("aggregator")
  481. customAggregation := r.URL.Query().Get("customAggregation")
  482. filterType := r.URL.Query().Get("filterType")
  483. filterValue := r.URL.Query().Get("filterValue")
  484. var data []*cloud.OutOfClusterAllocation
  485. var err error
  486. _, aggregations, filter := parseAggregations(customAggregation, aggregator, filterType)
  487. data, err = a.CloudProvider.ExternalAllocations(start, end, aggregations, filter, filterValue, false)
  488. w.Write(WrapData(data, err))
  489. }
  490. func (a *Accesses) OutOfClusterCostsWithCache(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. // start date for which to query costs, inclusive; format YYYY-MM-DD
  494. start := r.URL.Query().Get("start")
  495. // end date for which to query costs, inclusive; format YYYY-MM-DD
  496. end := r.URL.Query().Get("end")
  497. // aggregator sets the field by which to aggregate; default, prepended by "kubernetes_"
  498. kubernetesAggregation := r.URL.Query().Get("aggregator")
  499. // customAggregation allows full customization of aggregator w/o prepending
  500. customAggregation := r.URL.Query().Get("customAggregation")
  501. // disableCache, if set to "true", tells this function to recompute and
  502. // cache the requested data
  503. disableCache := r.URL.Query().Get("disableCache") == "true"
  504. // clearCache, if set to "true", tells this function to flush the cache,
  505. // then recompute and cache the requested data
  506. clearCache := r.URL.Query().Get("clearCache") == "true"
  507. filterType := r.URL.Query().Get("filterType")
  508. filterValue := r.URL.Query().Get("filterValue")
  509. aggregationkey, aggregation, filter := parseAggregations(customAggregation, kubernetesAggregation, filterType)
  510. // clear cache prior to checking the cache so that a clearCache=true
  511. // request always returns a freshly computed value
  512. if clearCache {
  513. a.OutOfClusterCache.Flush()
  514. }
  515. // attempt to retrieve cost data from cache
  516. key := fmt.Sprintf(`%s:%s:%s:%s:%s`, start, end, aggregationkey, filter, filterValue)
  517. if value, found := a.OutOfClusterCache.Get(key); found && !disableCache {
  518. if data, ok := value.([]*cloud.OutOfClusterAllocation); ok {
  519. w.Write(WrapDataWithMessage(data, nil, fmt.Sprintf("out of cluster cache hit: %s", key)))
  520. return
  521. }
  522. klog.Errorf("caching error: failed to type cast data: %s", key)
  523. }
  524. data, err := a.CloudProvider.ExternalAllocations(start, end, aggregation, filter, filterValue, false)
  525. if err == nil {
  526. a.OutOfClusterCache.Set(key, data, cache.DefaultExpiration)
  527. }
  528. w.Write(WrapDataWithMessage(data, err, fmt.Sprintf("out of cluser cache miss: %s", key)))
  529. }
  530. func (a *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  531. w.Header().Set("Content-Type", "application/json")
  532. w.Header().Set("Access-Control-Allow-Origin", "*")
  533. data, err := a.CloudProvider.AllNodePricing()
  534. w.Write(WrapData(data, err))
  535. }
  536. func (a *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  537. w.Header().Set("Content-Type", "application/json")
  538. w.Header().Set("Access-Control-Allow-Origin", "*")
  539. data, err := a.CloudProvider.GetConfig()
  540. w.Write(WrapData(data, err))
  541. }
  542. func (a *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  543. w.Header().Set("Content-Type", "application/json")
  544. w.Header().Set("Access-Control-Allow-Origin", "*")
  545. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.SpotInfoUpdateType)
  546. if err != nil {
  547. w.Write(WrapData(data, err))
  548. return
  549. }
  550. w.Write(WrapData(data, err))
  551. err = a.CloudProvider.DownloadPricingData()
  552. if err != nil {
  553. klog.V(1).Infof("Error redownloading data on config update: %s", err.Error())
  554. }
  555. return
  556. }
  557. func (a *Accesses) UpdateAthenaInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  558. w.Header().Set("Content-Type", "application/json")
  559. w.Header().Set("Access-Control-Allow-Origin", "*")
  560. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.AthenaInfoUpdateType)
  561. if err != nil {
  562. w.Write(WrapData(data, err))
  563. return
  564. }
  565. w.Write(WrapData(data, err))
  566. return
  567. }
  568. func (a *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  569. w.Header().Set("Content-Type", "application/json")
  570. w.Header().Set("Access-Control-Allow-Origin", "*")
  571. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.BigqueryUpdateType)
  572. if err != nil {
  573. w.Write(WrapData(data, err))
  574. return
  575. }
  576. w.Write(WrapData(data, err))
  577. return
  578. }
  579. func (a *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  580. w.Header().Set("Content-Type", "application/json")
  581. w.Header().Set("Access-Control-Allow-Origin", "*")
  582. data, err := a.CloudProvider.UpdateConfig(r.Body, "")
  583. if err != nil {
  584. w.Write(WrapData(data, err))
  585. return
  586. }
  587. w.Write(WrapData(data, err))
  588. return
  589. }
  590. func (a *Accesses) ManagementPlatform(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  591. w.Header().Set("Content-Type", "application/json")
  592. w.Header().Set("Access-Control-Allow-Origin", "*")
  593. data, err := a.CloudProvider.GetManagementPlatform()
  594. if err != nil {
  595. w.Write(WrapData(data, err))
  596. return
  597. }
  598. w.Write(WrapData(data, err))
  599. return
  600. }
  601. func (a *Accesses) ClusterInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  602. w.Header().Set("Content-Type", "application/json")
  603. w.Header().Set("Access-Control-Allow-Origin", "*")
  604. data := GetClusterInfo(a.KubeClientSet, a.CloudProvider)
  605. w.Write(WrapData(data, nil))
  606. }
  607. func (a *Accesses) GetClusterInfoMap(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  608. w.Header().Set("Content-Type", "application/json")
  609. w.Header().Set("Access-Control-Allow-Origin", "*")
  610. data := a.ClusterMap.AsMap()
  611. w.Write(WrapData(data, nil))
  612. }
  613. func (a *Accesses) GetServiceAccountStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  614. w.Header().Set("Content-Type", "application/json")
  615. w.Header().Set("Access-Control-Allow-Origin", "*")
  616. w.Write(WrapData(a.CloudProvider.ServiceAccountStatus(), nil))
  617. }
  618. func (a *Accesses) GetPricingSourceStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  619. w.Header().Set("Content-Type", "application/json")
  620. w.Header().Set("Access-Control-Allow-Origin", "*")
  621. w.Write(WrapData(a.CloudProvider.PricingSourceStatus(), nil))
  622. }
  623. func (a *Accesses) GetPricingSourceCounts(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  624. w.Header().Set("Content-Type", "application/json")
  625. w.Header().Set("Access-Control-Allow-Origin", "*")
  626. w.Write(WrapData(a.Model.GetPricingSourceCounts()))
  627. }
  628. func (a *Accesses) GetPrometheusMetadata(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  629. w.Header().Set("Content-Type", "application/json")
  630. w.Header().Set("Access-Control-Allow-Origin", "*")
  631. w.Write(WrapData(prom.Validate(a.PrometheusClient)))
  632. }
  633. // Creates a new ClusterManager instance using a boltdb storage. If that fails,
  634. // then we fall back to a memory-only storage.
  635. func newClusterManager() *cm.ClusterManager {
  636. clustersConfigFile := "/var/configs/clusters/default-clusters.yaml"
  637. // Return a memory-backed cluster manager populated by configmap
  638. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  639. // NOTE: The following should be used with a persistent disk store. Since the
  640. // NOTE: configmap approach is currently the "persistent" source (entries are read-only
  641. // NOTE: on the backend), we don't currently need to store on disk.
  642. /*
  643. path := env.GetConfigPath()
  644. db, err := bolt.Open(path+"costmodel.db", 0600, nil)
  645. if err != nil {
  646. klog.V(1).Infof("[Error] Failed to create costmodel.db: %s", err.Error())
  647. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  648. }
  649. store, err := cm.NewBoltDBClusterStorage("clusters", db)
  650. if err != nil {
  651. klog.V(1).Infof("[Error] Failed to Create Cluster Storage: %s", err.Error())
  652. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  653. }
  654. return cm.NewConfiguredClusterManager(store, clustersConfigFile)
  655. */
  656. }
  657. type ConfigWatchers struct {
  658. ConfigmapName string
  659. WatchFunc func(string, map[string]string) error
  660. }
  661. // captures the panic event in sentry
  662. func capturePanicEvent(err string, stack string) {
  663. msg := fmt.Sprintf("Panic: %s\nStackTrace: %s\n", err, stack)
  664. klog.V(1).Infoln(msg)
  665. sentry.CurrentHub().CaptureEvent(&sentry.Event{
  666. Level: sentry.LevelError,
  667. Message: msg,
  668. })
  669. sentry.Flush(5 * time.Second)
  670. }
  671. // handle any panics reported by the errors package
  672. func handlePanic(p errors.Panic) bool {
  673. err := p.Error
  674. if err != nil {
  675. if err, ok := err.(error); ok {
  676. capturePanicEvent(err.Error(), p.Stack)
  677. }
  678. if err, ok := err.(string); ok {
  679. capturePanicEvent(err, p.Stack)
  680. }
  681. }
  682. // Return true to recover iff the type is http, otherwise allow kubernetes
  683. // to recover.
  684. return p.Type == errors.PanicTypeHTTP
  685. }
  686. func Initialize(additionalConfigWatchers ...ConfigWatchers) *Accesses {
  687. klog.InitFlags(nil)
  688. flag.Set("v", "3")
  689. flag.Parse()
  690. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", env.GetAppVersion())
  691. var err error
  692. if errorReportingEnabled {
  693. err = sentry.Init(sentry.ClientOptions{Release: env.GetAppVersion()})
  694. if err != nil {
  695. klog.Infof("Failed to initialize sentry for error reporting")
  696. } else {
  697. err = errors.SetPanicHandler(handlePanic)
  698. if err != nil {
  699. klog.Infof("Failed to set panic handler: %s", err)
  700. }
  701. }
  702. }
  703. address := env.GetPrometheusServerEndpoint()
  704. if address == "" {
  705. klog.Fatalf("No address for prometheus set in $%s. Aborting.", env.PrometheusServerEndpointEnvVar)
  706. }
  707. queryConcurrency := env.GetMaxQueryConcurrency()
  708. klog.Infof("Prometheus/Thanos Client Max Concurrency set to %d", queryConcurrency)
  709. timeout := 120 * time.Second
  710. keepAlive := 120 * time.Second
  711. scrapeInterval, _ := time.ParseDuration("1m")
  712. promCli, _ := prom.NewPrometheusClient(address, timeout, keepAlive, queryConcurrency, "")
  713. api := prometheusAPI.NewAPI(promCli)
  714. pcfg, err := api.Config(context.Background())
  715. if err != nil {
  716. klog.Infof("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s. Ignore if using cortex/thanos here.", address, err.Error(), prometheusTroubleshootingEp)
  717. } else {
  718. klog.V(1).Info("Retrieved a prometheus config file from: " + address)
  719. sc, err := GetPrometheusConfig(pcfg.YAML)
  720. if err != nil {
  721. klog.Infof("Fix YAML error %s", err)
  722. }
  723. for _, scrapeconfig := range sc.ScrapeConfigs {
  724. if scrapeconfig.JobName == GetKubecostJobName() {
  725. if scrapeconfig.ScrapeInterval != "" {
  726. si := scrapeconfig.ScrapeInterval
  727. sid, err := time.ParseDuration(si)
  728. if err != nil {
  729. klog.Infof("error parseing scrapeConfig for %s", scrapeconfig.JobName)
  730. } else {
  731. klog.Infof("Found Kubecost job scrape interval of: %s", si)
  732. scrapeInterval = sid
  733. }
  734. }
  735. }
  736. }
  737. }
  738. klog.Infof("Using scrape interval of %f", scrapeInterval.Seconds())
  739. m, err := prom.Validate(promCli)
  740. if err != nil || m.Running == false {
  741. if err != nil {
  742. klog.Errorf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  743. } else if m.Running == false {
  744. klog.Errorf("Prometheus at %s is not running. Troubleshooting help available at: %s", address, prometheusTroubleshootingEp)
  745. }
  746. api := prometheusAPI.NewAPI(promCli)
  747. _, err = api.Config(context.Background())
  748. if err != nil {
  749. klog.Infof("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s. Ignore if using cortex/thanos here.", address, err.Error(), prometheusTroubleshootingEp)
  750. } else {
  751. klog.V(1).Info("Retrieved a prometheus config file from: " + address)
  752. }
  753. } else {
  754. klog.V(1).Info("Success: retrieved the 'up' query against prometheus at: " + address)
  755. }
  756. // Kubernetes API setup
  757. var kc *rest.Config
  758. if kubeconfig := env.GetKubeConfigPath(); kubeconfig != "" {
  759. kc, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
  760. } else {
  761. kc, err = rest.InClusterConfig()
  762. }
  763. if err != nil {
  764. panic(err.Error())
  765. }
  766. kubeClientset, err := kubernetes.NewForConfig(kc)
  767. if err != nil {
  768. panic(err.Error())
  769. }
  770. // Create Kubernetes Cluster Cache + Watchers
  771. k8sCache := clustercache.NewKubernetesClusterCache(kubeClientset)
  772. k8sCache.Run()
  773. cloudProviderKey := env.GetCloudProviderAPIKey()
  774. cloudProvider, err := cloud.NewProvider(k8sCache, cloudProviderKey)
  775. if err != nil {
  776. panic(err.Error())
  777. }
  778. watchConfigFunc := func(c interface{}) {
  779. conf := c.(*v1.ConfigMap)
  780. if conf.GetName() == "pricing-configs" {
  781. _, err := cloudProvider.UpdateConfigFromConfigMap(conf.Data)
  782. if err != nil {
  783. klog.Infof("ERROR UPDATING %s CONFIG: %s", "pricing-configs", err.Error())
  784. }
  785. }
  786. for _, cw := range additionalConfigWatchers {
  787. if conf.GetName() == cw.ConfigmapName {
  788. err := cw.WatchFunc(conf.GetName(), conf.Data)
  789. if err != nil {
  790. klog.Infof("ERROR UPDATING %s CONFIG: %s", cw.ConfigmapName, err.Error())
  791. }
  792. }
  793. }
  794. }
  795. kubecostNamespace := env.GetKubecostNamespace()
  796. // We need an initial invocation because the init of the cache has happened before we had access to the provider.
  797. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get("pricing-configs", metav1.GetOptions{})
  798. if err != nil {
  799. klog.Infof("No %s configmap found at installtime, using existing configs: %s", "pricing-configs", err.Error())
  800. } else {
  801. watchConfigFunc(configs)
  802. }
  803. for _, cw := range additionalConfigWatchers {
  804. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get(cw.ConfigmapName, metav1.GetOptions{})
  805. if err != nil {
  806. klog.Infof("No %s configmap found at installtime, using existing configs: %s", cw.ConfigmapName, err.Error())
  807. } else {
  808. watchConfigFunc(configs)
  809. }
  810. }
  811. k8sCache.SetConfigMapUpdateFunc(watchConfigFunc)
  812. // TODO: General Architecture Note: Several passes have been made to modularize a lot of
  813. // TODO: our code, but the router still continues to be the obvious entry point for new \
  814. // TODO: features. We should look to split out the actual "router" functionality and
  815. // TODO: implement a builder -> controller for stitching new features and other dependencies.
  816. clusterManager := newClusterManager()
  817. // Initialize metrics here
  818. remoteEnabled := env.IsRemoteEnabled()
  819. if remoteEnabled {
  820. info, err := cloudProvider.ClusterInfo()
  821. klog.Infof("Saving cluster with id:'%s', and name:'%s' to durable storage", info["id"], info["name"])
  822. if err != nil {
  823. klog.Infof("Error saving cluster id %s", err.Error())
  824. }
  825. _, _, err = cloud.GetOrCreateClusterMeta(info["id"], info["name"])
  826. if err != nil {
  827. klog.Infof("Unable to set cluster id '%s' for cluster '%s', %s", info["id"], info["name"], err.Error())
  828. }
  829. }
  830. // Thanos Client
  831. var thanosClient prometheusClient.Client
  832. if thanos.IsEnabled() {
  833. thanosAddress := thanos.QueryURL()
  834. if thanosAddress != "" {
  835. thanosCli, _ := thanos.NewThanosClient(thanosAddress, timeout, keepAlive, queryConcurrency, env.GetQueryLoggingFile())
  836. _, err = prom.Validate(thanosCli)
  837. if err != nil {
  838. klog.V(1).Infof("[Warning] Failed to query Thanos at %s. Error: %s.", thanosAddress, err.Error())
  839. thanosClient = thanosCli
  840. } else {
  841. klog.V(1).Info("Success: retrieved the 'up' query against Thanos at: " + thanosAddress)
  842. thanosClient = thanosCli
  843. }
  844. } else {
  845. klog.Infof("Error resolving environment variable: $%s", env.ThanosQueryUrlEnvVar)
  846. }
  847. }
  848. // Initialize ClusterMap for maintaining ClusterInfo by ClusterID
  849. var clusterMap clusters.ClusterMap
  850. if thanosClient != nil {
  851. clusterMap = clusters.NewClusterMap(thanosClient, 10*time.Minute)
  852. } else {
  853. clusterMap = clusters.NewClusterMap(promCli, 5*time.Minute)
  854. }
  855. // cache responses from model and aggregation for a default of 10 minutes;
  856. // clear expired responses every 20 minutes
  857. aggregateCache := cache.New(time.Minute*10, time.Minute*20)
  858. costDataCache := cache.New(time.Minute*10, time.Minute*20)
  859. clusterCostsCache := cache.New(cache.NoExpiration, cache.NoExpiration)
  860. outOfClusterCache := cache.New(time.Minute*5, time.Minute*10)
  861. settingsCache := cache.New(cache.NoExpiration, cache.NoExpiration)
  862. // query durations that should be cached longer should be registered here
  863. // use relatively prime numbers to minimize likelihood of synchronized
  864. // attempts at cache warming
  865. day := 24 * time.Hour
  866. cacheExpiration := map[time.Duration]time.Duration{
  867. day: maxCacheMinutes1d * time.Minute,
  868. 2 * day: maxCacheMinutes2d * time.Minute,
  869. 7 * day: maxCacheMinutes7d * time.Minute,
  870. 30 * day: maxCacheMinutes30d * time.Minute,
  871. }
  872. var pc prometheus.Client
  873. if thanosClient != nil {
  874. pc = thanosClient
  875. } else {
  876. pc = promCli
  877. }
  878. costModel := NewCostModel(pc, cloudProvider, k8sCache, clusterMap, scrapeInterval)
  879. metricsEmitter := NewCostModelMetricsEmitter(promCli, k8sCache, cloudProvider, costModel)
  880. a := &Accesses{
  881. Router: httprouter.New(),
  882. PrometheusClient: promCli,
  883. ThanosClient: thanosClient,
  884. KubeClientSet: kubeClientset,
  885. ClusterManager: clusterManager,
  886. ClusterMap: clusterMap,
  887. CloudProvider: cloudProvider,
  888. Model: costModel,
  889. MetricsEmitter: metricsEmitter,
  890. AggregateCache: aggregateCache,
  891. CostDataCache: costDataCache,
  892. ClusterCostsCache: clusterCostsCache,
  893. OutOfClusterCache: outOfClusterCache,
  894. SettingsCache: settingsCache,
  895. CacheExpiration: cacheExpiration,
  896. }
  897. // Use the Accesses instance, itself, as the CostModelAggregator. This is
  898. // confusing and unconventional, but necessary so that we can swap it
  899. // out for the ETL-adapted version elsewhere.
  900. // TODO clean this up once ETL is open-sourced.
  901. a.AggAPI = a
  902. // Initialize mechanism for subscribing to settings changes
  903. a.InitializeSettingsPubSub()
  904. // Warm the aggregate cache unless explicitly set to false
  905. if env.IsCacheWarmingEnabled() {
  906. log.Infof("Init: AggregateCostModel cache warming enabled")
  907. a.warmAggregateCostModelCache()
  908. } else {
  909. log.Infof("Init: AggregateCostModel cache warming disabled")
  910. }
  911. err = a.CloudProvider.DownloadPricingData()
  912. if err != nil {
  913. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  914. }
  915. a.MetricsEmitter.Start()
  916. managerEndpoints := cm.NewClusterManagerEndpoints(a.ClusterManager)
  917. a.Router.GET("/costDataModel", a.CostDataModel)
  918. a.Router.GET("/costDataModelRange", a.CostDataModelRange)
  919. a.Router.GET("/aggregatedCostModel", a.AggregateCostModelHandler)
  920. a.Router.GET("/outOfClusterCosts", a.OutOfClusterCostsWithCache)
  921. a.Router.GET("/allNodePricing", a.GetAllNodePricing)
  922. a.Router.POST("/refreshPricing", a.RefreshPricingData)
  923. a.Router.GET("/clusterCostsOverTime", a.ClusterCostsOverTime)
  924. a.Router.GET("/clusterCosts", a.ClusterCosts)
  925. a.Router.GET("/clusterCostsFromCache", a.ClusterCostsFromCacheHandler)
  926. a.Router.GET("/validatePrometheus", a.GetPrometheusMetadata)
  927. a.Router.GET("/managementPlatform", a.ManagementPlatform)
  928. a.Router.GET("/clusterInfo", a.ClusterInfo)
  929. a.Router.GET("/clusterInfoMap", a.GetClusterInfoMap)
  930. a.Router.GET("/serviceAccountStatus", a.GetServiceAccountStatus)
  931. a.Router.GET("/pricingSourceStatus", a.GetPricingSourceStatus)
  932. a.Router.GET("/pricingSourceCounts", a.GetPricingSourceCounts)
  933. // cluster manager endpoints
  934. a.Router.GET("/clusters", managerEndpoints.GetAllClusters)
  935. a.Router.PUT("/clusters", managerEndpoints.PutCluster)
  936. a.Router.DELETE("/clusters/:id", managerEndpoints.DeleteCluster)
  937. return a
  938. }