router.go 35 KB

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