controller.go 12 KB

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