controller.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package config
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "sync"
  7. "time"
  8. "github.com/opencost/opencost/core/pkg/log"
  9. "github.com/opencost/opencost/core/pkg/util/json"
  10. "github.com/opencost/opencost/core/pkg/util/timeutil"
  11. "github.com/opencost/opencost/pkg/cloud"
  12. "github.com/opencost/opencost/pkg/cloud/models"
  13. "github.com/opencost/opencost/pkg/cloud/provider"
  14. "github.com/opencost/opencost/pkg/env"
  15. )
  16. const configFile = "cloud-configurations.json"
  17. // Controller manages the cloud.Config using config Watcher(s) to track various configuration
  18. // methods. To do this it has a map of config watchers mapped on configuration source and a list Observers that it updates
  19. // upon any change detected from the config watchers.
  20. type Controller struct {
  21. path string
  22. lock sync.RWMutex
  23. observers []Observer
  24. watchers map[ConfigSource]cloud.KeyedConfigWatcher
  25. }
  26. // NewController initializes an Config Controller
  27. func NewController(cp models.Provider) *Controller {
  28. var watchers map[ConfigSource]cloud.KeyedConfigWatcher
  29. if env.IsKubernetesEnabled() && cp != nil {
  30. providerConfig := provider.ExtractConfigFromProviders(cp)
  31. watchers = GetCloudBillingWatchers(providerConfig)
  32. } else {
  33. watchers = GetCloudBillingWatchers(nil)
  34. }
  35. ic := &Controller{
  36. path: filepath.Join(env.GetConfigPathWithDefault(env.DefaultConfigMountPath), configFile),
  37. watchers: watchers,
  38. }
  39. ic.pullWatchers()
  40. go func() {
  41. ticker := timeutil.NewJobTicker()
  42. defer ticker.Close()
  43. for {
  44. ticker.TickIn(10 * time.Second)
  45. <-ticker.Ch
  46. ic.pullWatchers()
  47. }
  48. }()
  49. return ic
  50. }
  51. // pullWatchers retrieve configs from watchers and update configs according to priority of sources
  52. func (c *Controller) pullWatchers() {
  53. c.lock.Lock()
  54. defer c.lock.Unlock()
  55. statuses, err := c.load()
  56. if err != nil {
  57. log.Warnf("Controller: pullWatchers: %s. Proceeding to create the file", err.Error())
  58. statuses = Statuses{}
  59. err = c.save(statuses)
  60. if err != nil {
  61. log.Errorf("Controller: pullWatchers: failed to save statuses %s", err.Error())
  62. }
  63. }
  64. for source, watcher := range c.watchers {
  65. watcherConfsByKey := map[string]cloud.KeyedConfig{}
  66. for _, wConf := range watcher.GetConfigs() {
  67. watcherConfsByKey[wConf.Key()] = wConf
  68. }
  69. // remove existing configs that are no longer present in the source
  70. for _, status := range statuses.List() {
  71. if status.Source == source {
  72. if _, ok := watcherConfsByKey[status.Key]; !ok {
  73. err := c.deleteConfig(status.Key, status.Source, statuses)
  74. if err != nil {
  75. log.Errorf("Controller: pullWatchers: %s", err.Error())
  76. }
  77. }
  78. }
  79. }
  80. for key, conf := range watcherConfsByKey {
  81. // Check existing configs for matching key and source
  82. if existingStatus, ok := statuses.Get(key, source); ok {
  83. // if config has not changed continue
  84. if existingStatus.Config.Equals(conf) {
  85. continue
  86. }
  87. // remove the existing config
  88. err := c.deleteConfig(key, source, statuses)
  89. if err != nil {
  90. log.Errorf("Controller: pullWatchers: %s", err.Error())
  91. }
  92. }
  93. err := conf.Validate()
  94. valid := err == nil
  95. configType, err := ConfigTypeFromConfig(conf)
  96. if err != nil {
  97. log.Errorf("Controller: pullWatchers: failed to get config type for config with key: %s", conf.Key())
  98. continue
  99. }
  100. status := Status{
  101. Key: key,
  102. Source: source,
  103. Active: valid, // if valid, then new config will be active
  104. Valid: valid,
  105. ConfigType: configType,
  106. Config: conf,
  107. }
  108. // handle a config with a new unique key for a source or an update config from a source which was inactive before
  109. if valid {
  110. for _, matchStat := range statuses.List() {
  111. //// skip matching configs
  112. //if matchID.Equals(cID) {
  113. // continue
  114. //}
  115. if matchStat.Active {
  116. // if source is non-multi-cloud disable all other non-multi-cloud sourced configs
  117. if source == HelmSource || source == ConfigFileSource {
  118. if matchStat.Source == HelmSource || matchStat.Source == ConfigFileSource {
  119. matchStat.Active = false
  120. c.broadcastRemoveConfig(matchStat.Key)
  121. }
  122. }
  123. // check for configs with the same key that are active
  124. if matchStat.Key == key {
  125. // If source has higher priority disable other active configs
  126. matchStat.Active = false
  127. c.broadcastRemoveConfig(matchStat.Key)
  128. }
  129. }
  130. }
  131. }
  132. // update config and put to observers if active
  133. statuses.Insert(&status)
  134. if status.Active {
  135. c.broadcastAddConfig(conf)
  136. }
  137. err = c.save(statuses)
  138. if err != nil {
  139. log.Errorf("Controller: pullWatchers: failed to save statuses %s", err.Error())
  140. }
  141. }
  142. }
  143. }
  144. // CreateConfig adds a new config to status with a source of ConfigControllerSource
  145. // It will disable any config with the same key
  146. // fails if there is an existing config with the same key and source
  147. func (c *Controller) CreateConfig(conf cloud.KeyedConfig) error {
  148. c.lock.Lock()
  149. defer c.lock.Unlock()
  150. err := conf.Validate()
  151. if err != nil {
  152. return fmt.Errorf("provided configuration was invalid: %w", err)
  153. }
  154. statuses, err := c.load()
  155. if err != nil {
  156. return fmt.Errorf("failed to load statuses")
  157. }
  158. source := ConfigControllerSource
  159. key := conf.Key()
  160. _, ok := statuses.Get(key, source)
  161. if ok {
  162. return fmt.Errorf("config with key %s from source %s already exist", key, source.String())
  163. }
  164. configType, err := ConfigTypeFromConfig(conf)
  165. if err != nil {
  166. return fmt.Errorf("config did not have recoginzed config: %w", err)
  167. }
  168. statuses.Insert(&Status{
  169. Key: key,
  170. Source: source,
  171. Valid: true,
  172. Active: true,
  173. ConfigType: configType,
  174. Config: conf,
  175. })
  176. // check for configurations with the same configuration key that are already active.
  177. for _, confStat := range statuses.List() {
  178. if confStat.Key != key || confStat.Source == source {
  179. continue
  180. }
  181. // if active disable
  182. if confStat.Active == true {
  183. confStat.Active = false
  184. c.broadcastRemoveConfig(key)
  185. }
  186. }
  187. c.broadcastAddConfig(conf)
  188. err = c.save(statuses)
  189. if err != nil {
  190. return fmt.Errorf("failed to save statues: %w", err)
  191. }
  192. return nil
  193. }
  194. // EnableConfig enables a config with the given key and source, and disables any config with a matching key
  195. func (c *Controller) EnableConfig(key, sourceStr string) error {
  196. c.lock.Lock()
  197. defer c.lock.Unlock()
  198. statuses, err := c.load()
  199. if err != nil {
  200. return fmt.Errorf("failed to load statuses")
  201. }
  202. source := GetConfigSource(sourceStr)
  203. cs, ok := statuses.Get(key, source)
  204. if !ok {
  205. return fmt.Errorf("config with key %s from source %s does not exist", key, sourceStr)
  206. }
  207. if cs.Active {
  208. return fmt.Errorf("config with key %s from source %s is already active", key, sourceStr)
  209. }
  210. // check for configurations with the same configuration key that are already active.
  211. for _, confStat := range statuses.List() {
  212. if confStat.Key != key || confStat.Source == source {
  213. continue
  214. }
  215. // if active disable
  216. if confStat.Active == true {
  217. confStat.Active = false
  218. c.broadcastRemoveConfig(key)
  219. }
  220. }
  221. cs.Active = true
  222. c.broadcastAddConfig(cs.Config)
  223. c.save(statuses)
  224. return nil
  225. }
  226. // DisableConfig updates an config status if it was enabled
  227. func (c *Controller) DisableConfig(key, sourceStr string) error {
  228. c.lock.Lock()
  229. defer c.lock.Unlock()
  230. statuses, err := c.load()
  231. if err != nil {
  232. return fmt.Errorf("failed to load statuses")
  233. }
  234. source := GetConfigSource(sourceStr)
  235. is, ok := statuses.Get(key, source)
  236. if !ok {
  237. return fmt.Errorf("Controller: DisableConfig: config with key %s from source %s does not exist", key, source)
  238. }
  239. if !is.Active {
  240. return fmt.Errorf("Controller: DisableConfig: config with key %s from source %s is already disabled", key, source)
  241. }
  242. is.Active = false
  243. c.broadcastRemoveConfig(key)
  244. c.save(statuses)
  245. return nil
  246. }
  247. // DeleteConfig removes a config from the statuses and deletes the config on all observers if it was active
  248. // This can only be used on configs with ConfigControllerSource
  249. func (c *Controller) DeleteConfig(key, sourceStr string) error {
  250. c.lock.Lock()
  251. defer c.lock.Unlock()
  252. source := GetConfigSource(sourceStr)
  253. if source != ConfigControllerSource {
  254. return fmt.Errorf("controller does not own config with key %s from source %s, manage this config at its source", key, source.String())
  255. }
  256. statuses, err := c.load()
  257. if err != nil {
  258. return fmt.Errorf("failed to load statuses")
  259. }
  260. err = c.deleteConfig(key, source, statuses)
  261. if err != nil {
  262. return fmt.Errorf("Controller: DeleteConfig: %w", err)
  263. }
  264. return nil
  265. }
  266. func (c *Controller) deleteConfig(key string, source ConfigSource, statuses Statuses) error {
  267. is, ok := statuses.Get(key, source)
  268. if !ok {
  269. return fmt.Errorf("config with key %s from source %s does not exist", key, source.String())
  270. }
  271. // delete config on observers if active
  272. if is.Active {
  273. c.broadcastRemoveConfig(key)
  274. }
  275. delete(statuses[source], key)
  276. c.save(statuses)
  277. return nil
  278. }
  279. func (c *Controller) load() (Statuses, error) {
  280. raw, err := os.ReadFile(c.path)
  281. if err != nil {
  282. return nil, fmt.Errorf("failed to load config statuses from file: %w", err)
  283. }
  284. statuses := Statuses{}
  285. err = json.Unmarshal(raw, &statuses)
  286. if err != nil {
  287. return nil, fmt.Errorf("failed to marshal config statuses: %s", err.Error())
  288. }
  289. return statuses, nil
  290. }
  291. func (c *Controller) save(statuses Statuses) error {
  292. raw, err := json.Marshal(statuses)
  293. if err != nil {
  294. return fmt.Errorf("failed to marshal config statuses: %s", err)
  295. }
  296. err = os.WriteFile(c.path, raw, 0644)
  297. if err != nil {
  298. return fmt.Errorf("failed to save config statuses to file: %s", err)
  299. }
  300. return nil
  301. }
  302. func (c *Controller) ExportConfigs(key string) (*Configurations, error) {
  303. c.lock.RLock()
  304. defer c.lock.RUnlock()
  305. configs := new(Configurations)
  306. activeConfigs := c.getActiveConfigs()
  307. if key != "" {
  308. conf, ok := activeConfigs[key]
  309. if !ok {
  310. return nil, fmt.Errorf("Config with key %s does not exist or is inactive", key)
  311. }
  312. sanitizedConfig := conf.Sanitize()
  313. err := configs.Insert(sanitizedConfig)
  314. if err != nil {
  315. return nil, fmt.Errorf("failed to insert config: %w", err)
  316. }
  317. return configs, nil
  318. }
  319. for _, conf := range activeConfigs {
  320. sanitizedConfig := conf.Sanitize()
  321. err := configs.Insert(sanitizedConfig)
  322. if err != nil {
  323. return nil, fmt.Errorf("failed to insert config: %w", err)
  324. }
  325. }
  326. return configs, nil
  327. }
  328. func (c *Controller) getActiveConfigs() map[string]cloud.KeyedConfig {
  329. activeConfigs := make(map[string]cloud.KeyedConfig)
  330. statuses, err := c.load()
  331. if err != nil {
  332. log.Errorf("GetStatus: failed to load cloud statuses")
  333. }
  334. for _, cs := range statuses.List() {
  335. if cs.Active {
  336. activeConfigs[cs.Key] = cs.Config
  337. }
  338. }
  339. return activeConfigs
  340. }
  341. // broadcastRemoveConfig ask observers to remove and stop all processes related to a configuration with a given key
  342. func (c *Controller) broadcastRemoveConfig(key string) {
  343. var wg sync.WaitGroup
  344. for _, obs := range c.observers {
  345. observer := obs
  346. wg.Add(1)
  347. go func() {
  348. defer wg.Done()
  349. observer.DeleteConfig(key)
  350. }()
  351. }
  352. wg.Wait()
  353. }
  354. // broadcastAddConfig gives observers a new config to handle
  355. func (c *Controller) broadcastAddConfig(conf cloud.KeyedConfig) {
  356. var wg sync.WaitGroup
  357. for _, obs := range c.observers {
  358. observer := obs
  359. wg.Add(1)
  360. go func() {
  361. defer wg.Done()
  362. observer.PutConfig(conf)
  363. }()
  364. }
  365. wg.Wait()
  366. }
  367. // RegisterObserver gives out the current active list configs and adds the observer to the push list
  368. func (c *Controller) RegisterObserver(obs Observer) {
  369. c.lock.Lock()
  370. defer c.lock.Unlock()
  371. obs.SetConfigs(c.getActiveConfigs())
  372. c.observers = append(c.observers, obs)
  373. }
  374. func (c *Controller) GetStatus() []Status {
  375. c.lock.RLock()
  376. defer c.lock.RUnlock()
  377. var status []Status
  378. statuses, err := c.load()
  379. if err != nil {
  380. log.Errorf("GetStatus: failed to load cloud statuses")
  381. }
  382. for _, intStat := range statuses.List() {
  383. status = append(status, *intStat)
  384. }
  385. return status
  386. }