router.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. package costmodel
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "path"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/opencost/opencost/core/pkg/kubeconfig"
  15. "github.com/opencost/opencost/core/pkg/protocol"
  16. "github.com/opencost/opencost/core/pkg/source"
  17. "github.com/opencost/opencost/core/pkg/util/retry"
  18. "github.com/opencost/opencost/core/pkg/util/timeutil"
  19. "github.com/opencost/opencost/core/pkg/version"
  20. "github.com/opencost/opencost/pkg/cloud/aws"
  21. cloudconfig "github.com/opencost/opencost/pkg/cloud/config"
  22. "github.com/opencost/opencost/pkg/cloud/gcp"
  23. "github.com/opencost/opencost/pkg/cloud/provider"
  24. "github.com/opencost/opencost/pkg/cloudcost"
  25. "github.com/opencost/opencost/pkg/config"
  26. "github.com/opencost/opencost/pkg/customcost"
  27. "github.com/opencost/opencost/pkg/metrics"
  28. "github.com/opencost/opencost/pkg/util/watcher"
  29. "github.com/julienschmidt/httprouter"
  30. "github.com/opencost/opencost/core/pkg/clustercache"
  31. "github.com/opencost/opencost/core/pkg/clusters"
  32. sysenv "github.com/opencost/opencost/core/pkg/env"
  33. "github.com/opencost/opencost/core/pkg/log"
  34. "github.com/opencost/opencost/core/pkg/util/json"
  35. "github.com/opencost/opencost/modules/prometheus-source/pkg/prom"
  36. "github.com/opencost/opencost/pkg/cloud/azure"
  37. "github.com/opencost/opencost/pkg/cloud/models"
  38. clusterc "github.com/opencost/opencost/pkg/clustercache"
  39. "github.com/opencost/opencost/pkg/env"
  40. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  41. "github.com/patrickmn/go-cache"
  42. "k8s.io/client-go/kubernetes"
  43. )
  44. const (
  45. RFC3339Milli = "2006-01-02T15:04:05.000Z"
  46. maxCacheMinutes1d = 11
  47. maxCacheMinutes2d = 17
  48. maxCacheMinutes7d = 37
  49. maxCacheMinutes30d = 137
  50. CustomPricingSetting = "CustomPricing"
  51. DiscountSetting = "Discount"
  52. )
  53. var (
  54. // gitCommit is set by the build system
  55. gitCommit string
  56. proto = protocol.HTTP()
  57. )
  58. // Accesses defines a singleton application instance, providing access to
  59. // Prometheus, Kubernetes, the cloud provider, and caches.
  60. type Accesses struct {
  61. DataSource source.OpenCostDataSource
  62. KubeClientSet kubernetes.Interface
  63. ClusterCache clustercache.ClusterCache
  64. ClusterMap clusters.ClusterMap
  65. CloudProvider models.Provider
  66. ConfigFileManager *config.ConfigFileManager
  67. ClusterInfoProvider clusters.ClusterInfoProvider
  68. Model *CostModel
  69. MetricsEmitter *CostModelMetricsEmitter
  70. // SettingsCache stores current state of app settings
  71. SettingsCache *cache.Cache
  72. // settingsSubscribers tracks channels through which changes to different
  73. // settings will be published in a pub/sub model
  74. settingsSubscribers map[string][]chan string
  75. settingsMutex sync.Mutex
  76. }
  77. func filterFields(fields string, data map[string]*CostData) map[string]CostData {
  78. fs := strings.Split(fields, ",")
  79. fmap := make(map[string]bool)
  80. for _, f := range fs {
  81. fieldNameLower := strings.ToLower(f) // convert to go struct name by uppercasing first letter
  82. log.Debugf("to delete: %s", fieldNameLower)
  83. fmap[fieldNameLower] = true
  84. }
  85. filteredData := make(map[string]CostData)
  86. for cname, costdata := range data {
  87. s := reflect.TypeOf(*costdata)
  88. val := reflect.ValueOf(*costdata)
  89. costdata2 := CostData{}
  90. cd2 := reflect.New(reflect.Indirect(reflect.ValueOf(costdata2)).Type()).Elem()
  91. n := s.NumField()
  92. for i := 0; i < n; i++ {
  93. field := s.Field(i)
  94. value := val.Field(i)
  95. value2 := cd2.Field(i)
  96. if _, ok := fmap[strings.ToLower(field.Name)]; !ok {
  97. value2.Set(reflect.Value(value))
  98. }
  99. }
  100. filteredData[cname] = cd2.Interface().(CostData)
  101. }
  102. return filteredData
  103. }
  104. // ParsePercentString takes a string of expected format "N%" and returns a floating point 0.0N.
  105. // If the "%" symbol is missing, it just returns 0.0N. Empty string is interpreted as "0%" and
  106. // return 0.0.
  107. func ParsePercentString(percentStr string) (float64, error) {
  108. if len(percentStr) == 0 {
  109. return 0.0, nil
  110. }
  111. if percentStr[len(percentStr)-1:] == "%" {
  112. percentStr = percentStr[:len(percentStr)-1]
  113. }
  114. discount, err := strconv.ParseFloat(percentStr, 64)
  115. if err != nil {
  116. return 0.0, err
  117. }
  118. discount *= 0.01
  119. return discount, nil
  120. }
  121. func WriteData(w http.ResponseWriter, data interface{}, err error) {
  122. if err != nil {
  123. proto.WriteError(w, proto.InternalServerError(err.Error()))
  124. return
  125. }
  126. proto.WriteData(w, data)
  127. }
  128. // 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.
  129. func (a *Accesses) RefreshPricingData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  130. w.Header().Set("Content-Type", "application/json")
  131. w.Header().Set("Access-Control-Allow-Origin", "*")
  132. err := a.CloudProvider.DownloadPricingData()
  133. if err != nil {
  134. log.Errorf("Error refreshing pricing data: %s", err.Error())
  135. }
  136. WriteData(w, nil, err)
  137. }
  138. func (a *Accesses) CostDataModel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  139. w.Header().Set("Content-Type", "application/json")
  140. w.Header().Set("Access-Control-Allow-Origin", "*")
  141. window := r.URL.Query().Get("timeWindow")
  142. offset := r.URL.Query().Get("offset")
  143. fields := r.URL.Query().Get("filterFields")
  144. namespace := r.URL.Query().Get("namespace")
  145. duration, err := timeutil.ParseDuration(window)
  146. if err != nil {
  147. WriteData(w, nil, fmt.Errorf("error parsing window (%s): %s", window, err))
  148. return
  149. }
  150. end := time.Now()
  151. if offset != "" {
  152. offsetDur, err := timeutil.ParseDuration(offset)
  153. if err != nil {
  154. WriteData(w, nil, fmt.Errorf("error parsing offset (%s): %s", offset, err))
  155. return
  156. }
  157. end = end.Add(-offsetDur)
  158. }
  159. start := end.Add(-duration)
  160. data, err := a.Model.ComputeCostData(start, end)
  161. // apply filter by removing if != namespace
  162. if namespace != "" {
  163. for key, costData := range data {
  164. if costData.Namespace != namespace {
  165. delete(data, key)
  166. }
  167. }
  168. }
  169. if fields != "" {
  170. filteredData := filterFields(fields, data)
  171. WriteData(w, filteredData, err)
  172. } else {
  173. WriteData(w, data, err)
  174. }
  175. }
  176. func (a *Accesses) GetAllNodePricing(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  177. w.Header().Set("Content-Type", "application/json")
  178. w.Header().Set("Access-Control-Allow-Origin", "*")
  179. data, err := a.CloudProvider.AllNodePricing()
  180. WriteData(w, data, err)
  181. }
  182. func (a *Accesses) GetConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  183. w.Header().Set("Content-Type", "application/json")
  184. w.Header().Set("Access-Control-Allow-Origin", "*")
  185. data, err := a.CloudProvider.GetConfig()
  186. WriteData(w, data, err)
  187. }
  188. func (a *Accesses) UpdateSpotInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  189. w.Header().Set("Content-Type", "application/json")
  190. w.Header().Set("Access-Control-Allow-Origin", "*")
  191. data, err := a.CloudProvider.UpdateConfig(r.Body, aws.SpotInfoUpdateType)
  192. WriteData(w, data, err)
  193. err = a.CloudProvider.DownloadPricingData()
  194. if err != nil {
  195. log.Errorf("Error redownloading data on config update: %s", err.Error())
  196. }
  197. }
  198. func (a *Accesses) UpdateAthenaInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  199. w.Header().Set("Content-Type", "application/json")
  200. w.Header().Set("Access-Control-Allow-Origin", "*")
  201. data, err := a.CloudProvider.UpdateConfig(r.Body, aws.AthenaInfoUpdateType)
  202. WriteData(w, data, err)
  203. }
  204. func (a *Accesses) UpdateBigQueryInfoConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  205. w.Header().Set("Content-Type", "application/json")
  206. w.Header().Set("Access-Control-Allow-Origin", "*")
  207. data, err := a.CloudProvider.UpdateConfig(r.Body, gcp.BigqueryUpdateType)
  208. WriteData(w, data, err)
  209. }
  210. func (a *Accesses) UpdateAzureStorageConfigs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  211. w.Header().Set("Content-Type", "application/json")
  212. w.Header().Set("Access-Control-Allow-Origin", "*")
  213. data, err := a.CloudProvider.UpdateConfig(r.Body, azure.AzureStorageUpdateType)
  214. if err != nil {
  215. WriteData(w, nil, err)
  216. return
  217. }
  218. WriteData(w, data, err)
  219. }
  220. func (a *Accesses) UpdateConfigByKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  221. w.Header().Set("Content-Type", "application/json")
  222. w.Header().Set("Access-Control-Allow-Origin", "*")
  223. data, err := a.CloudProvider.UpdateConfig(r.Body, "")
  224. WriteData(w, data, err)
  225. }
  226. func (a *Accesses) ManagementPlatform(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  227. w.Header().Set("Content-Type", "application/json")
  228. w.Header().Set("Access-Control-Allow-Origin", "*")
  229. data, err := a.CloudProvider.GetManagementPlatform()
  230. WriteData(w, data, err)
  231. }
  232. func (a *Accesses) ClusterInfo(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  233. w.Header().Set("Content-Type", "application/json")
  234. w.Header().Set("Access-Control-Allow-Origin", "*")
  235. data := a.ClusterInfoProvider.GetClusterInfo()
  236. WriteData(w, data, nil)
  237. }
  238. func (a *Accesses) GetClusterInfoMap(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  239. w.Header().Set("Content-Type", "application/json")
  240. w.Header().Set("Access-Control-Allow-Origin", "*")
  241. data := a.ClusterMap.AsMap()
  242. WriteData(w, data, nil)
  243. }
  244. func (a *Accesses) GetServiceAccountStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  245. w.Header().Set("Content-Type", "application/json")
  246. w.Header().Set("Access-Control-Allow-Origin", "*")
  247. WriteData(w, a.CloudProvider.ServiceAccountStatus(), nil)
  248. }
  249. func (a *Accesses) GetPricingSourceStatus(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  250. w.Header().Set("Content-Type", "application/json")
  251. w.Header().Set("Access-Control-Allow-Origin", "*")
  252. data := a.CloudProvider.PricingSourceStatus()
  253. WriteData(w, data, nil)
  254. }
  255. func (a *Accesses) GetPricingSourceCounts(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  256. w.Header().Set("Content-Type", "application/json")
  257. w.Header().Set("Access-Control-Allow-Origin", "*")
  258. data, err := a.Model.GetPricingSourceCounts()
  259. WriteData(w, data, err)
  260. }
  261. func (a *Accesses) GetPricingSourceSummary(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
  262. w.Header().Set("Content-Type", "application/json")
  263. w.Header().Set("Access-Control-Allow-Origin", "*")
  264. data := a.CloudProvider.PricingSourceSummary()
  265. WriteData(w, data, nil)
  266. }
  267. func (a *Accesses) GetOrphanedPods(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  268. w.Header().Set("Content-Type", "application/json")
  269. w.Header().Set("Access-Control-Allow-Origin", "*")
  270. podlist := a.ClusterCache.GetAllPods()
  271. var lonePods []*clustercache.Pod
  272. for _, pod := range podlist {
  273. if len(pod.OwnerReferences) == 0 {
  274. lonePods = append(lonePods, pod)
  275. }
  276. }
  277. body, err := json.Marshal(lonePods)
  278. if err != nil {
  279. fmt.Fprintf(w, "Error decoding pod: %s", err)
  280. } else {
  281. w.Write(body)
  282. }
  283. }
  284. func (a *Accesses) GetInstallNamespace(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  285. w.Header().Set("Content-Type", "application/json")
  286. w.Header().Set("Access-Control-Allow-Origin", "*")
  287. ns := env.GetInstallNamespace()
  288. w.Write([]byte(ns))
  289. }
  290. type InstallInfo struct {
  291. Containers []ContainerInfo `json:"containers"`
  292. ClusterInfo map[string]string `json:"clusterInfo"`
  293. Version string `json:"version"`
  294. }
  295. type ContainerInfo struct {
  296. ContainerName string `json:"containerName"`
  297. Image string `json:"image"`
  298. StartTime string `json:"startTime"`
  299. }
  300. func (a *Accesses) GetInstallInfo(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  301. w.Header().Set("Content-Type", "application/json")
  302. w.Header().Set("Access-Control-Allow-Origin", "*")
  303. containers, err := GetKubecostContainers(a.KubeClientSet)
  304. if err != nil {
  305. http.Error(w, fmt.Sprintf("Unable to list pods: %s", err.Error()), http.StatusInternalServerError)
  306. return
  307. }
  308. info := InstallInfo{
  309. Containers: containers,
  310. ClusterInfo: make(map[string]string),
  311. Version: version.FriendlyVersion(),
  312. }
  313. nodes := a.ClusterCache.GetAllNodes()
  314. cachePods := a.ClusterCache.GetAllPods()
  315. info.ClusterInfo["nodeCount"] = strconv.Itoa(len(nodes))
  316. info.ClusterInfo["podCount"] = strconv.Itoa(len(cachePods))
  317. body, err := json.Marshal(info)
  318. if err != nil {
  319. http.Error(w, fmt.Sprintf("Error decoding pod: %s", err.Error()), http.StatusInternalServerError)
  320. return
  321. }
  322. w.Write(body)
  323. }
  324. func GetKubecostContainers(kubeClientSet kubernetes.Interface) ([]ContainerInfo, error) {
  325. pods, err := kubeClientSet.CoreV1().Pods(env.GetInstallNamespace()).List(context.Background(), metav1.ListOptions{
  326. LabelSelector: "app=cost-analyzer",
  327. FieldSelector: "status.phase=Running",
  328. Limit: 1,
  329. })
  330. if err != nil {
  331. return nil, fmt.Errorf("failed to query kubernetes client for kubecost pods: %s", err)
  332. }
  333. // If we have zero pods either something is weird with the install since the app selector is not exposed in the helm
  334. // chart or more likely we are running locally - in either case Images field will return as null
  335. var containers []ContainerInfo
  336. if len(pods.Items) > 0 {
  337. for _, pod := range pods.Items {
  338. for _, container := range pod.Spec.Containers {
  339. c := ContainerInfo{
  340. ContainerName: container.Name,
  341. Image: container.Image,
  342. StartTime: pod.Status.StartTime.String(),
  343. }
  344. containers = append(containers, c)
  345. }
  346. }
  347. }
  348. return containers, nil
  349. }
  350. func (a *Accesses) AddServiceKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  351. w.Header().Set("Content-Type", "application/json")
  352. w.Header().Set("Access-Control-Allow-Origin", "*")
  353. r.ParseForm()
  354. key := r.PostForm.Get("key")
  355. k := []byte(key)
  356. err := os.WriteFile(path.Join(env.GetConfigPathWithDefault(env.DefaultConfigMountPath), "key.json"), k, 0644)
  357. if err != nil {
  358. fmt.Fprintf(w, "Error writing service key: %s", err)
  359. }
  360. w.WriteHeader(http.StatusOK)
  361. }
  362. func (a *Accesses) GetHelmValues(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  363. w.Header().Set("Content-Type", "application/json")
  364. w.Header().Set("Access-Control-Allow-Origin", "*")
  365. encodedValues := sysenv.Get("HELM_VALUES", "")
  366. if encodedValues == "" {
  367. fmt.Fprintf(w, "Values reporting disabled")
  368. return
  369. }
  370. result, err := base64.StdEncoding.DecodeString(encodedValues)
  371. if err != nil {
  372. fmt.Fprintf(w, "Failed to decode encoded values: %s", err)
  373. return
  374. }
  375. w.Write(result)
  376. }
  377. func Initialize(router *httprouter.Router, additionalConfigWatchers ...*watcher.ConfigMapWatcher) *Accesses {
  378. var err error
  379. // Kubernetes API setup
  380. kubeClientset, err := kubeconfig.LoadKubeClient("")
  381. if err != nil {
  382. log.Fatalf("Failed to build Kubernetes client: %s", err.Error())
  383. }
  384. // Create Kubernetes Cluster Cache + Watchers
  385. k8sCache := clusterc.NewKubernetesClusterCache(kubeClientset)
  386. k8sCache.Run()
  387. // Create ConfigFileManager for synchronization of shared configuration
  388. confManager := config.NewConfigFileManager(&config.ConfigFileManagerOpts{
  389. BucketStoreConfig: env.GetConfigBucketFile(),
  390. LocalConfigPath: "/",
  391. })
  392. configPrefix := env.GetConfigPathWithDefault("/var/configs/")
  393. cloudProviderKey := env.GetCloudProviderAPIKey()
  394. cloudProvider, err := provider.NewProvider(k8sCache, cloudProviderKey, confManager)
  395. if err != nil {
  396. panic(err.Error())
  397. }
  398. // ClusterInfo Provider to provide the cluster map with local and remote cluster data
  399. var clusterInfoProvider clusters.ClusterInfoProvider
  400. if env.IsClusterInfoFileEnabled() {
  401. clusterInfoFile := confManager.ConfigFileAt(path.Join(configPrefix, "cluster-info.json"))
  402. clusterInfoProvider = NewConfiguredClusterInfoProvider(clusterInfoFile)
  403. } else {
  404. clusterInfoProvider = NewLocalClusterInfoProvider(kubeClientset, cloudProvider)
  405. }
  406. const maxRetries = 10
  407. const retryInterval = 10 * time.Second
  408. var fatalErr error
  409. ctx, cancel := context.WithCancel(context.Background())
  410. dataSource, _ := retry.Retry(
  411. ctx,
  412. func() (source.OpenCostDataSource, error) {
  413. ds, e := prom.NewDefaultPrometheusDataSource(clusterInfoProvider)
  414. if e != nil {
  415. if source.IsRetryable(e) {
  416. return nil, e
  417. }
  418. fatalErr = e
  419. cancel()
  420. }
  421. return ds, e
  422. },
  423. maxRetries,
  424. retryInterval,
  425. )
  426. if fatalErr != nil {
  427. log.Fatalf("Failed to create Prometheus data source: %s", fatalErr)
  428. panic(fatalErr)
  429. }
  430. // Append the pricing config watcher
  431. kubecostNamespace := env.GetInstallNamespace()
  432. configWatchers := watcher.NewConfigMapWatchers(kubeClientset, kubecostNamespace, additionalConfigWatchers...)
  433. configWatchers.AddWatcher(provider.ConfigWatcherFor(cloudProvider))
  434. configWatchers.AddWatcher(metrics.GetMetricsConfigWatcher())
  435. configWatchers.Watch()
  436. clusterMap := dataSource.ClusterMap()
  437. settingsCache := cache.New(cache.NoExpiration, cache.NoExpiration)
  438. costModel := NewCostModel(dataSource, cloudProvider, k8sCache, clusterMap, dataSource.BatchDuration())
  439. metricsEmitter := NewCostModelMetricsEmitter(k8sCache, cloudProvider, clusterInfoProvider, costModel)
  440. a := &Accesses{
  441. DataSource: dataSource,
  442. KubeClientSet: kubeClientset,
  443. ClusterCache: k8sCache,
  444. ClusterMap: clusterMap,
  445. CloudProvider: cloudProvider,
  446. ConfigFileManager: confManager,
  447. ClusterInfoProvider: clusterInfoProvider,
  448. Model: costModel,
  449. MetricsEmitter: metricsEmitter,
  450. SettingsCache: settingsCache,
  451. }
  452. // Initialize mechanism for subscribing to settings changes
  453. a.InitializeSettingsPubSub()
  454. err = a.CloudProvider.DownloadPricingData()
  455. if err != nil {
  456. log.Infof("Failed to download pricing data: %s", err)
  457. }
  458. if !env.IsKubecostMetricsPodEnabled() {
  459. a.MetricsEmitter.Start()
  460. }
  461. a.DataSource.RegisterEndPoints(router)
  462. router.GET("/costDataModel", a.CostDataModel)
  463. router.GET("/allocation/compute", a.ComputeAllocationHandler)
  464. router.GET("/allocation/compute/summary", a.ComputeAllocationHandlerSummary)
  465. router.GET("/allNodePricing", a.GetAllNodePricing)
  466. router.POST("/refreshPricing", a.RefreshPricingData)
  467. router.GET("/managementPlatform", a.ManagementPlatform)
  468. router.GET("/clusterInfo", a.ClusterInfo)
  469. router.GET("/clusterInfoMap", a.GetClusterInfoMap)
  470. router.GET("/serviceAccountStatus", a.GetServiceAccountStatus)
  471. router.GET("/pricingSourceStatus", a.GetPricingSourceStatus)
  472. router.GET("/pricingSourceSummary", a.GetPricingSourceSummary)
  473. router.GET("/pricingSourceCounts", a.GetPricingSourceCounts)
  474. router.GET("/orphanedPods", a.GetOrphanedPods)
  475. router.GET("/installNamespace", a.GetInstallNamespace)
  476. router.GET("/installInfo", a.GetInstallInfo)
  477. router.POST("/serviceKey", a.AddServiceKey)
  478. router.GET("/helmValues", a.GetHelmValues)
  479. return a
  480. }
  481. // InitializeCloudCost Initializes Cloud Cost pipeline and querier and registers endpoints
  482. func InitializeCloudCost(router *httprouter.Router, providerConfig models.ProviderConfig) {
  483. log.Debugf("Cloud Cost config path: %s", env.GetCloudCostConfigPath())
  484. cloudConfigController := cloudconfig.NewMemoryController(providerConfig)
  485. repo := cloudcost.NewMemoryRepository()
  486. cloudCostPipelineService := cloudcost.NewPipelineService(repo, cloudConfigController, cloudcost.DefaultIngestorConfiguration())
  487. repoQuerier := cloudcost.NewRepositoryQuerier(repo)
  488. cloudCostQueryService := cloudcost.NewQueryService(repoQuerier, repoQuerier)
  489. router.GET("/cloud/config/export", cloudConfigController.GetExportConfigHandler())
  490. router.GET("/cloud/config/enable", cloudConfigController.GetEnableConfigHandler())
  491. router.GET("/cloud/config/disable", cloudConfigController.GetDisableConfigHandler())
  492. router.GET("/cloud/config/delete", cloudConfigController.GetDeleteConfigHandler())
  493. router.GET("/cloudCost", cloudCostQueryService.GetCloudCostHandler())
  494. router.GET("/cloudCost/view/graph", cloudCostQueryService.GetCloudCostViewGraphHandler())
  495. router.GET("/cloudCost/view/totals", cloudCostQueryService.GetCloudCostViewTotalsHandler())
  496. router.GET("/cloudCost/view/table", cloudCostQueryService.GetCloudCostViewTableHandler())
  497. router.GET("/cloudCost/status", cloudCostPipelineService.GetCloudCostStatusHandler())
  498. router.GET("/cloudCost/rebuild", cloudCostPipelineService.GetCloudCostRebuildHandler())
  499. router.GET("/cloudCost/repair", cloudCostPipelineService.GetCloudCostRepairHandler())
  500. }
  501. func InitializeCustomCost(router *httprouter.Router) *customcost.PipelineService {
  502. hourlyRepo := customcost.NewMemoryRepository()
  503. dailyRepo := customcost.NewMemoryRepository()
  504. ingConfig := customcost.DefaultIngestorConfiguration()
  505. var err error
  506. customCostPipelineService, err := customcost.NewPipelineService(hourlyRepo, dailyRepo, ingConfig)
  507. if err != nil {
  508. log.Errorf("error instantiating custom cost pipeline service: %v", err)
  509. return nil
  510. }
  511. customCostQuerier := customcost.NewRepositoryQuerier(hourlyRepo, dailyRepo, ingConfig.HourlyDuration, ingConfig.DailyDuration)
  512. customCostQueryService := customcost.NewQueryService(customCostQuerier)
  513. router.GET("/customCost/total", customCostQueryService.GetCustomCostTotalHandler())
  514. router.GET("/customCost/timeseries", customCostQueryService.GetCustomCostTimeseriesHandler())
  515. return customCostPipelineService
  516. }