router.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/microcosm-cc/bluemonday"
  17. "github.com/opencost/opencost/pkg/config"
  18. "github.com/opencost/opencost/pkg/kubeconfig"
  19. "github.com/opencost/opencost/pkg/metrics"
  20. "github.com/opencost/opencost/pkg/services"
  21. "github.com/opencost/opencost/pkg/util/httputil"
  22. "github.com/opencost/opencost/pkg/util/timeutil"
  23. "github.com/opencost/opencost/pkg/util/watcher"
  24. "github.com/opencost/opencost/pkg/version"
  25. "github.com/spf13/viper"
  26. v1 "k8s.io/api/core/v1"
  27. "github.com/julienschmidt/httprouter"
  28. sentry "github.com/getsentry/sentry-go"
  29. "github.com/opencost/opencost/pkg/cloud"
  30. "github.com/opencost/opencost/pkg/clustercache"
  31. "github.com/opencost/opencost/pkg/costmodel/clusters"
  32. "github.com/opencost/opencost/pkg/env"
  33. "github.com/opencost/opencost/pkg/errors"
  34. "github.com/opencost/opencost/pkg/kubecost"
  35. "github.com/opencost/opencost/pkg/log"
  36. "github.com/opencost/opencost/pkg/prom"
  37. "github.com/opencost/opencost/pkg/thanos"
  38. "github.com/opencost/opencost/pkg/util/json"
  39. prometheus "github.com/prometheus/client_golang/api"
  40. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  41. appsv1 "k8s.io/api/apps/v1"
  42. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  43. "github.com/patrickmn/go-cache"
  44. "k8s.io/client-go/kubernetes"
  45. )
  46. var sanitizePolicy = bluemonday.UGCPolicy()
  47. const (
  48. RFC3339Milli = "2006-01-02T15:04:05.000Z"
  49. maxCacheMinutes1d = 11
  50. maxCacheMinutes2d = 17
  51. maxCacheMinutes7d = 37
  52. maxCacheMinutes30d = 137
  53. CustomPricingSetting = "CustomPricing"
  54. DiscountSetting = "Discount"
  55. epRules = apiPrefix + "/rules"
  56. LogSeparator = "+-------------------------------------------------------------------------------------"
  57. )
  58. var (
  59. // gitCommit is set by the build system
  60. gitCommit string
  61. // ANSIRegex matches ANSI escape and colors https://en.wikipedia.org/wiki/ANSI_escape_code
  62. ANSIRegex = regexp.MustCompile("\x1b\\[[0-9;]*m")
  63. )
  64. // Accesses defines a singleton application instance, providing access to
  65. // Prometheus, Kubernetes, the cloud provider, and caches.
  66. type Accesses struct {
  67. Router *httprouter.Router
  68. PrometheusClient prometheus.Client
  69. ThanosClient prometheus.Client
  70. KubeClientSet kubernetes.Interface
  71. ClusterCache clustercache.ClusterCache
  72. ClusterMap clusters.ClusterMap
  73. CloudProvider cloud.Provider
  74. ConfigFileManager *config.ConfigFileManager
  75. ClusterInfoProvider clusters.ClusterInfoProvider
  76. Model *CostModel
  77. MetricsEmitter *CostModelMetricsEmitter
  78. OutOfClusterCache *cache.Cache
  79. AggregateCache *cache.Cache
  80. CostDataCache *cache.Cache
  81. ClusterCostsCache *cache.Cache
  82. CacheExpiration map[time.Duration]time.Duration
  83. AggAPI Aggregator
  84. // SettingsCache stores current state of app settings
  85. SettingsCache *cache.Cache
  86. // settingsSubscribers tracks channels through which changes to different
  87. // settings will be published in a pub/sub model
  88. settingsSubscribers map[string][]chan string
  89. settingsMutex sync.Mutex
  90. // registered http service instances
  91. httpServices services.HTTPServices
  92. }
  93. // GetPrometheusClient decides whether the default Prometheus client or the Thanos client
  94. // should be used.
  95. func (a *Accesses) GetPrometheusClient(remote bool) prometheus.Client {
  96. // Use Thanos Client if it exists (enabled) and remote flag set
  97. var pc prometheus.Client
  98. if remote && a.ThanosClient != nil {
  99. pc = a.ThanosClient
  100. } else {
  101. pc = a.PrometheusClient
  102. }
  103. return pc
  104. }
  105. // GetCacheExpiration looks up and returns custom cache expiration for the given duration.
  106. // If one does not exists, it returns the default cache expiration, which is defined by
  107. // the particular cache.
  108. func (a *Accesses) GetCacheExpiration(dur time.Duration) time.Duration {
  109. if expiration, ok := a.CacheExpiration[dur]; ok {
  110. return expiration
  111. }
  112. return cache.DefaultExpiration
  113. }
  114. // GetCacheRefresh determines how long to wait before refreshing the cache for the given duration,
  115. // which is done 1 minute before we expect the cache to expire, or 1 minute if expiration is
  116. // not found or is less than 2 minutes.
  117. func (a *Accesses) GetCacheRefresh(dur time.Duration) time.Duration {
  118. expiry := a.GetCacheExpiration(dur).Minutes()
  119. if expiry <= 2.0 {
  120. return time.Minute
  121. }
  122. mins := time.Duration(expiry/2.0) * time.Minute
  123. return mins
  124. }
  125. func (a *Accesses) ClusterCostsFromCacheHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  126. w.Header().Set("Content-Type", "application/json")
  127. duration := 24 * time.Hour
  128. offset := time.Minute
  129. durationHrs := "24h"
  130. fmtOffset := "1m"
  131. pClient := a.GetPrometheusClient(true)
  132. key := fmt.Sprintf("%s:%s", durationHrs, fmtOffset)
  133. if data, valid := a.ClusterCostsCache.Get(key); valid {
  134. clusterCosts := data.(map[string]*ClusterCosts)
  135. w.Write(WrapDataWithMessage(clusterCosts, nil, "clusterCosts cache hit"))
  136. } else {
  137. data, err := a.ComputeClusterCosts(pClient, a.CloudProvider, duration, offset, true)
  138. w.Write(WrapDataWithMessage(data, err, fmt.Sprintf("clusterCosts cache miss: %s", key)))
  139. }
  140. }
  141. type Response struct {
  142. Code int `json:"code"`
  143. Status string `json:"status"`
  144. Data interface{} `json:"data"`
  145. Message string `json:"message,omitempty"`
  146. Warning string `json:"warning,omitempty"`
  147. }
  148. // 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
  149. type FilterFunc func(*CostData) (bool, string)
  150. // FilterCostData allows through only CostData that matches all the given filter functions
  151. func FilterCostData(data map[string]*CostData, retains []FilterFunc, filters []FilterFunc) (map[string]*CostData, int, map[string]int) {
  152. result := make(map[string]*CostData)
  153. filteredEnvironments := make(map[string]int)
  154. filteredContainers := 0
  155. DataLoop:
  156. for key, datum := range data {
  157. for _, rf := range retains {
  158. if ok, _ := rf(datum); ok {
  159. result[key] = datum
  160. // if any retain function passes, the data is retained and move on
  161. continue DataLoop
  162. }
  163. }
  164. for _, ff := range filters {
  165. if ok, environment := ff(datum); !ok {
  166. if environment != "" {
  167. filteredEnvironments[environment]++
  168. }
  169. filteredContainers++
  170. // if any filter function check fails, move on to the next datum
  171. continue DataLoop
  172. }
  173. }
  174. result[key] = datum
  175. }
  176. return result, filteredContainers, filteredEnvironments
  177. }
  178. func filterFields(fields string, data map[string]*CostData) map[string]CostData {
  179. fs := strings.Split(fields, ",")
  180. fmap := make(map[string]bool)
  181. for _, f := range fs {
  182. fieldNameLower := strings.ToLower(f) // convert to go struct name by uppercasing first letter
  183. log.Debugf("to delete: %s", fieldNameLower)
  184. fmap[fieldNameLower] = true
  185. }
  186. filteredData := make(map[string]CostData)
  187. for cname, costdata := range data {
  188. s := reflect.TypeOf(*costdata)
  189. val := reflect.ValueOf(*costdata)
  190. costdata2 := CostData{}
  191. cd2 := reflect.New(reflect.Indirect(reflect.ValueOf(costdata2)).Type()).Elem()
  192. n := s.NumField()
  193. for i := 0; i < n; i++ {
  194. field := s.Field(i)
  195. value := val.Field(i)
  196. value2 := cd2.Field(i)
  197. if _, ok := fmap[strings.ToLower(field.Name)]; !ok {
  198. value2.Set(reflect.Value(value))
  199. }
  200. }
  201. filteredData[cname] = cd2.Interface().(CostData)
  202. }
  203. return filteredData
  204. }
  205. func normalizeTimeParam(param string) (string, error) {
  206. if param == "" {
  207. return "", fmt.Errorf("invalid time param")
  208. }
  209. // convert days to hours
  210. if param[len(param)-1:] == "d" {
  211. count := param[:len(param)-1]
  212. val, err := strconv.ParseInt(count, 10, 64)
  213. if err != nil {
  214. return "", err
  215. }
  216. val = val * 24
  217. param = fmt.Sprintf("%dh", val)
  218. }
  219. return param, nil
  220. }
  221. // ParsePercentString takes a string of expected format "N%" and returns a floating point 0.0N.
  222. // If the "%" symbol is missing, it just returns 0.0N. Empty string is interpreted as "0%" and
  223. // return 0.0.
  224. func ParsePercentString(percentStr string) (float64, error) {
  225. if len(percentStr) == 0 {
  226. return 0.0, nil
  227. }
  228. if percentStr[len(percentStr)-1:] == "%" {
  229. percentStr = percentStr[:len(percentStr)-1]
  230. }
  231. discount, err := strconv.ParseFloat(percentStr, 64)
  232. if err != nil {
  233. return 0.0, err
  234. }
  235. discount *= 0.01
  236. return discount, nil
  237. }
  238. func WrapData(data interface{}, err error) []byte {
  239. var resp []byte
  240. if err != nil {
  241. log.Errorf("Error returned to client: %s", err.Error())
  242. resp, _ = json.Marshal(&Response{
  243. Code: http.StatusInternalServerError,
  244. Status: "error",
  245. Message: err.Error(),
  246. Data: data,
  247. })
  248. } else {
  249. resp, _ = json.Marshal(&Response{
  250. Code: http.StatusOK,
  251. Status: "success",
  252. Data: data,
  253. })
  254. }
  255. return resp
  256. }
  257. func WrapDataWithMessage(data interface{}, err error, message string) []byte {
  258. var resp []byte
  259. if err != nil {
  260. log.Errorf("Error returned to client: %s", err.Error())
  261. resp, _ = json.Marshal(&Response{
  262. Code: http.StatusInternalServerError,
  263. Status: "error",
  264. Message: err.Error(),
  265. Data: data,
  266. })
  267. } else {
  268. resp, _ = json.Marshal(&Response{
  269. Code: http.StatusOK,
  270. Status: "success",
  271. Data: data,
  272. Message: message,
  273. })
  274. }
  275. return resp
  276. }
  277. func WrapDataWithWarning(data interface{}, err error, warning string) []byte {
  278. var resp []byte
  279. if err != nil {
  280. log.Errorf("Error returned to client: %s", err.Error())
  281. resp, _ = json.Marshal(&Response{
  282. Code: http.StatusInternalServerError,
  283. Status: "error",
  284. Message: err.Error(),
  285. Warning: warning,
  286. Data: data,
  287. })
  288. } else {
  289. resp, _ = json.Marshal(&Response{
  290. Code: http.StatusOK,
  291. Status: "success",
  292. Data: data,
  293. Warning: warning,
  294. })
  295. }
  296. return resp
  297. }
  298. func WrapDataWithMessageAndWarning(data interface{}, err error, message, warning string) []byte {
  299. var resp []byte
  300. if err != nil {
  301. log.Errorf("Error returned to client: %s", err.Error())
  302. resp, _ = json.Marshal(&Response{
  303. Code: http.StatusInternalServerError,
  304. Status: "error",
  305. Message: err.Error(),
  306. Warning: warning,
  307. Data: data,
  308. })
  309. } else {
  310. resp, _ = json.Marshal(&Response{
  311. Code: http.StatusOK,
  312. Status: "success",
  313. Data: data,
  314. Message: message,
  315. Warning: warning,
  316. })
  317. }
  318. return resp
  319. }
  320. // wrapAsObjectItems wraps a slice of items into an object containing a single items list
  321. // allows our k8s proxy methods to emulate a List() request to k8s API
  322. func wrapAsObjectItems(items interface{}) map[string]interface{} {
  323. return map[string]interface{}{
  324. "items": items,
  325. }
  326. }
  327. // 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.
  328. func (a *Accesses) RefreshPricingData(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. err := a.CloudProvider.DownloadPricingData()
  332. if err != nil {
  333. log.Errorf("Error refreshing pricing data: %s", err.Error())
  334. }
  335. w.Write(WrapData(nil, err))
  336. }
  337. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  338. w.Header().Set("Content-Type", "application/json")
  339. w.Header().Set("Access-Control-Allow-Origin", "*")
  340. window := r.URL.Query().Get("timeWindow")
  341. offset := r.URL.Query().Get("offset")
  342. fields := r.URL.Query().Get("filterFields")
  343. namespace := r.URL.Query().Get("namespace")
  344. if offset != "" {
  345. offset = "offset " + offset
  346. }
  347. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.CloudProvider, window, offset, namespace)
  348. if fields != "" {
  349. filteredData := filterFields(fields, data)
  350. w.Write(WrapData(filteredData, err))
  351. } else {
  352. w.Write(WrapData(data, err))
  353. }
  354. }
  355. func (a *Accesses) ClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  356. w.Header().Set("Content-Type", "application/json")
  357. w.Header().Set("Access-Control-Allow-Origin", "*")
  358. window := r.URL.Query().Get("window")
  359. offset := r.URL.Query().Get("offset")
  360. if window == "" {
  361. w.Write(WrapData(nil, fmt.Errorf("missing window argument")))
  362. return
  363. }
  364. windowDur, err := timeutil.ParseDuration(window)
  365. if err != nil {
  366. w.Write(WrapData(nil, fmt.Errorf("error parsing window (%s): %s", window, err)))
  367. return
  368. }
  369. // offset is not a required parameter
  370. var offsetDur time.Duration
  371. if offset != "" {
  372. offsetDur, err = timeutil.ParseDuration(offset)
  373. if err != nil {
  374. w.Write(WrapData(nil, fmt.Errorf("error parsing offset (%s): %s", offset, err)))
  375. return
  376. }
  377. }
  378. useThanos, _ := strconv.ParseBool(r.URL.Query().Get("multi"))
  379. if useThanos && !thanos.IsEnabled() {
  380. w.Write(WrapData(nil, fmt.Errorf("Multi=true while Thanos is not enabled.")))
  381. return
  382. }
  383. var client prometheus.Client
  384. if useThanos {
  385. client = a.ThanosClient
  386. offsetDur = thanos.OffsetDuration()
  387. } else {
  388. client = a.PrometheusClient
  389. }
  390. data, err := a.ComputeClusterCosts(client, a.CloudProvider, windowDur, offsetDur, true)
  391. w.Write(WrapData(data, err))
  392. }
  393. func (a *Accesses) ClusterCostsOverTime(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  394. w.Header().Set("Content-Type", "application/json")
  395. w.Header().Set("Access-Control-Allow-Origin", "*")
  396. start := r.URL.Query().Get("start")
  397. end := r.URL.Query().Get("end")
  398. window := r.URL.Query().Get("window")
  399. offset := r.URL.Query().Get("offset")
  400. if window == "" {
  401. w.Write(WrapData(nil, fmt.Errorf("missing window argument")))
  402. return
  403. }
  404. windowDur, err := timeutil.ParseDuration(window)
  405. if err != nil {
  406. w.Write(WrapData(nil, fmt.Errorf("error parsing window (%s): %s", window, err)))
  407. return
  408. }
  409. // offset is not a required parameter
  410. var offsetDur time.Duration
  411. if offset != "" {
  412. offsetDur, err = timeutil.ParseDuration(offset)
  413. if err != nil {
  414. w.Write(WrapData(nil, fmt.Errorf("error parsing offset (%s): %s", offset, err)))
  415. return
  416. }
  417. }
  418. data, err := ClusterCostsOverTime(a.PrometheusClient, a.CloudProvider, start, end, windowDur, offsetDur)
  419. w.Write(WrapData(data, err))
  420. }
  421. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  422. w.Header().Set("Content-Type", "application/json")
  423. w.Header().Set("Access-Control-Allow-Origin", "*")
  424. startStr := r.URL.Query().Get("start")
  425. endStr := r.URL.Query().Get("end")
  426. windowStr := r.URL.Query().Get("window")
  427. fields := r.URL.Query().Get("filterFields")
  428. namespace := r.URL.Query().Get("namespace")
  429. cluster := r.URL.Query().Get("cluster")
  430. remote := r.URL.Query().Get("remote")
  431. remoteEnabled := env.IsRemoteEnabled() && remote != "false"
  432. layout := "2006-01-02T15:04:05.000Z"
  433. start, err := time.Parse(layout, startStr)
  434. if err != nil {
  435. w.Write(WrapDataWithMessage(nil, fmt.Errorf("invalid start date: %s", startStr), fmt.Sprintf("invalid start date: %s", startStr)))
  436. return
  437. }
  438. end, err := time.Parse(layout, endStr)
  439. if err != nil {
  440. w.Write(WrapDataWithMessage(nil, fmt.Errorf("invalid end date: %s", endStr), fmt.Sprintf("invalid end date: %s", endStr)))
  441. return
  442. }
  443. window := kubecost.NewWindow(&start, &end)
  444. if window.IsOpen() || !window.HasDuration() || window.IsNegative() {
  445. w.Write(WrapDataWithMessage(nil, fmt.Errorf("invalid date range: %s", window), fmt.Sprintf("invalid date range: %s", window)))
  446. return
  447. }
  448. resolution := time.Hour
  449. if resDur, err := time.ParseDuration(windowStr); err == nil {
  450. resolution = resDur
  451. }
  452. // Use Thanos Client if it exists (enabled) and remote flag set
  453. var pClient prometheus.Client
  454. if remote != "false" && a.ThanosClient != nil {
  455. pClient = a.ThanosClient
  456. } else {
  457. pClient = a.PrometheusClient
  458. }
  459. data, err := a.Model.ComputeCostDataRange(pClient, a.CloudProvider, window, resolution, namespace, cluster, remoteEnabled)
  460. if err != nil {
  461. w.Write(WrapData(nil, err))
  462. }
  463. if fields != "" {
  464. filteredData := filterFields(fields, data)
  465. w.Write(WrapData(filteredData, err))
  466. } else {
  467. w.Write(WrapData(data, err))
  468. }
  469. }
  470. func parseAggregations(customAggregation, aggregator, filterType string) (string, []string, string) {
  471. var key string
  472. var filter string
  473. var val []string
  474. if customAggregation != "" {
  475. key = customAggregation
  476. filter = filterType
  477. val = strings.Split(customAggregation, ",")
  478. } else {
  479. aggregations := strings.Split(aggregator, ",")
  480. for i, agg := range aggregations {
  481. aggregations[i] = "kubernetes_" + agg
  482. }
  483. key = strings.Join(aggregations, ",")
  484. filter = "kubernetes_" + filterType
  485. val = aggregations
  486. }
  487. return key, val, filter
  488. }
  489. func (a *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  490. w.Header().Set("Content-Type", "application/json")
  491. w.Header().Set("Access-Control-Allow-Origin", "*")
  492. data, err := a.CloudProvider.AllNodePricing()
  493. w.Write(WrapData(data, err))
  494. }
  495. func (a *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  496. w.Header().Set("Content-Type", "application/json")
  497. w.Header().Set("Access-Control-Allow-Origin", "*")
  498. data, err := a.CloudProvider.GetConfig()
  499. w.Write(WrapData(data, err))
  500. }
  501. func (a *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  502. w.Header().Set("Content-Type", "application/json")
  503. w.Header().Set("Access-Control-Allow-Origin", "*")
  504. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.SpotInfoUpdateType)
  505. if err != nil {
  506. w.Write(WrapData(data, err))
  507. return
  508. }
  509. w.Write(WrapData(data, err))
  510. err = a.CloudProvider.DownloadPricingData()
  511. if err != nil {
  512. log.Errorf("Error redownloading data on config update: %s", err.Error())
  513. }
  514. return
  515. }
  516. func (a *Accesses) UpdateAthenaInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  517. w.Header().Set("Content-Type", "application/json")
  518. w.Header().Set("Access-Control-Allow-Origin", "*")
  519. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.AthenaInfoUpdateType)
  520. if err != nil {
  521. w.Write(WrapData(data, err))
  522. return
  523. }
  524. w.Write(WrapData(data, err))
  525. return
  526. }
  527. func (a *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  528. w.Header().Set("Content-Type", "application/json")
  529. w.Header().Set("Access-Control-Allow-Origin", "*")
  530. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.BigqueryUpdateType)
  531. if err != nil {
  532. w.Write(WrapData(data, err))
  533. return
  534. }
  535. w.Write(WrapData(data, err))
  536. return
  537. }
  538. func (a *Accesses) UpdateAzureStorageConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  539. w.Header().Set("Content-Type", "application/json")
  540. w.Header().Set("Access-Control-Allow-Origin", "*")
  541. data, err := a.CloudProvider.UpdateConfig(r.Body, cloud.AzureStorageUpdateType)
  542. if err != nil {
  543. w.Write(WrapData(data, err))
  544. return
  545. }
  546. w.Write(WrapData(data, err))
  547. return
  548. }
  549. func (a *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  550. w.Header().Set("Content-Type", "application/json")
  551. w.Header().Set("Access-Control-Allow-Origin", "*")
  552. data, err := a.CloudProvider.UpdateConfig(r.Body, "")
  553. if err != nil {
  554. w.Write(WrapData(data, err))
  555. return
  556. }
  557. w.Write(WrapData(data, err))
  558. return
  559. }
  560. func (a *Accesses) ManagementPlatform(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  561. w.Header().Set("Content-Type", "application/json")
  562. w.Header().Set("Access-Control-Allow-Origin", "*")
  563. data, err := a.CloudProvider.GetManagementPlatform()
  564. if err != nil {
  565. w.Write(WrapData(data, err))
  566. return
  567. }
  568. w.Write(WrapData(data, err))
  569. return
  570. }
  571. func (a *Accesses) ClusterInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  572. w.Header().Set("Content-Type", "application/json")
  573. w.Header().Set("Access-Control-Allow-Origin", "*")
  574. data := a.ClusterInfoProvider.GetClusterInfo()
  575. w.Write(WrapData(data, nil))
  576. }
  577. func (a *Accesses) GetClusterInfoMap(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 := a.ClusterMap.AsMap()
  581. w.Write(WrapData(data, nil))
  582. }
  583. func (a *Accesses) GetServiceAccountStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  584. w.Header().Set("Content-Type", "application/json")
  585. w.Header().Set("Access-Control-Allow-Origin", "*")
  586. w.Write(WrapData(a.CloudProvider.ServiceAccountStatus(), nil))
  587. }
  588. func (a *Accesses) GetPricingSourceStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  589. w.Header().Set("Content-Type", "application/json")
  590. w.Header().Set("Access-Control-Allow-Origin", "*")
  591. w.Write(WrapData(a.CloudProvider.PricingSourceStatus(), nil))
  592. }
  593. func (a *Accesses) GetPricingSourceCounts(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  594. w.Header().Set("Content-Type", "application/json")
  595. w.Header().Set("Access-Control-Allow-Origin", "*")
  596. w.Write(WrapData(a.Model.GetPricingSourceCounts()))
  597. }
  598. func (a *Accesses) GetPrometheusMetadata(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  599. w.Header().Set("Content-Type", "application/json")
  600. w.Header().Set("Access-Control-Allow-Origin", "*")
  601. w.Write(WrapData(prom.Validate(a.PrometheusClient)))
  602. }
  603. func (a *Accesses) PrometheusQuery(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  604. w.Header().Set("Content-Type", "application/json")
  605. w.Header().Set("Access-Control-Allow-Origin", "*")
  606. qp := httputil.NewQueryParams(r.URL.Query())
  607. query := qp.Get("query", "")
  608. if query == "" {
  609. w.Write(WrapData(nil, fmt.Errorf("Query Parameter 'query' is unset'")))
  610. return
  611. }
  612. // Attempt to parse time as either a unix timestamp or as an RFC3339 value
  613. var timeVal time.Time
  614. timeStr := qp.Get("time", "")
  615. if len(timeStr) > 0 {
  616. if t, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
  617. timeVal = time.Unix(t, 0)
  618. } else if t, err := time.Parse(time.RFC3339, timeStr); err == nil {
  619. timeVal = t
  620. }
  621. // If time is given, but not parse-able, return an error
  622. if timeVal.IsZero() {
  623. http.Error(w, fmt.Sprintf("time must be a unix timestamp or RFC3339 value; illegal value given: %s", timeStr), http.StatusBadRequest)
  624. }
  625. }
  626. ctx := prom.NewNamedContext(a.PrometheusClient, prom.FrontendContextName)
  627. body, err := ctx.RawQuery(query, timeVal)
  628. if err != nil {
  629. w.Write(WrapData(nil, fmt.Errorf("Error running query %s. Error: %s", query, err)))
  630. return
  631. }
  632. w.Write(body)
  633. }
  634. func (a *Accesses) PrometheusQueryRange(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  635. w.Header().Set("Content-Type", "application/json")
  636. w.Header().Set("Access-Control-Allow-Origin", "*")
  637. qp := httputil.NewQueryParams(r.URL.Query())
  638. query := qp.Get("query", "")
  639. if query == "" {
  640. fmt.Fprintf(w, "Error parsing query from request parameters.")
  641. return
  642. }
  643. start, end, duration, err := toStartEndStep(qp)
  644. if err != nil {
  645. fmt.Fprintf(w, err.Error())
  646. return
  647. }
  648. ctx := prom.NewNamedContext(a.PrometheusClient, prom.FrontendContextName)
  649. body, err := ctx.RawQueryRange(query, start, end, duration)
  650. if err != nil {
  651. fmt.Fprintf(w, "Error running query %s. Error: %s", query, err)
  652. return
  653. }
  654. w.Write(body)
  655. }
  656. func (a *Accesses) ThanosQuery(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  657. w.Header().Set("Content-Type", "application/json")
  658. w.Header().Set("Access-Control-Allow-Origin", "*")
  659. if !thanos.IsEnabled() {
  660. w.Write(WrapData(nil, fmt.Errorf("ThanosDisabled")))
  661. return
  662. }
  663. qp := httputil.NewQueryParams(r.URL.Query())
  664. query := qp.Get("query", "")
  665. if query == "" {
  666. w.Write(WrapData(nil, fmt.Errorf("Query Parameter 'query' is unset'")))
  667. return
  668. }
  669. // Attempt to parse time as either a unix timestamp or as an RFC3339 value
  670. var timeVal time.Time
  671. timeStr := qp.Get("time", "")
  672. if len(timeStr) > 0 {
  673. if t, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
  674. timeVal = time.Unix(t, 0)
  675. } else if t, err := time.Parse(time.RFC3339, timeStr); err == nil {
  676. timeVal = t
  677. }
  678. // If time is given, but not parse-able, return an error
  679. if timeVal.IsZero() {
  680. http.Error(w, fmt.Sprintf("time must be a unix timestamp or RFC3339 value; illegal value given: %s", timeStr), http.StatusBadRequest)
  681. }
  682. }
  683. ctx := prom.NewNamedContext(a.ThanosClient, prom.FrontendContextName)
  684. body, err := ctx.RawQuery(query, timeVal)
  685. if err != nil {
  686. w.Write(WrapData(nil, fmt.Errorf("Error running query %s. Error: %s", query, err)))
  687. return
  688. }
  689. w.Write(body)
  690. }
  691. func (a *Accesses) ThanosQueryRange(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  692. w.Header().Set("Content-Type", "application/json")
  693. w.Header().Set("Access-Control-Allow-Origin", "*")
  694. if !thanos.IsEnabled() {
  695. w.Write(WrapData(nil, fmt.Errorf("ThanosDisabled")))
  696. return
  697. }
  698. qp := httputil.NewQueryParams(r.URL.Query())
  699. query := qp.Get("query", "")
  700. if query == "" {
  701. fmt.Fprintf(w, "Error parsing query from request parameters.")
  702. return
  703. }
  704. start, end, duration, err := toStartEndStep(qp)
  705. if err != nil {
  706. fmt.Fprintf(w, err.Error())
  707. return
  708. }
  709. ctx := prom.NewNamedContext(a.ThanosClient, prom.FrontendContextName)
  710. body, err := ctx.RawQueryRange(query, start, end, duration)
  711. if err != nil {
  712. fmt.Fprintf(w, "Error running query %s. Error: %s", query, err)
  713. return
  714. }
  715. w.Write(body)
  716. }
  717. // helper for query range proxy requests
  718. func toStartEndStep(qp httputil.QueryParams) (start, end time.Time, step time.Duration, err error) {
  719. var e error
  720. ss := qp.Get("start", "")
  721. es := qp.Get("end", "")
  722. ds := qp.Get("duration", "")
  723. layout := "2006-01-02T15:04:05.000Z"
  724. start, e = time.Parse(layout, ss)
  725. if e != nil {
  726. err = fmt.Errorf("Error parsing time %s. Error: %s", ss, err)
  727. return
  728. }
  729. end, e = time.Parse(layout, es)
  730. if e != nil {
  731. err = fmt.Errorf("Error parsing time %s. Error: %s", es, err)
  732. return
  733. }
  734. step, e = time.ParseDuration(ds)
  735. if e != nil {
  736. err = fmt.Errorf("Error parsing duration %s. Error: %s", ds, err)
  737. return
  738. }
  739. err = nil
  740. return
  741. }
  742. func (a *Accesses) GetPrometheusQueueState(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  743. w.Header().Set("Content-Type", "application/json")
  744. w.Header().Set("Access-Control-Allow-Origin", "*")
  745. promQueueState, err := prom.GetPrometheusQueueState(a.PrometheusClient)
  746. if err != nil {
  747. w.Write(WrapData(nil, err))
  748. return
  749. }
  750. result := map[string]*prom.PrometheusQueueState{
  751. "prometheus": promQueueState,
  752. }
  753. if thanos.IsEnabled() {
  754. thanosQueueState, err := prom.GetPrometheusQueueState(a.ThanosClient)
  755. if err != nil {
  756. log.Warnf("Error getting Thanos queue state: %s", err)
  757. } else {
  758. result["thanos"] = thanosQueueState
  759. }
  760. }
  761. w.Write(WrapData(result, nil))
  762. }
  763. // GetPrometheusMetrics retrieves availability of Prometheus and Thanos metrics
  764. func (a *Accesses) GetPrometheusMetrics(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  765. w.Header().Set("Content-Type", "application/json")
  766. w.Header().Set("Access-Control-Allow-Origin", "*")
  767. promMetrics := prom.GetPrometheusMetrics(a.PrometheusClient, "")
  768. result := map[string][]*prom.PrometheusDiagnostic{
  769. "prometheus": promMetrics,
  770. }
  771. if thanos.IsEnabled() {
  772. thanosMetrics := prom.GetPrometheusMetrics(a.ThanosClient, thanos.QueryOffset())
  773. result["thanos"] = thanosMetrics
  774. }
  775. w.Write(WrapData(result, nil))
  776. }
  777. func (a *Accesses) GetAllPersistentVolumes(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  778. w.Header().Set("Content-Type", "application/json")
  779. w.Header().Set("Access-Control-Allow-Origin", "*")
  780. pvList := a.ClusterCache.GetAllPersistentVolumes()
  781. body, err := json.Marshal(wrapAsObjectItems(pvList))
  782. if err != nil {
  783. fmt.Fprintf(w, "Error decoding persistent volumes: "+err.Error())
  784. } else {
  785. w.Write(body)
  786. }
  787. }
  788. func (a *Accesses) GetAllDeployments(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  789. w.Header().Set("Content-Type", "application/json")
  790. w.Header().Set("Access-Control-Allow-Origin", "*")
  791. qp := httputil.NewQueryParams(r.URL.Query())
  792. namespace := qp.Get("namespace", "")
  793. deploymentsList := a.ClusterCache.GetAllDeployments()
  794. // filter for provided namespace
  795. var deployments []*appsv1.Deployment
  796. if namespace == "" {
  797. deployments = deploymentsList
  798. } else {
  799. deployments = []*appsv1.Deployment{}
  800. for _, d := range deploymentsList {
  801. if d.Namespace == namespace {
  802. deployments = append(deployments, d)
  803. }
  804. }
  805. }
  806. body, err := json.Marshal(wrapAsObjectItems(deployments))
  807. if err != nil {
  808. fmt.Fprintf(w, "Error decoding deployment: "+err.Error())
  809. } else {
  810. w.Write(body)
  811. }
  812. }
  813. func (a *Accesses) GetAllStorageClasses(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  814. w.Header().Set("Content-Type", "application/json")
  815. w.Header().Set("Access-Control-Allow-Origin", "*")
  816. scList := a.ClusterCache.GetAllStorageClasses()
  817. body, err := json.Marshal(wrapAsObjectItems(scList))
  818. if err != nil {
  819. fmt.Fprintf(w, "Error decoding storageclasses: "+err.Error())
  820. } else {
  821. w.Write(body)
  822. }
  823. }
  824. func (a *Accesses) GetAllStatefulSets(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  825. w.Header().Set("Content-Type", "application/json")
  826. w.Header().Set("Access-Control-Allow-Origin", "*")
  827. qp := httputil.NewQueryParams(r.URL.Query())
  828. namespace := qp.Get("namespace", "")
  829. statefulSetsList := a.ClusterCache.GetAllStatefulSets()
  830. // filter for provided namespace
  831. var statefulSets []*appsv1.StatefulSet
  832. if namespace == "" {
  833. statefulSets = statefulSetsList
  834. } else {
  835. statefulSets = []*appsv1.StatefulSet{}
  836. for _, ss := range statefulSetsList {
  837. if ss.Namespace == namespace {
  838. statefulSets = append(statefulSets, ss)
  839. }
  840. }
  841. }
  842. body, err := json.Marshal(wrapAsObjectItems(statefulSets))
  843. if err != nil {
  844. fmt.Fprintf(w, "Error decoding deployment: "+err.Error())
  845. } else {
  846. w.Write(body)
  847. }
  848. }
  849. func (a *Accesses) GetAllNodes(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  850. w.Header().Set("Content-Type", "application/json")
  851. w.Header().Set("Access-Control-Allow-Origin", "*")
  852. nodeList := a.ClusterCache.GetAllNodes()
  853. body, err := json.Marshal(wrapAsObjectItems(nodeList))
  854. if err != nil {
  855. fmt.Fprintf(w, "Error decoding nodes: "+err.Error())
  856. } else {
  857. w.Write(body)
  858. }
  859. }
  860. func (a *Accesses) GetAllPods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  861. w.Header().Set("Content-Type", "application/json")
  862. w.Header().Set("Access-Control-Allow-Origin", "*")
  863. podlist := a.ClusterCache.GetAllPods()
  864. body, err := json.Marshal(wrapAsObjectItems(podlist))
  865. if err != nil {
  866. fmt.Fprintf(w, "Error decoding pods: "+err.Error())
  867. } else {
  868. w.Write(body)
  869. }
  870. }
  871. func (a *Accesses) GetAllNamespaces(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  872. w.Header().Set("Content-Type", "application/json")
  873. w.Header().Set("Access-Control-Allow-Origin", "*")
  874. namespaces := a.ClusterCache.GetAllNamespaces()
  875. body, err := json.Marshal(wrapAsObjectItems(namespaces))
  876. if err != nil {
  877. fmt.Fprintf(w, "Error decoding deployment: "+err.Error())
  878. } else {
  879. w.Write(body)
  880. }
  881. }
  882. func (a *Accesses) GetAllDaemonSets(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  883. w.Header().Set("Content-Type", "application/json")
  884. w.Header().Set("Access-Control-Allow-Origin", "*")
  885. daemonSets := a.ClusterCache.GetAllDaemonSets()
  886. body, err := json.Marshal(wrapAsObjectItems(daemonSets))
  887. if err != nil {
  888. fmt.Fprintf(w, "Error decoding daemon set: "+err.Error())
  889. } else {
  890. w.Write(body)
  891. }
  892. }
  893. func (a *Accesses) GetPod(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  894. w.Header().Set("Content-Type", "application/json")
  895. w.Header().Set("Access-Control-Allow-Origin", "*")
  896. podName := ps.ByName("name")
  897. podNamespace := ps.ByName("namespace")
  898. // TODO: ClusterCache API could probably afford to have some better filtering
  899. allPods := a.ClusterCache.GetAllPods()
  900. for _, pod := range allPods {
  901. for _, container := range pod.Spec.Containers {
  902. container.Env = make([]v1.EnvVar, 0)
  903. }
  904. if pod.Namespace == podNamespace && pod.Name == podName {
  905. body, err := json.Marshal(pod)
  906. if err != nil {
  907. fmt.Fprintf(w, "Error decoding pod: "+err.Error())
  908. } else {
  909. w.Write(body)
  910. }
  911. return
  912. }
  913. }
  914. fmt.Fprintf(w, "Pod not found\n")
  915. }
  916. func (a *Accesses) PrometheusRecordingRules(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  917. w.Header().Set("Content-Type", "application/json")
  918. w.Header().Set("Access-Control-Allow-Origin", "*")
  919. u := a.PrometheusClient.URL(epRules, nil)
  920. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  921. if err != nil {
  922. fmt.Fprintf(w, "Error creating Prometheus rule request: "+err.Error())
  923. }
  924. _, body, err := a.PrometheusClient.Do(r.Context(), req)
  925. if err != nil {
  926. fmt.Fprintf(w, "Error making Prometheus rule request: "+err.Error())
  927. } else {
  928. w.Write(body)
  929. }
  930. }
  931. func (a *Accesses) PrometheusConfig(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  932. w.Header().Set("Content-Type", "application/json")
  933. w.Header().Set("Access-Control-Allow-Origin", "*")
  934. pConfig := map[string]string{
  935. "address": env.GetPrometheusServerEndpoint(),
  936. }
  937. body, err := json.Marshal(pConfig)
  938. if err != nil {
  939. fmt.Fprintf(w, "Error marshalling prometheus config")
  940. } else {
  941. w.Write(body)
  942. }
  943. }
  944. func (a *Accesses) PrometheusTargets(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  945. w.Header().Set("Content-Type", "application/json")
  946. w.Header().Set("Access-Control-Allow-Origin", "*")
  947. u := a.PrometheusClient.URL(epTargets, nil)
  948. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  949. if err != nil {
  950. fmt.Fprintf(w, "Error creating Prometheus rule request: "+err.Error())
  951. }
  952. _, body, err := a.PrometheusClient.Do(r.Context(), req)
  953. if err != nil {
  954. fmt.Fprintf(w, "Error making Prometheus rule request: "+err.Error())
  955. } else {
  956. w.Write(body)
  957. }
  958. }
  959. func (a *Accesses) GetOrphanedPods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  960. w.Header().Set("Content-Type", "application/json")
  961. w.Header().Set("Access-Control-Allow-Origin", "*")
  962. podlist := a.ClusterCache.GetAllPods()
  963. var lonePods []*v1.Pod
  964. for _, pod := range podlist {
  965. if len(pod.OwnerReferences) == 0 {
  966. lonePods = append(lonePods, pod)
  967. }
  968. }
  969. body, err := json.Marshal(lonePods)
  970. if err != nil {
  971. fmt.Fprintf(w, "Error decoding pod: "+err.Error())
  972. } else {
  973. w.Write(body)
  974. }
  975. }
  976. func (a *Accesses) GetInstallNamespace(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  977. w.Header().Set("Content-Type", "application/json")
  978. w.Header().Set("Access-Control-Allow-Origin", "*")
  979. ns := env.GetKubecostNamespace()
  980. w.Write([]byte(ns))
  981. }
  982. type InstallInfo struct {
  983. Containers []ContainerInfo `json:"containers"`
  984. ClusterInfo map[string]string `json:"clusterInfo"`
  985. Version string `json:"version"`
  986. }
  987. type ContainerInfo struct {
  988. ContainerName string `json:"containerName"`
  989. Image string `json:"image"`
  990. ImageID string `json:"imageID"`
  991. StartTime string `json:"startTime"`
  992. Restarts int32 `json:"restarts"`
  993. }
  994. func (a *Accesses) GetInstallInfo(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  995. w.Header().Set("Content-Type", "application/json")
  996. w.Header().Set("Access-Control-Allow-Origin", "*")
  997. pods, err := a.KubeClientSet.CoreV1().Pods(env.GetKubecostNamespace()).List(context.Background(), metav1.ListOptions{
  998. LabelSelector: "app=cost-analyzer",
  999. FieldSelector: "status.phase=Running",
  1000. Limit: 1,
  1001. })
  1002. if err != nil {
  1003. writeErrorResponse(w, 500, fmt.Sprintf("Unable to list pods: %s", err.Error()))
  1004. return
  1005. }
  1006. info := InstallInfo{
  1007. ClusterInfo: make(map[string]string),
  1008. Version: version.FriendlyVersion(),
  1009. }
  1010. // If we have zero pods either something is weird with the install since the app selector is not exposed in the helm
  1011. // chart or more likely we are running locally - in either case Images field will return as null
  1012. if len(pods.Items) > 0 {
  1013. for _, pod := range pods.Items {
  1014. for _, container := range pod.Status.ContainerStatuses {
  1015. c := ContainerInfo{
  1016. ContainerName: container.Name,
  1017. Image: container.Image,
  1018. ImageID: container.ImageID,
  1019. StartTime: pod.Status.StartTime.String(),
  1020. Restarts: container.RestartCount,
  1021. }
  1022. info.Containers = append(info.Containers, c)
  1023. }
  1024. }
  1025. }
  1026. nodes := a.ClusterCache.GetAllNodes()
  1027. cachePods := a.ClusterCache.GetAllPods()
  1028. info.ClusterInfo["nodeCount"] = strconv.Itoa(len(nodes))
  1029. info.ClusterInfo["podCount"] = strconv.Itoa(len(cachePods))
  1030. body, err := json.Marshal(info)
  1031. if err != nil {
  1032. writeErrorResponse(w, 500, fmt.Sprintf("Error decoding pod: %s", err.Error()))
  1033. return
  1034. }
  1035. w.Write(body)
  1036. }
  1037. // logsFor pulls the logs for a specific pod, namespace, and container
  1038. func logsFor(c kubernetes.Interface, namespace string, pod string, container string, dur time.Duration, ctx context.Context) (string, error) {
  1039. since := time.Now().UTC().Add(-dur)
  1040. logOpts := v1.PodLogOptions{
  1041. SinceTime: &metav1.Time{Time: since},
  1042. }
  1043. if container != "" {
  1044. logOpts.Container = container
  1045. }
  1046. req := c.CoreV1().Pods(namespace).GetLogs(pod, &logOpts)
  1047. reader, err := req.Stream(ctx)
  1048. if err != nil {
  1049. return "", err
  1050. }
  1051. podLogs, err := io.ReadAll(reader)
  1052. if err != nil {
  1053. return "", err
  1054. }
  1055. // If color is already disabled then we don't need to process the logs
  1056. // to drop ANSI colors
  1057. if !viper.GetBool("disable-log-color") {
  1058. podLogs = ANSIRegex.ReplaceAll(podLogs, []byte{})
  1059. }
  1060. return string(podLogs), nil
  1061. }
  1062. func (a *Accesses) GetPodLogs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  1063. w.Header().Set("Content-Type", "application/json")
  1064. w.Header().Set("Access-Control-Allow-Origin", "*")
  1065. qp := httputil.NewQueryParams(r.URL.Query())
  1066. ns := qp.Get("namespace", env.GetKubecostNamespace())
  1067. pod := qp.Get("pod", "")
  1068. selector := qp.Get("selector", "")
  1069. container := qp.Get("container", "")
  1070. since := qp.Get("since", "24h")
  1071. sinceDuration, err := time.ParseDuration(since)
  1072. if err != nil {
  1073. fmt.Fprintf(w, "Invalid Duration String: "+err.Error())
  1074. return
  1075. }
  1076. var logResult string
  1077. appendLog := func(ns string, pod string, container string, l string) {
  1078. if l == "" {
  1079. return
  1080. }
  1081. logResult += fmt.Sprintf("%s\n| %s:%s:%s\n%s\n%s\n\n", LogSeparator, ns, pod, container, LogSeparator, l)
  1082. }
  1083. if pod != "" {
  1084. pd, err := a.KubeClientSet.CoreV1().Pods(ns).Get(r.Context(), pod, metav1.GetOptions{})
  1085. if err != nil {
  1086. fmt.Fprintf(w, "Error Finding Pod: "+err.Error())
  1087. return
  1088. }
  1089. if container != "" {
  1090. var foundContainer bool
  1091. for _, cont := range pd.Spec.Containers {
  1092. if strings.EqualFold(cont.Name, container) {
  1093. foundContainer = true
  1094. break
  1095. }
  1096. }
  1097. if !foundContainer {
  1098. fmt.Fprintf(w, "Could not find container: "+container)
  1099. return
  1100. }
  1101. }
  1102. logs, err := logsFor(a.KubeClientSet, ns, pod, container, sinceDuration, r.Context())
  1103. if err != nil {
  1104. fmt.Fprintf(w, "Error Getting Logs: "+err.Error())
  1105. return
  1106. }
  1107. appendLog(ns, pod, container, logs)
  1108. w.Write([]byte(logResult))
  1109. return
  1110. }
  1111. if selector != "" {
  1112. pods, err := a.KubeClientSet.CoreV1().Pods(ns).List(r.Context(), metav1.ListOptions{LabelSelector: selector})
  1113. if err != nil {
  1114. fmt.Fprintf(w, "Error Finding Pod: "+err.Error())
  1115. return
  1116. }
  1117. for _, pd := range pods.Items {
  1118. for _, cont := range pd.Spec.Containers {
  1119. logs, err := logsFor(a.KubeClientSet, ns, pd.Name, cont.Name, sinceDuration, r.Context())
  1120. if err != nil {
  1121. continue
  1122. }
  1123. appendLog(ns, pd.Name, cont.Name, logs)
  1124. }
  1125. }
  1126. }
  1127. w.Write([]byte(logResult))
  1128. }
  1129. func (a *Accesses) AddServiceKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  1130. w.Header().Set("Content-Type", "application/json")
  1131. w.Header().Set("Access-Control-Allow-Origin", "*")
  1132. r.ParseForm()
  1133. key := r.PostForm.Get("key")
  1134. k := []byte(key)
  1135. err := os.WriteFile(path.Join(env.GetConfigPathWithDefault("/var/configs/"), "key.json"), k, 0644)
  1136. if err != nil {
  1137. fmt.Fprintf(w, "Error writing service key: "+err.Error())
  1138. }
  1139. w.WriteHeader(http.StatusOK)
  1140. }
  1141. func (a *Accesses) GetHelmValues(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  1142. w.Header().Set("Content-Type", "application/json")
  1143. w.Header().Set("Access-Control-Allow-Origin", "*")
  1144. encodedValues := env.Get("HELM_VALUES", "")
  1145. if encodedValues == "" {
  1146. fmt.Fprintf(w, "Values reporting disabled")
  1147. return
  1148. }
  1149. result, err := base64.StdEncoding.DecodeString(encodedValues)
  1150. if err != nil {
  1151. fmt.Fprintf(w, "Failed to decode encoded values: %s", err)
  1152. return
  1153. }
  1154. w.Write(result)
  1155. }
  1156. func (a *Accesses) Status(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  1157. w.Header().Set("Content-Type", "application/json")
  1158. w.Header().Set("Access-Control-Allow-Origin", "*")
  1159. promServer := env.GetPrometheusServerEndpoint()
  1160. api := prometheusAPI.NewAPI(a.PrometheusClient)
  1161. result, err := api.Config(r.Context())
  1162. if err != nil {
  1163. fmt.Fprintf(w, "Using Prometheus at "+promServer+". Error: "+err.Error())
  1164. } else {
  1165. fmt.Fprintf(w, "Using Prometheus at "+promServer+". PrometheusConfig: "+result.YAML)
  1166. }
  1167. }
  1168. type LogLevelRequestResponse struct {
  1169. Level string `json:"level"`
  1170. }
  1171. func (a *Accesses) GetLogLevel(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  1172. w.Header().Set("Content-Type", "application/json")
  1173. w.Header().Set("Access-Control-Allow-Origin", "*")
  1174. level := log.GetLogLevel()
  1175. llrr := LogLevelRequestResponse{
  1176. Level: level,
  1177. }
  1178. body, err := json.Marshal(llrr)
  1179. if err != nil {
  1180. http.Error(w, fmt.Sprintf("unable to retrive log level"), http.StatusInternalServerError)
  1181. return
  1182. }
  1183. _, err = w.Write(body)
  1184. if err != nil {
  1185. http.Error(w, fmt.Sprintf("unable to write response: %s", body), http.StatusInternalServerError)
  1186. return
  1187. }
  1188. }
  1189. func (a *Accesses) SetLogLevel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  1190. params := LogLevelRequestResponse{}
  1191. err := json.NewDecoder(r.Body).Decode(&params)
  1192. if err != nil {
  1193. http.Error(w, fmt.Sprintf("unable to decode request body, error: %s", err), http.StatusBadRequest)
  1194. return
  1195. }
  1196. err = log.SetLogLevel(params.Level)
  1197. if err != nil {
  1198. http.Error(w, fmt.Sprintf("level must be a valid log level according to zerolog; level given: %s, error: %s", params.Level, err), http.StatusBadRequest)
  1199. return
  1200. }
  1201. w.WriteHeader(http.StatusOK)
  1202. }
  1203. // captures the panic event in sentry
  1204. func capturePanicEvent(err string, stack string) {
  1205. msg := fmt.Sprintf("Panic: %s\nStackTrace: %s\n", err, stack)
  1206. log.Infof(msg)
  1207. sentry.CurrentHub().CaptureEvent(&sentry.Event{
  1208. Level: sentry.LevelError,
  1209. Message: msg,
  1210. })
  1211. sentry.Flush(5 * time.Second)
  1212. }
  1213. // handle any panics reported by the errors package
  1214. func handlePanic(p errors.Panic) bool {
  1215. err := p.Error
  1216. if err != nil {
  1217. if err, ok := err.(error); ok {
  1218. capturePanicEvent(err.Error(), p.Stack)
  1219. }
  1220. if err, ok := err.(string); ok {
  1221. capturePanicEvent(err, p.Stack)
  1222. }
  1223. }
  1224. // Return true to recover iff the type is http, otherwise allow kubernetes
  1225. // to recover.
  1226. return p.Type == errors.PanicTypeHTTP
  1227. }
  1228. func Initialize(additionalConfigWatchers ...*watcher.ConfigMapWatcher) *Accesses {
  1229. configWatchers := watcher.NewConfigMapWatchers(additionalConfigWatchers...)
  1230. var err error
  1231. if errorReportingEnabled {
  1232. err = sentry.Init(sentry.ClientOptions{Release: env.GetAppVersion()})
  1233. if err != nil {
  1234. log.Infof("Failed to initialize sentry for error reporting")
  1235. } else {
  1236. err = errors.SetPanicHandler(handlePanic)
  1237. if err != nil {
  1238. log.Infof("Failed to set panic handler: %s", err)
  1239. }
  1240. }
  1241. }
  1242. address := env.GetPrometheusServerEndpoint()
  1243. if address == "" {
  1244. log.Fatalf("No address for prometheus set in $%s. Aborting.", env.PrometheusServerEndpointEnvVar)
  1245. }
  1246. queryConcurrency := env.GetMaxQueryConcurrency()
  1247. log.Infof("Prometheus/Thanos Client Max Concurrency set to %d", queryConcurrency)
  1248. timeout := 120 * time.Second
  1249. keepAlive := 120 * time.Second
  1250. tlsHandshakeTimeout := 10 * time.Second
  1251. scrapeInterval := time.Minute
  1252. var rateLimitRetryOpts *prom.RateLimitRetryOpts = nil
  1253. if env.IsPrometheusRetryOnRateLimitResponse() {
  1254. rateLimitRetryOpts = &prom.RateLimitRetryOpts{
  1255. MaxRetries: env.GetPrometheusRetryOnRateLimitMaxRetries(),
  1256. DefaultRetryWait: env.GetPrometheusRetryOnRateLimitDefaultWait(),
  1257. }
  1258. }
  1259. promCli, err := prom.NewPrometheusClient(address, &prom.PrometheusClientConfig{
  1260. Timeout: timeout,
  1261. KeepAlive: keepAlive,
  1262. TLSHandshakeTimeout: tlsHandshakeTimeout,
  1263. TLSInsecureSkipVerify: env.GetInsecureSkipVerify(),
  1264. RateLimitRetryOpts: rateLimitRetryOpts,
  1265. Auth: &prom.ClientAuth{
  1266. Username: env.GetDBBasicAuthUsername(),
  1267. Password: env.GetDBBasicAuthUserPassword(),
  1268. BearerToken: env.GetDBBearerToken(),
  1269. },
  1270. QueryConcurrency: queryConcurrency,
  1271. QueryLogFile: "",
  1272. })
  1273. if err != nil {
  1274. log.Fatalf("Failed to create prometheus client, Error: %v", err)
  1275. }
  1276. m, err := prom.Validate(promCli)
  1277. if err != nil || !m.Running {
  1278. if err != nil {
  1279. log.Errorf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prom.PrometheusTroubleshootingURL)
  1280. } else if !m.Running {
  1281. log.Errorf("Prometheus at %s is not running. Troubleshooting help available at: %s", address, prom.PrometheusTroubleshootingURL)
  1282. }
  1283. } else {
  1284. log.Infof("Success: retrieved the 'up' query against prometheus at: " + address)
  1285. }
  1286. api := prometheusAPI.NewAPI(promCli)
  1287. _, err = api.Config(context.Background())
  1288. if err != nil {
  1289. log.Infof("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s. Ignore if using cortex/thanos here.", address, err.Error(), prom.PrometheusTroubleshootingURL)
  1290. } else {
  1291. log.Infof("Retrieved a prometheus config file from: %s", address)
  1292. }
  1293. // Lookup scrape interval for kubecost job, update if found
  1294. si, err := prom.ScrapeIntervalFor(promCli, env.GetKubecostJobName())
  1295. if err == nil {
  1296. scrapeInterval = si
  1297. }
  1298. log.Infof("Using scrape interval of %f", scrapeInterval.Seconds())
  1299. // Kubernetes API setup
  1300. kubeClientset, err := kubeconfig.LoadKubeClient("")
  1301. if err != nil {
  1302. log.Fatalf("Failed to build Kubernetes client: %s", err.Error())
  1303. }
  1304. // Create ConfigFileManager for synchronization of shared configuration
  1305. confManager := config.NewConfigFileManager(&config.ConfigFileManagerOpts{
  1306. BucketStoreConfig: env.GetKubecostConfigBucket(),
  1307. LocalConfigPath: "/",
  1308. })
  1309. configPrefix := env.GetConfigPathWithDefault("/var/configs/")
  1310. // Create Kubernetes Cluster Cache + Watchers
  1311. var k8sCache clustercache.ClusterCache
  1312. if env.IsClusterCacheFileEnabled() {
  1313. importLocation := confManager.ConfigFileAt(path.Join(configPrefix, "cluster-cache.json"))
  1314. k8sCache = clustercache.NewClusterImporter(importLocation)
  1315. } else {
  1316. k8sCache = clustercache.NewKubernetesClusterCache(kubeClientset)
  1317. }
  1318. k8sCache.Run()
  1319. cloudProviderKey := env.GetCloudProviderAPIKey()
  1320. cloudProvider, err := cloud.NewProvider(k8sCache, cloudProviderKey, confManager)
  1321. if err != nil {
  1322. panic(err.Error())
  1323. }
  1324. // Append the pricing config watcher
  1325. configWatchers.AddWatcher(cloud.ConfigWatcherFor(cloudProvider))
  1326. configWatchers.AddWatcher(metrics.GetMetricsConfigWatcher())
  1327. watchConfigFunc := configWatchers.ToWatchFunc()
  1328. watchedConfigs := configWatchers.GetWatchedConfigs()
  1329. kubecostNamespace := env.GetKubecostNamespace()
  1330. // We need an initial invocation because the init of the cache has happened before we had access to the provider.
  1331. for _, cw := range watchedConfigs {
  1332. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get(context.Background(), cw, metav1.GetOptions{})
  1333. if err != nil {
  1334. log.Infof("No %s configmap found at install time, using existing configs: %s", cw, err.Error())
  1335. } else {
  1336. log.Infof("Found configmap %s, watching...", configs.Name)
  1337. watchConfigFunc(configs)
  1338. }
  1339. }
  1340. k8sCache.SetConfigMapUpdateFunc(watchConfigFunc)
  1341. remoteEnabled := env.IsRemoteEnabled()
  1342. if remoteEnabled {
  1343. info, err := cloudProvider.ClusterInfo()
  1344. log.Infof("Saving cluster with id:'%s', and name:'%s' to durable storage", info["id"], info["name"])
  1345. if err != nil {
  1346. log.Infof("Error saving cluster id %s", err.Error())
  1347. }
  1348. _, _, err = cloud.GetOrCreateClusterMeta(info["id"], info["name"])
  1349. if err != nil {
  1350. log.Infof("Unable to set cluster id '%s' for cluster '%s', %s", info["id"], info["name"], err.Error())
  1351. }
  1352. }
  1353. // Thanos Client
  1354. var thanosClient prometheus.Client
  1355. if thanos.IsEnabled() {
  1356. thanosAddress := thanos.QueryURL()
  1357. if thanosAddress != "" {
  1358. thanosCli, _ := thanos.NewThanosClient(thanosAddress, &prom.PrometheusClientConfig{
  1359. Timeout: timeout,
  1360. KeepAlive: keepAlive,
  1361. TLSHandshakeTimeout: tlsHandshakeTimeout,
  1362. TLSInsecureSkipVerify: env.GetInsecureSkipVerify(),
  1363. RateLimitRetryOpts: rateLimitRetryOpts,
  1364. Auth: &prom.ClientAuth{
  1365. Username: env.GetMultiClusterBasicAuthUsername(),
  1366. Password: env.GetMultiClusterBasicAuthPassword(),
  1367. BearerToken: env.GetMultiClusterBearerToken(),
  1368. },
  1369. QueryConcurrency: queryConcurrency,
  1370. QueryLogFile: env.GetQueryLoggingFile(),
  1371. })
  1372. _, err = prom.Validate(thanosCli)
  1373. if err != nil {
  1374. log.Warnf("Failed to query Thanos at %s. Error: %s.", thanosAddress, err.Error())
  1375. thanosClient = thanosCli
  1376. } else {
  1377. log.Infof("Success: retrieved the 'up' query against Thanos at: " + thanosAddress)
  1378. thanosClient = thanosCli
  1379. }
  1380. } else {
  1381. log.Infof("Error resolving environment variable: $%s", env.ThanosQueryUrlEnvVar)
  1382. }
  1383. }
  1384. // ClusterInfo Provider to provide the cluster map with local and remote cluster data
  1385. var clusterInfoProvider clusters.ClusterInfoProvider
  1386. if env.IsClusterInfoFileEnabled() {
  1387. clusterInfoFile := confManager.ConfigFileAt(path.Join(configPrefix, "cluster-info.json"))
  1388. clusterInfoProvider = NewConfiguredClusterInfoProvider(clusterInfoFile)
  1389. } else {
  1390. clusterInfoProvider = NewLocalClusterInfoProvider(kubeClientset, cloudProvider)
  1391. }
  1392. // Initialize ClusterMap for maintaining ClusterInfo by ClusterID
  1393. var clusterMap clusters.ClusterMap
  1394. if thanosClient != nil {
  1395. clusterMap = clusters.NewClusterMap(thanosClient, clusterInfoProvider, 10*time.Minute)
  1396. } else {
  1397. clusterMap = clusters.NewClusterMap(promCli, clusterInfoProvider, 5*time.Minute)
  1398. }
  1399. // cache responses from model and aggregation for a default of 10 minutes;
  1400. // clear expired responses every 20 minutes
  1401. aggregateCache := cache.New(time.Minute*10, time.Minute*20)
  1402. costDataCache := cache.New(time.Minute*10, time.Minute*20)
  1403. clusterCostsCache := cache.New(cache.NoExpiration, cache.NoExpiration)
  1404. outOfClusterCache := cache.New(time.Minute*5, time.Minute*10)
  1405. settingsCache := cache.New(cache.NoExpiration, cache.NoExpiration)
  1406. // query durations that should be cached longer should be registered here
  1407. // use relatively prime numbers to minimize likelihood of synchronized
  1408. // attempts at cache warming
  1409. day := 24 * time.Hour
  1410. cacheExpiration := map[time.Duration]time.Duration{
  1411. day: maxCacheMinutes1d * time.Minute,
  1412. 2 * day: maxCacheMinutes2d * time.Minute,
  1413. 7 * day: maxCacheMinutes7d * time.Minute,
  1414. 30 * day: maxCacheMinutes30d * time.Minute,
  1415. }
  1416. var pc prometheus.Client
  1417. if thanosClient != nil {
  1418. pc = thanosClient
  1419. } else {
  1420. pc = promCli
  1421. }
  1422. costModel := NewCostModel(pc, cloudProvider, k8sCache, clusterMap, scrapeInterval)
  1423. metricsEmitter := NewCostModelMetricsEmitter(promCli, k8sCache, cloudProvider, clusterInfoProvider, costModel)
  1424. a := &Accesses{
  1425. Router: httprouter.New(),
  1426. PrometheusClient: promCli,
  1427. ThanosClient: thanosClient,
  1428. KubeClientSet: kubeClientset,
  1429. ClusterCache: k8sCache,
  1430. ClusterMap: clusterMap,
  1431. CloudProvider: cloudProvider,
  1432. ConfigFileManager: confManager,
  1433. ClusterInfoProvider: clusterInfoProvider,
  1434. Model: costModel,
  1435. MetricsEmitter: metricsEmitter,
  1436. AggregateCache: aggregateCache,
  1437. CostDataCache: costDataCache,
  1438. ClusterCostsCache: clusterCostsCache,
  1439. OutOfClusterCache: outOfClusterCache,
  1440. SettingsCache: settingsCache,
  1441. CacheExpiration: cacheExpiration,
  1442. httpServices: services.NewCostModelServices(),
  1443. }
  1444. // Use the Accesses instance, itself, as the CostModelAggregator. This is
  1445. // confusing and unconventional, but necessary so that we can swap it
  1446. // out for the ETL-adapted version elsewhere.
  1447. // TODO clean this up once ETL is open-sourced.
  1448. a.AggAPI = a
  1449. // Initialize mechanism for subscribing to settings changes
  1450. a.InitializeSettingsPubSub()
  1451. err = a.CloudProvider.DownloadPricingData()
  1452. if err != nil {
  1453. log.Infof("Failed to download pricing data: " + err.Error())
  1454. }
  1455. // Warm the aggregate cache unless explicitly set to false
  1456. if env.IsCacheWarmingEnabled() {
  1457. log.Infof("Init: AggregateCostModel cache warming enabled")
  1458. a.warmAggregateCostModelCache()
  1459. } else {
  1460. log.Infof("Init: AggregateCostModel cache warming disabled")
  1461. }
  1462. if !env.IsKubecostMetricsPodEnabled() {
  1463. a.MetricsEmitter.Start()
  1464. }
  1465. a.Router.GET("/costDataModel", a.CostDataModel)
  1466. a.Router.GET("/costDataModelRange", a.CostDataModelRange)
  1467. a.Router.GET("/aggregatedCostModel", a.AggregateCostModelHandler)
  1468. a.Router.GET("/allocation/compute", a.ComputeAllocationHandler)
  1469. a.Router.GET("/allocation/compute/summary", a.ComputeAllocationHandlerSummary)
  1470. a.Router.GET("/allNodePricing", a.GetAllNodePricing)
  1471. a.Router.POST("/refreshPricing", a.RefreshPricingData)
  1472. a.Router.GET("/clusterCostsOverTime", a.ClusterCostsOverTime)
  1473. a.Router.GET("/clusterCosts", a.ClusterCosts)
  1474. a.Router.GET("/clusterCostsFromCache", a.ClusterCostsFromCacheHandler)
  1475. a.Router.GET("/validatePrometheus", a.GetPrometheusMetadata)
  1476. a.Router.GET("/managementPlatform", a.ManagementPlatform)
  1477. a.Router.GET("/clusterInfo", a.ClusterInfo)
  1478. a.Router.GET("/clusterInfoMap", a.GetClusterInfoMap)
  1479. a.Router.GET("/serviceAccountStatus", a.GetServiceAccountStatus)
  1480. a.Router.GET("/pricingSourceStatus", a.GetPricingSourceStatus)
  1481. a.Router.GET("/pricingSourceCounts", a.GetPricingSourceCounts)
  1482. // endpoints migrated from server
  1483. a.Router.GET("/allPersistentVolumes", a.GetAllPersistentVolumes)
  1484. a.Router.GET("/allDeployments", a.GetAllDeployments)
  1485. a.Router.GET("/allStorageClasses", a.GetAllStorageClasses)
  1486. a.Router.GET("/allStatefulSets", a.GetAllStatefulSets)
  1487. a.Router.GET("/allNodes", a.GetAllNodes)
  1488. a.Router.GET("/allPods", a.GetAllPods)
  1489. a.Router.GET("/allNamespaces", a.GetAllNamespaces)
  1490. a.Router.GET("/allDaemonSets", a.GetAllDaemonSets)
  1491. a.Router.GET("/pod/:namespace/:name", a.GetPod)
  1492. a.Router.GET("/prometheusRecordingRules", a.PrometheusRecordingRules)
  1493. a.Router.GET("/prometheusConfig", a.PrometheusConfig)
  1494. a.Router.GET("/prometheusTargets", a.PrometheusTargets)
  1495. a.Router.GET("/orphanedPods", a.GetOrphanedPods)
  1496. a.Router.GET("/installNamespace", a.GetInstallNamespace)
  1497. a.Router.GET("/installInfo", a.GetInstallInfo)
  1498. a.Router.GET("/podLogs", a.GetPodLogs)
  1499. a.Router.POST("/serviceKey", a.AddServiceKey)
  1500. a.Router.GET("/helmValues", a.GetHelmValues)
  1501. a.Router.GET("/status", a.Status)
  1502. // prom query proxies
  1503. a.Router.GET("/prometheusQuery", a.PrometheusQuery)
  1504. a.Router.GET("/prometheusQueryRange", a.PrometheusQueryRange)
  1505. a.Router.GET("/thanosQuery", a.ThanosQuery)
  1506. a.Router.GET("/thanosQueryRange", a.ThanosQueryRange)
  1507. // diagnostics
  1508. a.Router.GET("/diagnostics/requestQueue", a.GetPrometheusQueueState)
  1509. a.Router.GET("/diagnostics/prometheusMetrics", a.GetPrometheusMetrics)
  1510. a.Router.GET("/logs/level", a.GetLogLevel)
  1511. a.Router.POST("/logs/level", a.SetLogLevel)
  1512. a.httpServices.RegisterAll(a.Router)
  1513. return a
  1514. }
  1515. func writeErrorResponse(w http.ResponseWriter, code int, message string) {
  1516. out := map[string]string{
  1517. "message": message,
  1518. }
  1519. bytes, err := json.Marshal(out)
  1520. if err != nil {
  1521. w.Header().Set("Content-Type", "text/plain")
  1522. w.WriteHeader(500)
  1523. fmt.Fprint(w, "unable to marshall json for error")
  1524. log.Warnf("Failed to marshall JSON for error response: %s", err.Error())
  1525. return
  1526. }
  1527. w.WriteHeader(code)
  1528. fmt.Fprint(w, string(bytes))
  1529. }