router.go 35 KB

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