router.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. package costmodel
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "k8s.io/klog"
  15. "github.com/julienschmidt/httprouter"
  16. sentry "github.com/getsentry/sentry-go"
  17. costAnalyzerCloud "github.com/kubecost/cost-model/pkg/cloud"
  18. "github.com/kubecost/cost-model/pkg/clustercache"
  19. cm "github.com/kubecost/cost-model/pkg/clustermanager"
  20. "github.com/kubecost/cost-model/pkg/env"
  21. "github.com/kubecost/cost-model/pkg/errors"
  22. "github.com/kubecost/cost-model/pkg/prom"
  23. "github.com/kubecost/cost-model/pkg/thanos"
  24. prometheusClient "github.com/prometheus/client_golang/api"
  25. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  26. v1 "k8s.io/api/core/v1"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "github.com/patrickmn/go-cache"
  29. "github.com/prometheus/client_golang/prometheus"
  30. "k8s.io/client-go/kubernetes"
  31. "k8s.io/client-go/rest"
  32. )
  33. const (
  34. prometheusTroubleshootingEp = "http://docs.kubecost.com/custom-prom#troubleshoot"
  35. RFC3339Milli = "2006-01-02T15:04:05.000Z"
  36. )
  37. var (
  38. // gitCommit is set by the build system
  39. gitCommit string
  40. dbBasicAuthUsername string = env.GetDBBasicAuthUsername()
  41. dbBasicAuthPW string = env.GetDBBasicAuthUserPassword()
  42. dbBearerToken string = env.GetDBBearerToken()
  43. multiclusterDBBasicAuthUsername string = env.GetMultiClusterBasicAuthUsername()
  44. multiclusterDBBasicAuthPW string = env.GetMultiClusterBasicAuthPassword()
  45. multiClusterBearerToken string = env.GetMultiClusterBearerToken()
  46. )
  47. var Router = httprouter.New()
  48. var A Accesses
  49. type Accesses struct {
  50. PrometheusClient prometheusClient.Client
  51. ThanosClient prometheusClient.Client
  52. KubeClientSet kubernetes.Interface
  53. ClusterManager *cm.ClusterManager
  54. Cloud costAnalyzerCloud.Provider
  55. CPUPriceRecorder *prometheus.GaugeVec
  56. RAMPriceRecorder *prometheus.GaugeVec
  57. PersistentVolumePriceRecorder *prometheus.GaugeVec
  58. GPUPriceRecorder *prometheus.GaugeVec
  59. NodeTotalPriceRecorder *prometheus.GaugeVec
  60. NodeSpotRecorder *prometheus.GaugeVec
  61. RAMAllocationRecorder *prometheus.GaugeVec
  62. CPUAllocationRecorder *prometheus.GaugeVec
  63. GPUAllocationRecorder *prometheus.GaugeVec
  64. PVAllocationRecorder *prometheus.GaugeVec
  65. ClusterManagementCostRecorder *prometheus.GaugeVec
  66. NetworkZoneEgressRecorder prometheus.Gauge
  67. NetworkRegionEgressRecorder prometheus.Gauge
  68. NetworkInternetEgressRecorder prometheus.Gauge
  69. ServiceSelectorRecorder *prometheus.GaugeVec
  70. DeploymentSelectorRecorder *prometheus.GaugeVec
  71. Model *CostModel
  72. OutOfClusterCache *cache.Cache
  73. }
  74. type DataEnvelope struct {
  75. Code int `json:"code"`
  76. Status string `json:"status"`
  77. Data interface{} `json:"data"`
  78. Message string `json:"message,omitempty"`
  79. }
  80. // 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
  81. type FilterFunc func(*CostData) (bool, string)
  82. // FilterCostData allows through only CostData that matches all the given filter functions
  83. func FilterCostData(data map[string]*CostData, retains []FilterFunc, filters []FilterFunc) (map[string]*CostData, int, map[string]int) {
  84. result := make(map[string]*CostData)
  85. filteredEnvironments := make(map[string]int)
  86. filteredContainers := 0
  87. DataLoop:
  88. for key, datum := range data {
  89. for _, rf := range retains {
  90. if ok, _ := rf(datum); ok {
  91. result[key] = datum
  92. // if any retain function passes, the data is retained and move on
  93. continue DataLoop
  94. }
  95. }
  96. for _, ff := range filters {
  97. if ok, environment := ff(datum); !ok {
  98. if environment != "" {
  99. filteredEnvironments[environment]++
  100. }
  101. filteredContainers++
  102. // if any filter function check fails, move on to the next datum
  103. continue DataLoop
  104. }
  105. }
  106. result[key] = datum
  107. }
  108. return result, filteredContainers, filteredEnvironments
  109. }
  110. func filterFields(fields string, data map[string]*CostData) map[string]CostData {
  111. fs := strings.Split(fields, ",")
  112. fmap := make(map[string]bool)
  113. for _, f := range fs {
  114. fieldNameLower := strings.ToLower(f) // convert to go struct name by uppercasing first letter
  115. klog.V(1).Infof("to delete: %s", fieldNameLower)
  116. fmap[fieldNameLower] = true
  117. }
  118. filteredData := make(map[string]CostData)
  119. for cname, costdata := range data {
  120. s := reflect.TypeOf(*costdata)
  121. val := reflect.ValueOf(*costdata)
  122. costdata2 := CostData{}
  123. cd2 := reflect.New(reflect.Indirect(reflect.ValueOf(costdata2)).Type()).Elem()
  124. n := s.NumField()
  125. for i := 0; i < n; i++ {
  126. field := s.Field(i)
  127. value := val.Field(i)
  128. value2 := cd2.Field(i)
  129. if _, ok := fmap[strings.ToLower(field.Name)]; !ok {
  130. value2.Set(reflect.Value(value))
  131. }
  132. }
  133. filteredData[cname] = cd2.Interface().(CostData)
  134. }
  135. return filteredData
  136. }
  137. func normalizeTimeParam(param string) (string, error) {
  138. if param == "" {
  139. return "", fmt.Errorf("invalid time param")
  140. }
  141. // convert days to hours
  142. if param[len(param)-1:] == "d" {
  143. count := param[:len(param)-1]
  144. val, err := strconv.ParseInt(count, 10, 64)
  145. if err != nil {
  146. return "", err
  147. }
  148. val = val * 24
  149. param = fmt.Sprintf("%dh", val)
  150. }
  151. return param, nil
  152. }
  153. // parsePercentString takes a string of expected format "N%" and returns a floating point 0.0N.
  154. // If the "%" symbol is missing, it just returns 0.0N. Empty string is interpreted as "0%" and
  155. // return 0.0.
  156. func ParsePercentString(percentStr string) (float64, error) {
  157. if len(percentStr) == 0 {
  158. return 0.0, nil
  159. }
  160. if percentStr[len(percentStr)-1:] == "%" {
  161. percentStr = percentStr[:len(percentStr)-1]
  162. }
  163. discount, err := strconv.ParseFloat(percentStr, 64)
  164. if err != nil {
  165. return 0.0, err
  166. }
  167. discount *= 0.01
  168. return discount, nil
  169. }
  170. // parseDuration converts a Prometheus-style duration string into a Duration
  171. func ParseDuration(duration string) (*time.Duration, error) {
  172. unitStr := duration[len(duration)-1:]
  173. var unit time.Duration
  174. switch unitStr {
  175. case "s":
  176. unit = time.Second
  177. case "m":
  178. unit = time.Minute
  179. case "h":
  180. unit = time.Hour
  181. case "d":
  182. unit = 24.0 * time.Hour
  183. default:
  184. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  185. }
  186. amountStr := duration[:len(duration)-1]
  187. amount, err := strconv.ParseInt(amountStr, 10, 64)
  188. if err != nil {
  189. return nil, fmt.Errorf("error parsing duration: %s did not match expected format [0-9+](s|m|d|h)", duration)
  190. }
  191. dur := time.Duration(amount) * unit
  192. return &dur, nil
  193. }
  194. // ParseTimeRange returns a start and end time, respectively, which are converted from
  195. // a duration and offset, defined as strings with Prometheus-style syntax.
  196. func ParseTimeRange(duration, offset string) (*time.Time, *time.Time, error) {
  197. // endTime defaults to the current time, unless an offset is explicity declared,
  198. // in which case it shifts endTime back by given duration
  199. endTime := time.Now()
  200. if offset != "" {
  201. o, err := ParseDuration(offset)
  202. if err != nil {
  203. return nil, nil, fmt.Errorf("error parsing offset (%s): %s", offset, err)
  204. }
  205. endTime = endTime.Add(-1 * *o)
  206. }
  207. // if duration is defined in terms of days, convert to hours
  208. // e.g. convert "2d" to "48h"
  209. durationNorm, err := normalizeTimeParam(duration)
  210. if err != nil {
  211. return nil, nil, fmt.Errorf("error parsing duration (%s): %s", duration, err)
  212. }
  213. // convert time duration into start and end times, formatted
  214. // as ISO datetime strings
  215. dur, err := time.ParseDuration(durationNorm)
  216. if err != nil {
  217. return nil, nil, fmt.Errorf("errorf parsing duration (%s): %s", durationNorm, err)
  218. }
  219. startTime := endTime.Add(-1 * dur)
  220. return &startTime, &endTime, nil
  221. }
  222. func WrapDataWithMessage(data interface{}, err error, message string) []byte {
  223. var resp []byte
  224. if err != nil {
  225. klog.V(1).Infof("Error returned to client: %s", err.Error())
  226. resp, _ = json.Marshal(&DataEnvelope{
  227. Code: http.StatusInternalServerError,
  228. Status: "error",
  229. Message: err.Error(),
  230. Data: data,
  231. })
  232. } else {
  233. resp, _ = json.Marshal(&DataEnvelope{
  234. Code: http.StatusOK,
  235. Status: "success",
  236. Data: data,
  237. Message: message,
  238. })
  239. }
  240. return resp
  241. }
  242. func WrapData(data interface{}, err error) []byte {
  243. var resp []byte
  244. if err != nil {
  245. klog.V(1).Infof("Error returned to client: %s", err.Error())
  246. resp, _ = json.Marshal(&DataEnvelope{
  247. Code: http.StatusInternalServerError,
  248. Status: "error",
  249. Message: err.Error(),
  250. Data: data,
  251. })
  252. } else {
  253. resp, _ = json.Marshal(&DataEnvelope{
  254. Code: http.StatusOK,
  255. Status: "success",
  256. Data: data,
  257. })
  258. }
  259. return resp
  260. }
  261. // 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.
  262. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  263. w.Header().Set("Content-Type", "application/json")
  264. w.Header().Set("Access-Control-Allow-Origin", "*")
  265. err := a.Cloud.DownloadPricingData()
  266. w.Write(WrapData(nil, err))
  267. }
  268. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  269. w.Header().Set("Content-Type", "application/json")
  270. w.Header().Set("Access-Control-Allow-Origin", "*")
  271. window := r.URL.Query().Get("timeWindow")
  272. offset := r.URL.Query().Get("offset")
  273. fields := r.URL.Query().Get("filterFields")
  274. namespace := r.URL.Query().Get("namespace")
  275. if offset != "" {
  276. offset = "offset " + offset
  277. }
  278. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, window, offset, namespace)
  279. if fields != "" {
  280. filteredData := filterFields(fields, data)
  281. w.Write(WrapData(filteredData, err))
  282. } else {
  283. w.Write(WrapData(data, err))
  284. }
  285. }
  286. func (a *Accesses) ClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  287. w.Header().Set("Content-Type", "application/json")
  288. w.Header().Set("Access-Control-Allow-Origin", "*")
  289. window := r.URL.Query().Get("window")
  290. offset := r.URL.Query().Get("offset")
  291. useThanos, _ := strconv.ParseBool(r.URL.Query().Get("multi"))
  292. if useThanos && !thanos.IsEnabled() {
  293. w.Write(WrapData(nil, fmt.Errorf("Multi=true while Thanos is not enabled.")))
  294. return
  295. }
  296. var client prometheusClient.Client
  297. if useThanos {
  298. client = a.ThanosClient
  299. offset = thanos.Offset()
  300. } else {
  301. client = a.PrometheusClient
  302. }
  303. data, err := ComputeClusterCosts(client, a.Cloud, window, offset, true)
  304. w.Write(WrapData(data, err))
  305. }
  306. func (a *Accesses) ClusterCostsOverTime(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  307. w.Header().Set("Content-Type", "application/json")
  308. w.Header().Set("Access-Control-Allow-Origin", "*")
  309. start := r.URL.Query().Get("start")
  310. end := r.URL.Query().Get("end")
  311. window := r.URL.Query().Get("window")
  312. offset := r.URL.Query().Get("offset")
  313. data, err := ClusterCostsOverTime(a.PrometheusClient, a.Cloud, start, end, window, offset)
  314. w.Write(WrapData(data, err))
  315. }
  316. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  317. w.Header().Set("Content-Type", "application/json")
  318. w.Header().Set("Access-Control-Allow-Origin", "*")
  319. start := r.URL.Query().Get("start")
  320. end := r.URL.Query().Get("end")
  321. window := r.URL.Query().Get("window")
  322. fields := r.URL.Query().Get("filterFields")
  323. namespace := r.URL.Query().Get("namespace")
  324. cluster := r.URL.Query().Get("cluster")
  325. remote := r.URL.Query().Get("remote")
  326. remoteEnabled := env.IsRemoteEnabled() && remote != "false"
  327. // Use Thanos Client if it exists (enabled) and remote flag set
  328. var pClient prometheusClient.Client
  329. if remote != "false" && a.ThanosClient != nil {
  330. pClient = a.ThanosClient
  331. } else {
  332. pClient = a.PrometheusClient
  333. }
  334. resolutionHours := 1.0
  335. data, err := a.Model.ComputeCostDataRange(pClient, a.KubeClientSet, a.Cloud, start, end, window, resolutionHours, namespace, cluster, remoteEnabled)
  336. if err != nil {
  337. w.Write(WrapData(nil, err))
  338. }
  339. if fields != "" {
  340. filteredData := filterFields(fields, data)
  341. w.Write(WrapData(filteredData, err))
  342. } else {
  343. w.Write(WrapData(data, err))
  344. }
  345. }
  346. // CostDataModelRangeLarge is experimental multi-cluster and long-term data storage in SQL support.
  347. func (a *Accesses) CostDataModelRangeLarge(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  348. w.Header().Set("Content-Type", "application/json")
  349. w.Header().Set("Access-Control-Allow-Origin", "*")
  350. startString := r.URL.Query().Get("start")
  351. endString := r.URL.Query().Get("end")
  352. windowString := r.URL.Query().Get("window")
  353. var start time.Time
  354. var end time.Time
  355. var err error
  356. if windowString == "" {
  357. windowString = "1h"
  358. }
  359. if startString != "" {
  360. start, err = time.Parse(RFC3339Milli, startString)
  361. if err != nil {
  362. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  363. w.Write(WrapData(nil, err))
  364. }
  365. } else {
  366. window, err := time.ParseDuration(windowString)
  367. if err != nil {
  368. w.Write(WrapData(nil, fmt.Errorf("Invalid duration '%s'", windowString)))
  369. }
  370. start = time.Now().Add(-2 * window)
  371. }
  372. if endString != "" {
  373. end, err = time.Parse(RFC3339Milli, endString)
  374. if err != nil {
  375. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  376. w.Write(WrapData(nil, err))
  377. }
  378. } else {
  379. end = time.Now()
  380. }
  381. remoteLayout := "2006-01-02T15:04:05Z"
  382. remoteStartStr := start.Format(remoteLayout)
  383. remoteEndStr := end.Format(remoteLayout)
  384. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  385. data, err := CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  386. w.Write(WrapData(data, err))
  387. }
  388. func parseAggregations(customAggregation, aggregator, filterType string) (string, []string, string) {
  389. var key string
  390. var filter string
  391. var val []string
  392. if customAggregation != "" {
  393. key = customAggregation
  394. filter = filterType
  395. val = strings.Split(customAggregation, ",")
  396. } else {
  397. aggregations := strings.Split(aggregator, ",")
  398. for i, agg := range aggregations {
  399. aggregations[i] = "kubernetes_" + agg
  400. }
  401. key = strings.Join(aggregations, ",")
  402. filter = "kubernetes_" + filterType
  403. val = aggregations
  404. }
  405. return key, val, filter
  406. }
  407. func (a *Accesses) OutofClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  408. w.Header().Set("Content-Type", "application/json")
  409. w.Header().Set("Access-Control-Allow-Origin", "*")
  410. start := r.URL.Query().Get("start")
  411. end := r.URL.Query().Get("end")
  412. aggregator := r.URL.Query().Get("aggregator")
  413. customAggregation := r.URL.Query().Get("customAggregation")
  414. filterType := r.URL.Query().Get("filterType")
  415. filterValue := r.URL.Query().Get("filterValue")
  416. var data []*costAnalyzerCloud.OutOfClusterAllocation
  417. var err error
  418. _, aggregations, filter := parseAggregations(customAggregation, aggregator, filterType)
  419. data, err = a.Cloud.ExternalAllocations(start, end, aggregations, filter, filterValue, false)
  420. w.Write(WrapData(data, err))
  421. }
  422. func (a *Accesses) OutOfClusterCostsWithCache(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  423. w.Header().Set("Content-Type", "application/json")
  424. w.Header().Set("Access-Control-Allow-Origin", "*")
  425. // start date for which to query costs, inclusive; format YYYY-MM-DD
  426. start := r.URL.Query().Get("start")
  427. // end date for which to query costs, inclusive; format YYYY-MM-DD
  428. end := r.URL.Query().Get("end")
  429. // aggregator sets the field by which to aggregate; default, prepended by "kubernetes_"
  430. kubernetesAggregation := r.URL.Query().Get("aggregator")
  431. // customAggregation allows full customization of aggregator w/o prepending
  432. customAggregation := r.URL.Query().Get("customAggregation")
  433. // disableCache, if set to "true", tells this function to recompute and
  434. // cache the requested data
  435. disableCache := r.URL.Query().Get("disableCache") == "true"
  436. // clearCache, if set to "true", tells this function to flush the cache,
  437. // then recompute and cache the requested data
  438. clearCache := r.URL.Query().Get("clearCache") == "true"
  439. filterType := r.URL.Query().Get("filterType")
  440. filterValue := r.URL.Query().Get("filterValue")
  441. aggregationkey, aggregation, filter := parseAggregations(customAggregation, kubernetesAggregation, filterType)
  442. // clear cache prior to checking the cache so that a clearCache=true
  443. // request always returns a freshly computed value
  444. if clearCache {
  445. a.OutOfClusterCache.Flush()
  446. }
  447. // attempt to retrieve cost data from cache
  448. key := fmt.Sprintf(`%s:%s:%s:%s:%s`, start, end, aggregationkey, filter, filterValue)
  449. if value, found := a.OutOfClusterCache.Get(key); found && !disableCache {
  450. if data, ok := value.([]*costAnalyzerCloud.OutOfClusterAllocation); ok {
  451. w.Write(WrapDataWithMessage(data, nil, fmt.Sprintf("out of cluster cache hit: %s", key)))
  452. return
  453. }
  454. klog.Errorf("caching error: failed to type cast data: %s", key)
  455. }
  456. data, err := a.Cloud.ExternalAllocations(start, end, aggregation, filter, filterValue, false)
  457. if err == nil {
  458. a.OutOfClusterCache.Set(key, data, cache.DefaultExpiration)
  459. }
  460. w.Write(WrapDataWithMessage(data, err, fmt.Sprintf("out of cluser cache miss: %s", key)))
  461. }
  462. func (p *Accesses) GetAllNodePricing(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. data, err := p.Cloud.AllNodePricing()
  466. w.Write(WrapData(data, err))
  467. }
  468. func (p *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  469. w.Header().Set("Content-Type", "application/json")
  470. w.Header().Set("Access-Control-Allow-Origin", "*")
  471. data, err := p.Cloud.GetConfig()
  472. w.Write(WrapData(data, err))
  473. }
  474. func (p *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  475. w.Header().Set("Content-Type", "application/json")
  476. w.Header().Set("Access-Control-Allow-Origin", "*")
  477. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.SpotInfoUpdateType)
  478. if err != nil {
  479. w.Write(WrapData(data, err))
  480. return
  481. }
  482. w.Write(WrapData(data, err))
  483. err = p.Cloud.DownloadPricingData()
  484. if err != nil {
  485. klog.V(1).Infof("Error redownloading data on config update: %s", err.Error())
  486. }
  487. return
  488. }
  489. func (p *Accesses) UpdateAthenaInfoConfigs(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 := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.AthenaInfoUpdateType)
  493. if err != nil {
  494. w.Write(WrapData(data, err))
  495. return
  496. }
  497. w.Write(WrapData(data, err))
  498. return
  499. }
  500. func (p *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  501. w.Header().Set("Content-Type", "application/json")
  502. w.Header().Set("Access-Control-Allow-Origin", "*")
  503. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.BigqueryUpdateType)
  504. if err != nil {
  505. w.Write(WrapData(data, err))
  506. return
  507. }
  508. w.Write(WrapData(data, err))
  509. return
  510. }
  511. func (p *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  512. w.Header().Set("Content-Type", "application/json")
  513. w.Header().Set("Access-Control-Allow-Origin", "*")
  514. data, err := p.Cloud.UpdateConfig(r.Body, "")
  515. if err != nil {
  516. w.Write(WrapData(data, err))
  517. return
  518. }
  519. w.Write(WrapData(data, err))
  520. return
  521. }
  522. func (p *Accesses) ManagementPlatform(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  523. w.Header().Set("Content-Type", "application/json")
  524. w.Header().Set("Access-Control-Allow-Origin", "*")
  525. data, err := p.Cloud.GetManagementPlatform()
  526. if err != nil {
  527. w.Write(WrapData(data, err))
  528. return
  529. }
  530. w.Write(WrapData(data, err))
  531. return
  532. }
  533. func (p *Accesses) ClusterInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  534. w.Header().Set("Content-Type", "application/json")
  535. w.Header().Set("Access-Control-Allow-Origin", "*")
  536. data := GetClusterInfo(p.KubeClientSet, p.Cloud)
  537. w.Write(WrapData(data, nil))
  538. }
  539. func (p *Accesses) GetServiceAccountStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  540. w.Header().Set("Content-Type", "application/json")
  541. w.Header().Set("Access-Control-Allow-Origin", "*")
  542. w.Write(WrapData(A.Cloud.ServiceAccountStatus(), nil))
  543. }
  544. func (p *Accesses) GetPrometheusMetadata(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  545. w.Header().Set("Content-Type", "application/json")
  546. w.Header().Set("Access-Control-Allow-Origin", "*")
  547. w.Write(WrapData(ValidatePrometheus(p.PrometheusClient, false)))
  548. }
  549. // Creates a new ClusterManager instance using a boltdb storage. If that fails,
  550. // then we fall back to a memory-only storage.
  551. func newClusterManager() *cm.ClusterManager {
  552. clustersConfigFile := "/var/configs/clusters/default-clusters.yaml"
  553. // Return a memory-backed cluster manager populated by configmap
  554. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  555. // NOTE: The following should be used with a persistent disk store. Since the
  556. // NOTE: configmap approach is currently the "persistent" source (entries are read-only
  557. // NOTE: on the backend), we don't currently need to store on disk.
  558. /*
  559. path := env.GetConfigPath()
  560. db, err := bolt.Open(path+"costmodel.db", 0600, nil)
  561. if err != nil {
  562. klog.V(1).Infof("[Error] Failed to create costmodel.db: %s", err.Error())
  563. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  564. }
  565. store, err := cm.NewBoltDBClusterStorage("clusters", db)
  566. if err != nil {
  567. klog.V(1).Infof("[Error] Failed to Create Cluster Storage: %s", err.Error())
  568. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  569. }
  570. return cm.NewConfiguredClusterManager(store, clustersConfigFile)
  571. */
  572. }
  573. type ConfigWatchers struct {
  574. ConfigmapName string
  575. WatchFunc func(string, map[string]string) error
  576. }
  577. // captures the panic event in sentry
  578. func capturePanicEvent(err string, stack string) {
  579. msg := fmt.Sprintf("Panic: %s\nStackTrace: %s\n", err, stack)
  580. sentry.CurrentHub().CaptureEvent(&sentry.Event{
  581. Level: sentry.LevelError,
  582. Message: msg,
  583. })
  584. sentry.Flush(5 * time.Second)
  585. }
  586. // handle any panics reported by the errors package
  587. func handlePanic(p errors.Panic) bool {
  588. err := p.Error
  589. if err != nil {
  590. if err, ok := err.(error); ok {
  591. capturePanicEvent(err.Error(), p.Stack)
  592. }
  593. if err, ok := err.(string); ok {
  594. capturePanicEvent(err, p.Stack)
  595. }
  596. }
  597. // Return true to recover iff the type is http, otherwise allow kubernetes
  598. // to recover.
  599. return p.Type == errors.PanicTypeHTTP
  600. }
  601. func Initialize(additionalConfigWatchers ...ConfigWatchers) {
  602. klog.InitFlags(nil)
  603. flag.Set("v", "3")
  604. flag.Parse()
  605. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  606. var err error
  607. if errorReportingEnabled {
  608. err = sentry.Init(sentry.ClientOptions{Release: gitCommit})
  609. if err != nil {
  610. klog.Infof("Failed to initialize sentry for error reporting")
  611. } else {
  612. err = errors.SetPanicHandler(handlePanic)
  613. if err != nil {
  614. klog.Infof("Failed to set panic handler: %s", err)
  615. }
  616. }
  617. }
  618. address := env.GetPrometheusServerEndpoint()
  619. if address == "" {
  620. klog.Fatalf("No address for prometheus set in $%s. Aborting.", env.PrometheusServerEndpointEnvVar)
  621. }
  622. queryConcurrency := env.GetMaxQueryConcurrency()
  623. klog.Infof("Prometheus/Thanos Client Max Concurrency set to %d", queryConcurrency)
  624. tlsConfig := &tls.Config{InsecureSkipVerify: env.GetInsecureSkipVerify()}
  625. var LongTimeoutRoundTripper http.RoundTripper = &http.Transport{ // may be necessary for long prometheus queries. TODO: make this configurable
  626. Proxy: http.ProxyFromEnvironment,
  627. DialContext: (&net.Dialer{
  628. Timeout: 120 * time.Second,
  629. KeepAlive: 120 * time.Second,
  630. }).DialContext,
  631. TLSHandshakeTimeout: 10 * time.Second,
  632. TLSClientConfig: tlsConfig,
  633. }
  634. pc := prometheusClient.Config{
  635. Address: address,
  636. RoundTripper: LongTimeoutRoundTripper,
  637. }
  638. promCli, _ := prom.NewRateLimitedClient(pc, queryConcurrency, dbBasicAuthUsername, dbBasicAuthPW, dbBearerToken)
  639. m, err := ValidatePrometheus(promCli, false)
  640. if err != nil || m.Running == false {
  641. if err != nil {
  642. klog.Errorf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  643. } else if m.Running == false {
  644. klog.Errorf("Prometheus at %s is not running. Troubleshooting help available at: %s", address, prometheusTroubleshootingEp)
  645. }
  646. api := prometheusAPI.NewAPI(promCli)
  647. _, err = api.Config(context.Background())
  648. if err != nil {
  649. 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)
  650. } else {
  651. klog.V(1).Info("Retrieved a prometheus config file from: " + address)
  652. }
  653. } else {
  654. klog.V(1).Info("Success: retrieved the 'up' query against prometheus at: " + address)
  655. }
  656. // Kubernetes API setup
  657. kc, err := rest.InClusterConfig()
  658. if err != nil {
  659. panic(err.Error())
  660. }
  661. kubeClientset, err := kubernetes.NewForConfig(kc)
  662. if err != nil {
  663. panic(err.Error())
  664. }
  665. // Create Kubernetes Cluster Cache + Watchers
  666. k8sCache := clustercache.NewKubernetesClusterCache(kubeClientset)
  667. k8sCache.Run()
  668. cloudProviderKey := env.GetCloudProviderAPIKey()
  669. cloudProvider, err := costAnalyzerCloud.NewProvider(k8sCache, cloudProviderKey)
  670. if err != nil {
  671. panic(err.Error())
  672. }
  673. watchConfigFunc := func(c interface{}) {
  674. conf := c.(*v1.ConfigMap)
  675. if conf.GetName() == "pricing-configs" {
  676. _, err := cloudProvider.UpdateConfigFromConfigMap(conf.Data)
  677. if err != nil {
  678. klog.Infof("ERROR UPDATING %s CONFIG: %s", "pricing-configs", err.Error())
  679. }
  680. }
  681. for _, cw := range additionalConfigWatchers {
  682. if conf.GetName() == cw.ConfigmapName {
  683. err := cw.WatchFunc(conf.GetName(), conf.Data)
  684. if err != nil {
  685. klog.Infof("ERROR UPDATING %s CONFIG: %s", cw.ConfigmapName, err.Error())
  686. }
  687. }
  688. }
  689. }
  690. kubecostNamespace := env.GetKubecostNamespace()
  691. // We need an initial invocation because the init of the cache has happened before we had access to the provider.
  692. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get("pricing-configs", metav1.GetOptions{})
  693. if err != nil {
  694. klog.Infof("No %s configmap found at installtime, using existing configs: %s", "pricing-configs", err.Error())
  695. } else {
  696. watchConfigFunc(configs)
  697. }
  698. for _, cw := range additionalConfigWatchers {
  699. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get(cw.ConfigmapName, metav1.GetOptions{})
  700. if err != nil {
  701. klog.Infof("No %s configmap found at installtime, using existing configs: %s", cw.ConfigmapName, err.Error())
  702. } else {
  703. watchConfigFunc(configs)
  704. }
  705. }
  706. k8sCache.SetConfigMapUpdateFunc(watchConfigFunc)
  707. // TODO: General Architecture Note: Several passes have been made to modularize a lot of
  708. // TODO: our code, but the router still continues to be the obvious entry point for new \
  709. // TODO: features. We should look to spliting out the actual "router" functionality and
  710. // TODO: implement a builder -> controller for stitching new features and other dependencies.
  711. clusterManager := newClusterManager()
  712. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  713. Name: "node_cpu_hourly_cost",
  714. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  715. }, []string{"instance", "node", "instance_type", "region", "provider_id"})
  716. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  717. Name: "node_ram_hourly_cost",
  718. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  719. }, []string{"instance", "node", "instance_type", "region", "provider_id"})
  720. gpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  721. Name: "node_gpu_hourly_cost",
  722. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  723. }, []string{"instance", "node", "instance_type", "region", "provider_id"})
  724. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  725. Name: "node_total_hourly_cost",
  726. Help: "node_total_hourly_cost Total node cost per hour",
  727. }, []string{"instance", "node", "instance_type", "region", "provider_id"})
  728. spotGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  729. Name: "kubecost_node_is_spot",
  730. Help: "kubecost_node_is_spot Cloud provider info about node preemptibility",
  731. }, []string{"instance", "node", "instance_type", "region", "provider_id"})
  732. pvGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  733. Name: "pv_hourly_cost",
  734. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  735. }, []string{"volumename", "persistentvolume"})
  736. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  737. Name: "container_memory_allocation_bytes",
  738. Help: "container_memory_allocation_bytes Bytes of RAM used",
  739. }, []string{"namespace", "pod", "container", "instance", "node"})
  740. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  741. Name: "container_cpu_allocation",
  742. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  743. }, []string{"namespace", "pod", "container", "instance", "node"})
  744. GPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  745. Name: "container_gpu_allocation",
  746. Help: "container_gpu_allocation GPU used",
  747. }, []string{"namespace", "pod", "container", "instance", "node"})
  748. PVAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  749. Name: "pod_pvc_allocation",
  750. Help: "pod_pvc_allocation Bytes used by a PVC attached to a pod",
  751. }, []string{"namespace", "pod", "persistentvolumeclaim", "persistentvolume"})
  752. NetworkZoneEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  753. Name: "kubecost_network_zone_egress_cost",
  754. Help: "kubecost_network_zone_egress_cost Total cost per GB egress across zones",
  755. })
  756. NetworkRegionEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  757. Name: "kubecost_network_region_egress_cost",
  758. Help: "kubecost_network_region_egress_cost Total cost per GB egress across regions",
  759. })
  760. NetworkInternetEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  761. Name: "kubecost_network_internet_egress_cost",
  762. Help: "kubecost_network_internet_egress_cost Total cost per GB of internet egress.",
  763. })
  764. ClusterManagementCostRecorder := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  765. Name: "kubecost_cluster_management_cost",
  766. Help: "kubecost_cluster_management_cost Hourly cost paid as a cluster management fee.",
  767. }, []string{"provisioner_name"})
  768. prometheus.MustRegister(cpuGv)
  769. prometheus.MustRegister(ramGv)
  770. prometheus.MustRegister(gpuGv)
  771. prometheus.MustRegister(totalGv)
  772. prometheus.MustRegister(pvGv)
  773. prometheus.MustRegister(spotGv)
  774. prometheus.MustRegister(RAMAllocation)
  775. prometheus.MustRegister(CPUAllocation)
  776. prometheus.MustRegister(PVAllocation)
  777. prometheus.MustRegister(GPUAllocation)
  778. prometheus.MustRegister(NetworkZoneEgressRecorder, NetworkRegionEgressRecorder, NetworkInternetEgressRecorder)
  779. prometheus.MustRegister(ClusterManagementCostRecorder)
  780. prometheus.MustRegister(ServiceCollector{
  781. KubeClientSet: kubeClientset,
  782. })
  783. prometheus.MustRegister(DeploymentCollector{
  784. KubeClientSet: kubeClientset,
  785. })
  786. prometheus.MustRegister(StatefulsetCollector{
  787. KubeClientSet: kubeClientset,
  788. })
  789. prometheus.MustRegister(ClusterInfoCollector{
  790. KubeClientSet: kubeClientset,
  791. Cloud: cloudProvider,
  792. })
  793. // cache responses from model for a default of 5 minutes; clear expired responses every 10 minutes
  794. outOfClusterCache := cache.New(time.Minute*5, time.Minute*10)
  795. A = Accesses{
  796. PrometheusClient: promCli,
  797. KubeClientSet: kubeClientset,
  798. ClusterManager: clusterManager,
  799. Cloud: cloudProvider,
  800. CPUPriceRecorder: cpuGv,
  801. RAMPriceRecorder: ramGv,
  802. GPUPriceRecorder: gpuGv,
  803. NodeTotalPriceRecorder: totalGv,
  804. NodeSpotRecorder: spotGv,
  805. RAMAllocationRecorder: RAMAllocation,
  806. CPUAllocationRecorder: CPUAllocation,
  807. GPUAllocationRecorder: GPUAllocation,
  808. PVAllocationRecorder: PVAllocation,
  809. NetworkZoneEgressRecorder: NetworkZoneEgressRecorder,
  810. NetworkRegionEgressRecorder: NetworkRegionEgressRecorder,
  811. NetworkInternetEgressRecorder: NetworkInternetEgressRecorder,
  812. PersistentVolumePriceRecorder: pvGv,
  813. ClusterManagementCostRecorder: ClusterManagementCostRecorder,
  814. Model: NewCostModel(k8sCache),
  815. OutOfClusterCache: outOfClusterCache,
  816. }
  817. remoteEnabled := env.IsRemoteEnabled()
  818. if remoteEnabled {
  819. info, err := cloudProvider.ClusterInfo()
  820. klog.Infof("Saving cluster with id:'%s', and name:'%s' to durable storage", info["id"], info["name"])
  821. if err != nil {
  822. klog.Infof("Error saving cluster id %s", err.Error())
  823. }
  824. _, _, err = costAnalyzerCloud.GetOrCreateClusterMeta(info["id"], info["name"])
  825. if err != nil {
  826. klog.Infof("Unable to set cluster id '%s' for cluster '%s', %s", info["id"], info["name"], err.Error())
  827. }
  828. }
  829. // Thanos Client
  830. if thanos.IsEnabled() {
  831. thanosUrl := thanos.QueryURL()
  832. if thanosUrl != "" {
  833. var thanosRT http.RoundTripper = &http.Transport{
  834. Proxy: http.ProxyFromEnvironment,
  835. DialContext: (&net.Dialer{
  836. Timeout: 120 * time.Second,
  837. KeepAlive: 120 * time.Second,
  838. }).DialContext,
  839. TLSHandshakeTimeout: 10 * time.Second,
  840. TLSClientConfig: tlsConfig,
  841. }
  842. thanosConfig := prometheusClient.Config{
  843. Address: thanosUrl,
  844. RoundTripper: thanosRT,
  845. }
  846. thanosCli, _ := prom.NewRateLimitedClient(thanosConfig, queryConcurrency, multiclusterDBBasicAuthUsername, multiclusterDBBasicAuthPW, multiClusterBearerToken)
  847. _, err = ValidatePrometheus(thanosCli, true)
  848. if err != nil {
  849. klog.V(1).Infof("[Warning] Failed to query Thanos at %s. Error: %s.", thanosUrl, err.Error())
  850. A.ThanosClient = thanosCli
  851. } else {
  852. klog.V(1).Info("Success: retrieved the 'up' query against Thanos at: " + thanosUrl)
  853. A.ThanosClient = thanosCli
  854. }
  855. } else {
  856. klog.Infof("Error resolving environment variable: $%s", env.ThanosQueryUrlEnvVar)
  857. }
  858. }
  859. err = A.Cloud.DownloadPricingData()
  860. if err != nil {
  861. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  862. }
  863. StartCostModelMetricRecording(&A)
  864. managerEndpoints := cm.NewClusterManagerEndpoints(A.ClusterManager)
  865. Router.GET("/costDataModel", A.CostDataModel)
  866. Router.GET("/costDataModelRange", A.CostDataModelRange)
  867. Router.GET("/costDataModelRangeLarge", A.CostDataModelRangeLarge)
  868. Router.GET("/outOfClusterCosts", A.OutOfClusterCostsWithCache)
  869. Router.GET("/allNodePricing", A.GetAllNodePricing)
  870. Router.POST("/refreshPricing", A.RefreshPricingData)
  871. Router.GET("/clusterCostsOverTime", A.ClusterCostsOverTime)
  872. Router.GET("/clusterCosts", A.ClusterCosts)
  873. Router.GET("/validatePrometheus", A.GetPrometheusMetadata)
  874. Router.GET("/managementPlatform", A.ManagementPlatform)
  875. Router.GET("/clusterInfo", A.ClusterInfo)
  876. Router.GET("/clusters", managerEndpoints.GetAllClusters)
  877. Router.GET("/serviceAccountStatus", A.GetServiceAccountStatus)
  878. Router.PUT("/clusters", managerEndpoints.PutCluster)
  879. Router.DELETE("/clusters/:id", managerEndpoints.DeleteCluster)
  880. }