router.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "math"
  8. "net"
  9. "net/http"
  10. "os"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "k8s.io/klog"
  16. "github.com/julienschmidt/httprouter"
  17. sentry "github.com/getsentry/sentry-go"
  18. costAnalyzerCloud "github.com/kubecost/cost-model/pkg/cloud"
  19. "github.com/kubecost/cost-model/pkg/clustercache"
  20. cm "github.com/kubecost/cost-model/pkg/clustermanager"
  21. "github.com/kubecost/cost-model/pkg/errors"
  22. prometheusClient "github.com/prometheus/client_golang/api"
  23. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  24. v1 "k8s.io/api/core/v1"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "github.com/patrickmn/go-cache"
  27. "github.com/prometheus/client_golang/prometheus"
  28. "k8s.io/client-go/kubernetes"
  29. "k8s.io/client-go/rest"
  30. )
  31. const (
  32. logCollectionEnvVar = "LOG_COLLECTION_ENABLED"
  33. productAnalyticsEnvVar = "PRODUCT_ANALYTICS_ENABLED"
  34. errorReportingEnvVar = "ERROR_REPORTING_ENABLED"
  35. prometheusServerEndpointEnvVar = "PROMETHEUS_SERVER_ENDPOINT"
  36. prometheusTroubleshootingEp = "http://docs.kubecost.com/custom-prom#troubleshoot"
  37. RFC3339Milli = "2006-01-02T15:04:05.000Z"
  38. )
  39. var (
  40. // gitCommit is set by the build system
  41. gitCommit string
  42. logCollectionEnabled bool = strings.EqualFold(os.Getenv(logCollectionEnvVar), "true")
  43. productAnalyticsEnabled bool = strings.EqualFold(os.Getenv(productAnalyticsEnvVar), "true")
  44. errorReportingEnabled bool = strings.EqualFold(os.Getenv(errorReportingEnvVar), "true")
  45. )
  46. var Router = httprouter.New()
  47. var A Accesses
  48. type Accesses struct {
  49. PrometheusClient prometheusClient.Client
  50. ThanosClient prometheusClient.Client
  51. KubeClientSet kubernetes.Interface
  52. ClusterManager *cm.ClusterManager
  53. Cloud costAnalyzerCloud.Provider
  54. CPUPriceRecorder *prometheus.GaugeVec
  55. RAMPriceRecorder *prometheus.GaugeVec
  56. PersistentVolumePriceRecorder *prometheus.GaugeVec
  57. GPUPriceRecorder *prometheus.GaugeVec
  58. NodeTotalPriceRecorder *prometheus.GaugeVec
  59. RAMAllocationRecorder *prometheus.GaugeVec
  60. CPUAllocationRecorder *prometheus.GaugeVec
  61. GPUAllocationRecorder *prometheus.GaugeVec
  62. PVAllocationRecorder *prometheus.GaugeVec
  63. NetworkZoneEgressRecorder prometheus.Gauge
  64. NetworkRegionEgressRecorder prometheus.Gauge
  65. NetworkInternetEgressRecorder prometheus.Gauge
  66. ServiceSelectorRecorder *prometheus.GaugeVec
  67. DeploymentSelectorRecorder *prometheus.GaugeVec
  68. Model *CostModel
  69. OutOfClusterCache *cache.Cache
  70. }
  71. type DataEnvelope struct {
  72. Code int `json:"code"`
  73. Status string `json:"status"`
  74. Data interface{} `json:"data"`
  75. Message string `json:"message,omitempty"`
  76. }
  77. // 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
  78. type FilterFunc func(*CostData) (bool, string)
  79. // FilterCostData allows through only CostData that matches all the given filter functions
  80. func FilterCostData(data map[string]*CostData, retains []FilterFunc, filters []FilterFunc) (map[string]*CostData, int, map[string]int) {
  81. result := make(map[string]*CostData)
  82. filteredEnvironments := make(map[string]int)
  83. filteredContainers := 0
  84. DataLoop:
  85. for key, datum := range data {
  86. for _, rf := range retains {
  87. if ok, _ := rf(datum); ok {
  88. result[key] = datum
  89. // if any retain function passes, the data is retained and move on
  90. continue DataLoop
  91. }
  92. }
  93. for _, ff := range filters {
  94. if ok, environment := ff(datum); !ok {
  95. if environment != "" {
  96. filteredEnvironments[environment]++
  97. }
  98. filteredContainers++
  99. // if any filter function check fails, move on to the next datum
  100. continue DataLoop
  101. }
  102. }
  103. result[key] = datum
  104. }
  105. return result, filteredContainers, filteredEnvironments
  106. }
  107. func filterFields(fields string, data map[string]*CostData) map[string]CostData {
  108. fs := strings.Split(fields, ",")
  109. fmap := make(map[string]bool)
  110. for _, f := range fs {
  111. fieldNameLower := strings.ToLower(f) // convert to go struct name by uppercasing first letter
  112. klog.V(1).Infof("to delete: %s", fieldNameLower)
  113. fmap[fieldNameLower] = true
  114. }
  115. filteredData := make(map[string]CostData)
  116. for cname, costdata := range data {
  117. s := reflect.TypeOf(*costdata)
  118. val := reflect.ValueOf(*costdata)
  119. costdata2 := CostData{}
  120. cd2 := reflect.New(reflect.Indirect(reflect.ValueOf(costdata2)).Type()).Elem()
  121. n := s.NumField()
  122. for i := 0; i < n; i++ {
  123. field := s.Field(i)
  124. value := val.Field(i)
  125. value2 := cd2.Field(i)
  126. if _, ok := fmap[strings.ToLower(field.Name)]; !ok {
  127. value2.Set(reflect.Value(value))
  128. }
  129. }
  130. filteredData[cname] = cd2.Interface().(CostData)
  131. }
  132. return filteredData
  133. }
  134. func normalizeTimeParam(param string) (string, error) {
  135. // convert days to hours
  136. if param[len(param)-1:] == "d" {
  137. count := param[:len(param)-1]
  138. val, err := strconv.ParseInt(count, 10, 64)
  139. if err != nil {
  140. return "", err
  141. }
  142. val = val * 24
  143. param = fmt.Sprintf("%dh", val)
  144. }
  145. return param, nil
  146. }
  147. // writeReportingFlags writes the reporting flags to the cluster info map
  148. func writeReportingFlags(clusterInfo map[string]string) {
  149. clusterInfo["logCollection"] = fmt.Sprintf("%t", logCollectionEnabled)
  150. clusterInfo["productAnalytics"] = fmt.Sprintf("%t", productAnalyticsEnabled)
  151. clusterInfo["errorReporting"] = fmt.Sprintf("%t", errorReportingEnabled)
  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. data, err := ComputeClusterCosts(a.PrometheusClient, a.Cloud, window, offset, true)
  292. w.Write(WrapData(data, err))
  293. }
  294. func (a *Accesses) ClusterCostsOverTime(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  295. w.Header().Set("Content-Type", "application/json")
  296. w.Header().Set("Access-Control-Allow-Origin", "*")
  297. start := r.URL.Query().Get("start")
  298. end := r.URL.Query().Get("end")
  299. window := r.URL.Query().Get("window")
  300. offset := r.URL.Query().Get("offset")
  301. data, err := ClusterCostsOverTime(a.PrometheusClient, a.Cloud, start, end, window, offset)
  302. w.Write(WrapData(data, err))
  303. }
  304. func (a *Accesses) CostDataModelRange(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  305. w.Header().Set("Content-Type", "application/json")
  306. w.Header().Set("Access-Control-Allow-Origin", "*")
  307. start := r.URL.Query().Get("start")
  308. end := r.URL.Query().Get("end")
  309. window := r.URL.Query().Get("window")
  310. fields := r.URL.Query().Get("filterFields")
  311. namespace := r.URL.Query().Get("namespace")
  312. cluster := r.URL.Query().Get("cluster")
  313. remote := r.URL.Query().Get("remote")
  314. remoteAvailable := os.Getenv(remoteEnabled)
  315. remoteEnabled := false
  316. if remoteAvailable == "true" && remote != "false" {
  317. remoteEnabled = true
  318. }
  319. // Use Thanos Client if it exists (enabled) and remote flag set
  320. var pClient prometheusClient.Client
  321. if remote != "false" && a.ThanosClient != nil {
  322. pClient = a.ThanosClient
  323. } else {
  324. pClient = a.PrometheusClient
  325. }
  326. resolutionHours := 1.0
  327. data, err := a.Model.ComputeCostDataRange(pClient, a.KubeClientSet, a.Cloud, start, end, window, resolutionHours, namespace, cluster, remoteEnabled)
  328. if err != nil {
  329. w.Write(WrapData(nil, err))
  330. }
  331. if fields != "" {
  332. filteredData := filterFields(fields, data)
  333. w.Write(WrapData(filteredData, err))
  334. } else {
  335. w.Write(WrapData(data, err))
  336. }
  337. }
  338. // CostDataModelRangeLarge is experimental multi-cluster and long-term data storage in SQL support.
  339. func (a *Accesses) CostDataModelRangeLarge(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  340. w.Header().Set("Content-Type", "application/json")
  341. w.Header().Set("Access-Control-Allow-Origin", "*")
  342. startString := r.URL.Query().Get("start")
  343. endString := r.URL.Query().Get("end")
  344. windowString := r.URL.Query().Get("window")
  345. var start time.Time
  346. var end time.Time
  347. var err error
  348. if windowString == "" {
  349. windowString = "1h"
  350. }
  351. if startString != "" {
  352. start, err = time.Parse(RFC3339Milli, startString)
  353. if err != nil {
  354. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  355. w.Write(WrapData(nil, err))
  356. }
  357. } else {
  358. window, err := time.ParseDuration(windowString)
  359. if err != nil {
  360. w.Write(WrapData(nil, fmt.Errorf("Invalid duration '%s'", windowString)))
  361. }
  362. start = time.Now().Add(-2 * window)
  363. }
  364. if endString != "" {
  365. end, err = time.Parse(RFC3339Milli, endString)
  366. if err != nil {
  367. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  368. w.Write(WrapData(nil, err))
  369. }
  370. } else {
  371. end = time.Now()
  372. }
  373. remoteLayout := "2006-01-02T15:04:05Z"
  374. remoteStartStr := start.Format(remoteLayout)
  375. remoteEndStr := end.Format(remoteLayout)
  376. klog.V(1).Infof("Using remote database for query from %s to %s with window %s", startString, endString, windowString)
  377. data, err := CostDataRangeFromSQL("", "", windowString, remoteStartStr, remoteEndStr)
  378. w.Write(WrapData(data, err))
  379. }
  380. func parseAggregations(customAggregation, aggregator, filterType string) (string, []string, string) {
  381. var key string
  382. var filter string
  383. var val []string
  384. if customAggregation != "" {
  385. key = customAggregation
  386. filter = filterType
  387. val = strings.Split(customAggregation, ",")
  388. } else {
  389. aggregations := strings.Split(aggregator, ",")
  390. for i, agg := range aggregations {
  391. aggregations[i] = "kubernetes_" + agg
  392. }
  393. key = strings.Join(aggregations, ",")
  394. filter = "kubernetes_" + filterType
  395. val = aggregations
  396. }
  397. return key, val, filter
  398. }
  399. func (a *Accesses) OutofClusterCosts(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  400. w.Header().Set("Content-Type", "application/json")
  401. w.Header().Set("Access-Control-Allow-Origin", "*")
  402. start := r.URL.Query().Get("start")
  403. end := r.URL.Query().Get("end")
  404. aggregator := r.URL.Query().Get("aggregator")
  405. customAggregation := r.URL.Query().Get("customAggregation")
  406. filterType := r.URL.Query().Get("filterType")
  407. filterValue := r.URL.Query().Get("filterValue")
  408. var data []*costAnalyzerCloud.OutOfClusterAllocation
  409. var err error
  410. _, aggregations, filter := parseAggregations(customAggregation, aggregator, filterType)
  411. data, err = a.Cloud.ExternalAllocations(start, end, aggregations, filter, filterValue, false)
  412. w.Write(WrapData(data, err))
  413. }
  414. func (a *Accesses) OutOfClusterCostsWithCache(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  415. w.Header().Set("Content-Type", "application/json")
  416. w.Header().Set("Access-Control-Allow-Origin", "*")
  417. // start date for which to query costs, inclusive; format YYYY-MM-DD
  418. start := r.URL.Query().Get("start")
  419. // end date for which to query costs, inclusive; format YYYY-MM-DD
  420. end := r.URL.Query().Get("end")
  421. // aggregator sets the field by which to aggregate; default, prepended by "kubernetes_"
  422. kubernetesAggregation := r.URL.Query().Get("aggregator")
  423. // customAggregation allows full customization of aggregator w/o prepending
  424. customAggregation := r.URL.Query().Get("customAggregation")
  425. // disableCache, if set to "true", tells this function to recompute and
  426. // cache the requested data
  427. disableCache := r.URL.Query().Get("disableCache") == "true"
  428. // clearCache, if set to "true", tells this function to flush the cache,
  429. // then recompute and cache the requested data
  430. clearCache := r.URL.Query().Get("clearCache") == "true"
  431. filterType := r.URL.Query().Get("filterType")
  432. filterValue := r.URL.Query().Get("filterValue")
  433. aggregationkey, aggregation, filter := parseAggregations(customAggregation, kubernetesAggregation, filterType)
  434. // clear cache prior to checking the cache so that a clearCache=true
  435. // request always returns a freshly computed value
  436. if clearCache {
  437. a.OutOfClusterCache.Flush()
  438. }
  439. // attempt to retrieve cost data from cache
  440. key := fmt.Sprintf(`%s:%s:%s:%s:%s`, start, end, aggregationkey, filter, filterValue)
  441. if value, found := a.OutOfClusterCache.Get(key); found && !disableCache {
  442. if data, ok := value.([]*costAnalyzerCloud.OutOfClusterAllocation); ok {
  443. w.Write(WrapDataWithMessage(data, nil, fmt.Sprintf("out of cluster cache hit: %s", key)))
  444. return
  445. }
  446. klog.Errorf("caching error: failed to type cast data: %s", key)
  447. }
  448. data, err := a.Cloud.ExternalAllocations(start, end, aggregation, filter, filterValue, false)
  449. if err == nil {
  450. a.OutOfClusterCache.Set(key, data, cache.DefaultExpiration)
  451. }
  452. w.Write(WrapDataWithMessage(data, err, fmt.Sprintf("out of cluser cache miss: %s", key)))
  453. }
  454. func (p *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  455. w.Header().Set("Content-Type", "application/json")
  456. w.Header().Set("Access-Control-Allow-Origin", "*")
  457. data, err := p.Cloud.AllNodePricing()
  458. w.Write(WrapData(data, err))
  459. }
  460. func (p *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  461. w.Header().Set("Content-Type", "application/json")
  462. w.Header().Set("Access-Control-Allow-Origin", "*")
  463. data, err := p.Cloud.GetConfig()
  464. w.Write(WrapData(data, err))
  465. }
  466. func (p *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  467. w.Header().Set("Content-Type", "application/json")
  468. w.Header().Set("Access-Control-Allow-Origin", "*")
  469. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.SpotInfoUpdateType)
  470. if err != nil {
  471. w.Write(WrapData(data, err))
  472. return
  473. }
  474. w.Write(WrapData(data, err))
  475. err = p.Cloud.DownloadPricingData()
  476. if err != nil {
  477. klog.V(1).Infof("Error redownloading data on config update: %s", err.Error())
  478. }
  479. return
  480. }
  481. func (p *Accesses) UpdateAthenaInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  482. w.Header().Set("Content-Type", "application/json")
  483. w.Header().Set("Access-Control-Allow-Origin", "*")
  484. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.AthenaInfoUpdateType)
  485. if err != nil {
  486. w.Write(WrapData(data, err))
  487. return
  488. }
  489. w.Write(WrapData(data, err))
  490. return
  491. }
  492. func (p *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  493. w.Header().Set("Content-Type", "application/json")
  494. w.Header().Set("Access-Control-Allow-Origin", "*")
  495. data, err := p.Cloud.UpdateConfig(r.Body, costAnalyzerCloud.BigqueryUpdateType)
  496. if err != nil {
  497. w.Write(WrapData(data, err))
  498. return
  499. }
  500. w.Write(WrapData(data, err))
  501. return
  502. }
  503. func (p *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  504. w.Header().Set("Content-Type", "application/json")
  505. w.Header().Set("Access-Control-Allow-Origin", "*")
  506. data, err := p.Cloud.UpdateConfig(r.Body, "")
  507. if err != nil {
  508. w.Write(WrapData(data, err))
  509. return
  510. }
  511. w.Write(WrapData(data, err))
  512. return
  513. }
  514. func (p *Accesses) ManagementPlatform(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  515. w.Header().Set("Content-Type", "application/json")
  516. w.Header().Set("Access-Control-Allow-Origin", "*")
  517. data, err := p.Cloud.GetManagementPlatform()
  518. if err != nil {
  519. w.Write(WrapData(data, err))
  520. return
  521. }
  522. w.Write(WrapData(data, err))
  523. return
  524. }
  525. func (p *Accesses) ClusterInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  526. w.Header().Set("Content-Type", "application/json")
  527. w.Header().Set("Access-Control-Allow-Origin", "*")
  528. data, err := p.Cloud.ClusterInfo()
  529. kc, ok := p.KubeClientSet.(*kubernetes.Clientset)
  530. if ok && data != nil {
  531. v, err := kc.ServerVersion()
  532. if err != nil {
  533. klog.Infof("Could not get k8s version info: %s", err.Error())
  534. } else if v != nil {
  535. data["version"] = v.Major + "." + v.Minor
  536. }
  537. } else {
  538. klog.Infof("Could not get k8s version info: %s", err.Error())
  539. }
  540. // Include Product Reporting Flags with Cluster Info
  541. writeReportingFlags(data)
  542. w.Write(WrapData(data, err))
  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. func (a *Accesses) recordPrices() {
  550. go func() {
  551. defer errors.HandlePanic()
  552. containerSeen := make(map[string]bool)
  553. nodeSeen := make(map[string]bool)
  554. pvSeen := make(map[string]bool)
  555. pvcSeen := make(map[string]bool)
  556. getKeyFromLabelStrings := func(labels ...string) string {
  557. return strings.Join(labels, ",")
  558. }
  559. getLabelStringsFromKey := func(key string) []string {
  560. return strings.Split(key, ",")
  561. }
  562. var defaultRegion string = ""
  563. nodeList := a.Model.Cache.GetAllNodes()
  564. if len(nodeList) > 0 {
  565. defaultRegion = nodeList[0].Labels[v1.LabelZoneRegion]
  566. }
  567. for {
  568. klog.V(4).Info("Recording prices...")
  569. podlist := a.Model.Cache.GetAllPods()
  570. podStatus := make(map[string]v1.PodPhase)
  571. for _, pod := range podlist {
  572. podStatus[pod.Name] = pod.Status.Phase
  573. }
  574. cfg, _ := a.Cloud.GetConfig()
  575. // Record network pricing at global scope
  576. networkCosts, err := a.Cloud.NetworkPricing()
  577. if err != nil {
  578. klog.V(4).Infof("Failed to retrieve network costs: %s", err.Error())
  579. } else {
  580. a.NetworkZoneEgressRecorder.Set(networkCosts.ZoneNetworkEgressCost)
  581. a.NetworkRegionEgressRecorder.Set(networkCosts.RegionNetworkEgressCost)
  582. a.NetworkInternetEgressRecorder.Set(networkCosts.InternetNetworkEgressCost)
  583. }
  584. data, err := a.Model.ComputeCostData(a.PrometheusClient, a.KubeClientSet, a.Cloud, "2m", "", "")
  585. if err != nil {
  586. klog.V(1).Info("Error in price recording: " + err.Error())
  587. // zero the for loop so the time.Sleep will still work
  588. data = map[string]*CostData{}
  589. }
  590. nodes, err := a.Model.GetNodeCost(a.Cloud)
  591. for nodeName, node := range nodes {
  592. // Emit costs, guarding against NaN inputs for custom pricing.
  593. cpuCost, _ := strconv.ParseFloat(node.VCPUCost, 64)
  594. if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  595. cpuCost, _ = strconv.ParseFloat(cfg.CPU, 64)
  596. if math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  597. cpuCost = 0
  598. }
  599. }
  600. cpu, _ := strconv.ParseFloat(node.VCPU, 64)
  601. if math.IsNaN(cpu) || math.IsInf(cpu, 0) {
  602. cpu = 1 // Assume 1 CPU
  603. }
  604. ramCost, _ := strconv.ParseFloat(node.RAMCost, 64)
  605. if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  606. ramCost, _ = strconv.ParseFloat(cfg.RAM, 64)
  607. if math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  608. ramCost = 0
  609. }
  610. }
  611. ram, _ := strconv.ParseFloat(node.RAMBytes, 64)
  612. if math.IsNaN(ram) || math.IsInf(ram, 0) {
  613. ram = 0
  614. }
  615. gpu, _ := strconv.ParseFloat(node.GPU, 64)
  616. if math.IsNaN(gpu) || math.IsInf(gpu, 0) {
  617. gpu = 0
  618. }
  619. gpuCost, _ := strconv.ParseFloat(node.GPUCost, 64)
  620. if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  621. gpuCost, _ = strconv.ParseFloat(cfg.GPU, 64)
  622. if math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  623. gpuCost = 0
  624. }
  625. }
  626. nodeType := node.InstanceType
  627. nodeRegion := node.Region
  628. totalCost := cpu*cpuCost + ramCost*(ram/1024/1024/1024) + gpu*gpuCost
  629. a.CPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(cpuCost)
  630. a.RAMPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(ramCost)
  631. a.GPUPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(gpuCost)
  632. a.NodeTotalPriceRecorder.WithLabelValues(nodeName, nodeName, nodeType, nodeRegion).Set(totalCost)
  633. labelKey := getKeyFromLabelStrings(nodeName, nodeName)
  634. nodeSeen[labelKey] = true
  635. }
  636. for _, costs := range data {
  637. nodeName := costs.NodeName
  638. namespace := costs.Namespace
  639. podName := costs.PodName
  640. containerName := costs.Name
  641. if costs.PVCData != nil {
  642. for _, pvc := range costs.PVCData {
  643. if pvc.Volume != nil {
  644. a.PVAllocationRecorder.WithLabelValues(namespace, podName, pvc.Claim, pvc.VolumeName).Set(pvc.Values[0].Value)
  645. labelKey := getKeyFromLabelStrings(namespace, podName, pvc.Claim, pvc.VolumeName)
  646. pvcSeen[labelKey] = true
  647. }
  648. }
  649. }
  650. if len(costs.RAMAllocation) > 0 {
  651. a.RAMAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.RAMAllocation[0].Value)
  652. }
  653. if len(costs.CPUAllocation) > 0 {
  654. a.CPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.CPUAllocation[0].Value)
  655. }
  656. if len(costs.GPUReq) > 0 {
  657. // allocation here is set to the request because shared GPU usage not yet supported.
  658. a.GPUAllocationRecorder.WithLabelValues(namespace, podName, containerName, nodeName, nodeName).Set(costs.GPUReq[0].Value)
  659. }
  660. labelKey := getKeyFromLabelStrings(namespace, podName, containerName, nodeName, nodeName)
  661. if podStatus[podName] == v1.PodRunning { // Only report data for current pods
  662. containerSeen[labelKey] = true
  663. } else {
  664. containerSeen[labelKey] = false
  665. }
  666. storageClasses := a.Model.Cache.GetAllStorageClasses()
  667. storageClassMap := make(map[string]map[string]string)
  668. for _, storageClass := range storageClasses {
  669. params := storageClass.Parameters
  670. storageClassMap[storageClass.ObjectMeta.Name] = params
  671. if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
  672. storageClassMap["default"] = params
  673. storageClassMap[""] = params
  674. }
  675. }
  676. pvs := a.Model.Cache.GetAllPersistentVolumes()
  677. for _, pv := range pvs {
  678. parameters, ok := storageClassMap[pv.Spec.StorageClassName]
  679. if !ok {
  680. klog.V(4).Infof("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
  681. }
  682. var region string
  683. if r, ok := pv.Labels[v1.LabelZoneRegion]; ok {
  684. region = r
  685. } else {
  686. region = defaultRegion
  687. }
  688. cacPv := &costAnalyzerCloud.PV{
  689. Class: pv.Spec.StorageClassName,
  690. Region: region,
  691. Parameters: parameters,
  692. }
  693. GetPVCost(cacPv, pv, a.Cloud, region)
  694. c, _ := strconv.ParseFloat(cacPv.Cost, 64)
  695. a.PersistentVolumePriceRecorder.WithLabelValues(pv.Name, pv.Name).Set(c)
  696. labelKey := getKeyFromLabelStrings(pv.Name, pv.Name)
  697. pvSeen[labelKey] = true
  698. }
  699. }
  700. for labelString, seen := range nodeSeen {
  701. if !seen {
  702. labels := getLabelStringsFromKey(labelString)
  703. a.NodeTotalPriceRecorder.DeleteLabelValues(labels...)
  704. a.CPUPriceRecorder.DeleteLabelValues(labels...)
  705. a.GPUPriceRecorder.DeleteLabelValues(labels...)
  706. a.RAMPriceRecorder.DeleteLabelValues(labels...)
  707. delete(nodeSeen, labelString)
  708. }
  709. nodeSeen[labelString] = false
  710. }
  711. for labelString, seen := range containerSeen {
  712. if !seen {
  713. labels := getLabelStringsFromKey(labelString)
  714. a.RAMAllocationRecorder.DeleteLabelValues(labels...)
  715. a.CPUAllocationRecorder.DeleteLabelValues(labels...)
  716. a.GPUAllocationRecorder.DeleteLabelValues(labels...)
  717. delete(containerSeen, labelString)
  718. }
  719. containerSeen[labelString] = false
  720. }
  721. for labelString, seen := range pvSeen {
  722. if !seen {
  723. labels := getLabelStringsFromKey(labelString)
  724. a.PersistentVolumePriceRecorder.DeleteLabelValues(labels...)
  725. delete(pvSeen, labelString)
  726. }
  727. pvSeen[labelString] = false
  728. }
  729. for labelString, seen := range pvcSeen {
  730. if !seen {
  731. labels := getLabelStringsFromKey(labelString)
  732. a.PVAllocationRecorder.DeleteLabelValues(labels...)
  733. delete(pvcSeen, labelString)
  734. }
  735. pvcSeen[labelString] = false
  736. }
  737. time.Sleep(time.Minute)
  738. }
  739. }()
  740. }
  741. // Creates a new ClusterManager instance using a boltdb storage. If that fails,
  742. // then we fall back to a memory-only storage.
  743. func newClusterManager() *cm.ClusterManager {
  744. clustersConfigFile := "/var/configs/clusters/default-clusters.yaml"
  745. // Return a memory-backed cluster manager populated by configmap
  746. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  747. // NOTE: The following should be used with a persistent disk store. Since the
  748. // NOTE: configmap approach is currently the "persistent" source (entries are read-only
  749. // NOTE: on the backend), we don't currently need to store on disk.
  750. /*
  751. path := os.Getenv("CONFIG_PATH")
  752. db, err := bolt.Open(path+"costmodel.db", 0600, nil)
  753. if err != nil {
  754. klog.V(1).Infof("[Error] Failed to create costmodel.db: %s", err.Error())
  755. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  756. }
  757. store, err := cm.NewBoltDBClusterStorage("clusters", db)
  758. if err != nil {
  759. klog.V(1).Infof("[Error] Failed to Create Cluster Storage: %s", err.Error())
  760. return cm.NewConfiguredClusterManager(cm.NewMapDBClusterStorage(), clustersConfigFile)
  761. }
  762. return cm.NewConfiguredClusterManager(store, clustersConfigFile)
  763. */
  764. }
  765. type ConfigWatchers struct {
  766. ConfigmapName string
  767. WatchFunc func(string, map[string]string) error
  768. }
  769. // handle any panics reported by the errors package
  770. func handlePanic(p errors.Panic) bool {
  771. err := p.Error
  772. if err != nil {
  773. if err, ok := err.(error); ok {
  774. sentry.CurrentHub().CaptureException(err)
  775. sentry.Flush(5 * time.Second)
  776. }
  777. if err, ok := err.(string); ok {
  778. msg := fmt.Sprintf("Panic: %s\nStackTrace: %s\n", err, p.Stack)
  779. sentry.CurrentHub().CaptureEvent(&sentry.Event{
  780. Level: sentry.LevelError,
  781. Message: msg,
  782. })
  783. sentry.Flush(5 * time.Second)
  784. }
  785. }
  786. // Return true to recover iff the type is http, otherwise allow kubernetes
  787. // to recover.
  788. return p.Type == errors.PanicTypeHTTP
  789. }
  790. func Initialize(additionalConfigWatchers ...ConfigWatchers) {
  791. klog.InitFlags(nil)
  792. flag.Set("v", "3")
  793. flag.Parse()
  794. klog.V(1).Infof("Starting cost-model (git commit \"%s\")", gitCommit)
  795. var err error
  796. if errorReportingEnabled {
  797. err = sentry.Init(sentry.ClientOptions{Release: gitCommit})
  798. if err != nil {
  799. klog.Infof("Failed to initialize sentry for error reporting")
  800. } else {
  801. err = errors.SetPanicHandler(handlePanic)
  802. if err != nil {
  803. klog.Infof("Failed to set panic handler: %s", err)
  804. }
  805. }
  806. }
  807. address := os.Getenv(prometheusServerEndpointEnvVar)
  808. if address == "" {
  809. klog.Fatalf("No address for prometheus set in $%s. Aborting.", prometheusServerEndpointEnvVar)
  810. }
  811. var LongTimeoutRoundTripper http.RoundTripper = &http.Transport{ // may be necessary for long prometheus queries. TODO: make this configurable
  812. Proxy: http.ProxyFromEnvironment,
  813. DialContext: (&net.Dialer{
  814. Timeout: 120 * time.Second,
  815. KeepAlive: 120 * time.Second,
  816. }).DialContext,
  817. TLSHandshakeTimeout: 10 * time.Second,
  818. }
  819. pc := prometheusClient.Config{
  820. Address: address,
  821. RoundTripper: LongTimeoutRoundTripper,
  822. }
  823. promCli, _ := prometheusClient.NewClient(pc)
  824. api := prometheusAPI.NewAPI(promCli)
  825. _, err = api.Config(context.Background())
  826. if err != nil {
  827. klog.Fatalf("No valid prometheus config file at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  828. }
  829. klog.V(1).Info("Success: retrieved a prometheus config file from: " + address)
  830. _, err = ValidatePrometheus(promCli, false)
  831. if err != nil {
  832. klog.Fatalf("Failed to query prometheus at %s. Error: %s . Troubleshooting help available at: %s", address, err.Error(), prometheusTroubleshootingEp)
  833. }
  834. klog.V(1).Info("Success: retrieved the 'up' query against prometheus at: " + address)
  835. // Kubernetes API setup
  836. kc, err := rest.InClusterConfig()
  837. if err != nil {
  838. panic(err.Error())
  839. }
  840. kubeClientset, err := kubernetes.NewForConfig(kc)
  841. if err != nil {
  842. panic(err.Error())
  843. }
  844. // Create Kubernetes Cluster Cache + Watchers
  845. k8sCache := clustercache.NewKubernetesClusterCache(kubeClientset)
  846. k8sCache.Run()
  847. cloudProviderKey := os.Getenv("CLOUD_PROVIDER_API_KEY")
  848. cloudProvider, err := costAnalyzerCloud.NewProvider(k8sCache, cloudProviderKey)
  849. if err != nil {
  850. panic(err.Error())
  851. }
  852. watchConfigFunc := func(c interface{}) {
  853. conf := c.(*v1.ConfigMap)
  854. if conf.GetName() == "pricing-configs" {
  855. _, err := cloudProvider.UpdateConfigFromConfigMap(conf.Data)
  856. if err != nil {
  857. klog.Infof("ERROR UPDATING %s CONFIG: %s", "pricing-configs", err.Error())
  858. }
  859. }
  860. for _, cw := range additionalConfigWatchers {
  861. if conf.GetName() == cw.ConfigmapName {
  862. err := cw.WatchFunc(conf.GetName(), conf.Data)
  863. if err != nil {
  864. klog.Infof("ERROR UPDATING %s CONFIG: %s", cw.ConfigmapName, err.Error())
  865. }
  866. }
  867. }
  868. }
  869. kubecostNamespace := os.Getenv("KUBECOST_NAMESPACE")
  870. // We need an initial invocation because the init of the cache has happened before we had access to the provider.
  871. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get("pricing-configs", metav1.GetOptions{})
  872. if err != nil {
  873. klog.Infof("No %s configmap found at installtime, using existing configs: %s", "pricing-configs", err.Error())
  874. } else {
  875. watchConfigFunc(configs)
  876. }
  877. for _, cw := range additionalConfigWatchers {
  878. configs, err := kubeClientset.CoreV1().ConfigMaps(kubecostNamespace).Get(cw.ConfigmapName, metav1.GetOptions{})
  879. if err != nil {
  880. klog.Infof("No %s configmap found at installtime, using existing configs: %s", cw.ConfigmapName, err.Error())
  881. } else {
  882. watchConfigFunc(configs)
  883. }
  884. }
  885. k8sCache.SetConfigMapUpdateFunc(watchConfigFunc)
  886. // TODO: General Architecture Note: Several passes have been made to modularize a lot of
  887. // TODO: our code, but the router still continues to be the obvious entry point for new \
  888. // TODO: features. We should look to spliting out the actual "router" functionality and
  889. // TODO: implement a builder -> controller for stitching new features and other dependencies.
  890. clusterManager := newClusterManager()
  891. cpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  892. Name: "node_cpu_hourly_cost",
  893. Help: "node_cpu_hourly_cost hourly cost for each cpu on this node",
  894. }, []string{"instance", "node", "instance_type", "region"})
  895. ramGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  896. Name: "node_ram_hourly_cost",
  897. Help: "node_ram_hourly_cost hourly cost for each gb of ram on this node",
  898. }, []string{"instance", "node", "instance_type", "region"})
  899. gpuGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  900. Name: "node_gpu_hourly_cost",
  901. Help: "node_gpu_hourly_cost hourly cost for each gpu on this node",
  902. }, []string{"instance", "node", "instance_type", "region"})
  903. totalGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  904. Name: "node_total_hourly_cost",
  905. Help: "node_total_hourly_cost Total node cost per hour",
  906. }, []string{"instance", "node", "instance_type", "region"})
  907. pvGv := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  908. Name: "pv_hourly_cost",
  909. Help: "pv_hourly_cost Cost per GB per hour on a persistent disk",
  910. }, []string{"volumename", "persistentvolume"})
  911. RAMAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  912. Name: "container_memory_allocation_bytes",
  913. Help: "container_memory_allocation_bytes Bytes of RAM used",
  914. }, []string{"namespace", "pod", "container", "instance", "node"})
  915. CPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  916. Name: "container_cpu_allocation",
  917. Help: "container_cpu_allocation Percent of a single CPU used in a minute",
  918. }, []string{"namespace", "pod", "container", "instance", "node"})
  919. GPUAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  920. Name: "container_gpu_allocation",
  921. Help: "container_gpu_allocation GPU used",
  922. }, []string{"namespace", "pod", "container", "instance", "node"})
  923. PVAllocation := prometheus.NewGaugeVec(prometheus.GaugeOpts{
  924. Name: "pod_pvc_allocation",
  925. Help: "pod_pvc_allocation Bytes used by a PVC attached to a pod",
  926. }, []string{"namespace", "pod", "persistentvolumeclaim", "persistentvolume"})
  927. NetworkZoneEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  928. Name: "kubecost_network_zone_egress_cost",
  929. Help: "kubecost_network_zone_egress_cost Total cost per GB egress across zones",
  930. })
  931. NetworkRegionEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  932. Name: "kubecost_network_region_egress_cost",
  933. Help: "kubecost_network_region_egress_cost Total cost per GB egress across regions",
  934. })
  935. NetworkInternetEgressRecorder := prometheus.NewGauge(prometheus.GaugeOpts{
  936. Name: "kubecost_network_internet_egress_cost",
  937. Help: "kubecost_network_internet_egress_cost Total cost per GB of internet egress.",
  938. })
  939. prometheus.MustRegister(cpuGv)
  940. prometheus.MustRegister(ramGv)
  941. prometheus.MustRegister(gpuGv)
  942. prometheus.MustRegister(totalGv)
  943. prometheus.MustRegister(pvGv)
  944. prometheus.MustRegister(RAMAllocation)
  945. prometheus.MustRegister(CPUAllocation)
  946. prometheus.MustRegister(PVAllocation)
  947. prometheus.MustRegister(GPUAllocation)
  948. prometheus.MustRegister(NetworkZoneEgressRecorder, NetworkRegionEgressRecorder, NetworkInternetEgressRecorder)
  949. prometheus.MustRegister(ServiceCollector{
  950. KubeClientSet: kubeClientset,
  951. })
  952. prometheus.MustRegister(DeploymentCollector{
  953. KubeClientSet: kubeClientset,
  954. })
  955. prometheus.MustRegister(StatefulsetCollector{
  956. KubeClientSet: kubeClientset,
  957. })
  958. // cache responses from model for a default of 5 minutes; clear expired responses every 10 minutes
  959. outOfClusterCache := cache.New(time.Minute*5, time.Minute*10)
  960. A = Accesses{
  961. PrometheusClient: promCli,
  962. KubeClientSet: kubeClientset,
  963. ClusterManager: clusterManager,
  964. Cloud: cloudProvider,
  965. CPUPriceRecorder: cpuGv,
  966. RAMPriceRecorder: ramGv,
  967. GPUPriceRecorder: gpuGv,
  968. NodeTotalPriceRecorder: totalGv,
  969. RAMAllocationRecorder: RAMAllocation,
  970. CPUAllocationRecorder: CPUAllocation,
  971. GPUAllocationRecorder: GPUAllocation,
  972. PVAllocationRecorder: PVAllocation,
  973. NetworkZoneEgressRecorder: NetworkZoneEgressRecorder,
  974. NetworkRegionEgressRecorder: NetworkRegionEgressRecorder,
  975. NetworkInternetEgressRecorder: NetworkInternetEgressRecorder,
  976. PersistentVolumePriceRecorder: pvGv,
  977. Model: NewCostModel(k8sCache),
  978. OutOfClusterCache: outOfClusterCache,
  979. }
  980. remoteEnabled := os.Getenv(remoteEnabled)
  981. if remoteEnabled == "true" {
  982. info, err := cloudProvider.ClusterInfo()
  983. klog.Infof("Saving cluster with id:'%s', and name:'%s' to durable storage", info["id"], info["name"])
  984. if err != nil {
  985. klog.Infof("Error saving cluster id %s", err.Error())
  986. }
  987. _, _, err = costAnalyzerCloud.GetOrCreateClusterMeta(info["id"], info["name"])
  988. if err != nil {
  989. klog.Infof("Unable to set cluster id '%s' for cluster '%s', %s", info["id"], info["name"], err.Error())
  990. }
  991. }
  992. // Thanos Client
  993. if os.Getenv(thanosEnabled) == "true" {
  994. thanosUrl := os.Getenv(thanosQueryUrl)
  995. if thanosUrl != "" {
  996. var thanosRT http.RoundTripper = &http.Transport{
  997. Proxy: http.ProxyFromEnvironment,
  998. DialContext: (&net.Dialer{
  999. Timeout: 120 * time.Second,
  1000. KeepAlive: 120 * time.Second,
  1001. }).DialContext,
  1002. TLSHandshakeTimeout: 10 * time.Second,
  1003. }
  1004. thanosConfig := prometheusClient.Config{
  1005. Address: thanosUrl,
  1006. RoundTripper: thanosRT,
  1007. }
  1008. thanosCli, _ := prometheusClient.NewClient(thanosConfig)
  1009. _, err = ValidatePrometheus(thanosCli, true)
  1010. if err != nil {
  1011. klog.V(1).Infof("[Warning] Failed to query Thanos at %s. Error: %s.", thanosUrl, err.Error())
  1012. A.ThanosClient = thanosCli
  1013. } else {
  1014. klog.V(1).Info("Success: retrieved the 'up' query against Thanos at: " + thanosUrl)
  1015. A.ThanosClient = thanosCli
  1016. }
  1017. } else {
  1018. klog.Infof("Error resolving environment variable: $%s", thanosQueryUrl)
  1019. }
  1020. }
  1021. err = A.Cloud.DownloadPricingData()
  1022. if err != nil {
  1023. klog.V(1).Info("Failed to download pricing data: " + err.Error())
  1024. }
  1025. A.recordPrices()
  1026. managerEndpoints := cm.NewClusterManagerEndpoints(A.ClusterManager)
  1027. Router.GET("/costDataModel", A.CostDataModel)
  1028. Router.GET("/costDataModelRange", A.CostDataModelRange)
  1029. Router.GET("/costDataModelRangeLarge", A.CostDataModelRangeLarge)
  1030. Router.GET("/outOfClusterCosts", A.OutOfClusterCostsWithCache)
  1031. Router.GET("/allNodePricing", A.GetAllNodePricing)
  1032. Router.POST("/refreshPricing", A.RefreshPricingData)
  1033. Router.GET("/clusterCostsOverTime", A.ClusterCostsOverTime)
  1034. Router.GET("/clusterCosts", A.ClusterCosts)
  1035. Router.GET("/validatePrometheus", A.GetPrometheusMetadata)
  1036. Router.GET("/managementPlatform", A.ManagementPlatform)
  1037. Router.GET("/clusterInfo", A.ClusterInfo)
  1038. Router.GET("/clusters", managerEndpoints.GetAllClusters)
  1039. Router.PUT("/clusters", managerEndpoints.PutCluster)
  1040. Router.DELETE("/clusters/:id", managerEndpoints.DeleteCluster)
  1041. }