controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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() {
  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. fmt.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: %s", err.Error())
  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 an config from the statuses and deletes the config on all observers if it was active
  244. func (c *Controller) DeleteConfig(key, source string) error {
  245. c.lock.Lock()
  246. defer c.lock.Unlock()
  247. statuses, err := c.load()
  248. if err != nil {
  249. return fmt.Errorf("failed to load statuses")
  250. }
  251. err = c.deleteConfig(key, GetConfigSource(source), statuses)
  252. if err != nil {
  253. return fmt.Errorf("Controller: DeleteConfig: %w", err)
  254. }
  255. return nil
  256. }
  257. func (c *Controller) deleteConfig(key string, source ConfigSource, statuses Statuses) error {
  258. if source != ConfigControllerSource {
  259. return fmt.Errorf("controller does not own config with key %s from source %s, manage this config at its source", key, source.String())
  260. }
  261. is, ok := statuses.Get(key, source)
  262. if !ok {
  263. return fmt.Errorf("config with key %s from source %s does not exist", key, source.String())
  264. }
  265. // delete config on observers if active
  266. if is.Active {
  267. c.broadcastRemoveConfig(key)
  268. }
  269. delete(statuses[source], key)
  270. c.save(statuses)
  271. return nil
  272. }
  273. func (c *Controller) load() (Statuses, error) {
  274. raw, err := os.ReadFile(c.path)
  275. if err != nil {
  276. return nil, fmt.Errorf("ConfigController: failed to load config statuses from file: %w", err)
  277. }
  278. statuses := Statuses{}
  279. err = json.Unmarshal(raw, &statuses)
  280. if err != nil {
  281. return nil, fmt.Errorf("ConfigController: failed to marshal config statuses: %s", err.Error())
  282. }
  283. return statuses, nil
  284. }
  285. func (c *Controller) save(statuses Statuses) error {
  286. raw, err := json.Marshal(statuses)
  287. if err != nil {
  288. return fmt.Errorf("ConfigController: failed to marshal config statuses: %s", err)
  289. }
  290. err = os.WriteFile(c.path, raw, 0644)
  291. if err != nil {
  292. return fmt.Errorf("ConfigController: failed to save config statuses to file: %s", err)
  293. }
  294. return nil
  295. }
  296. func (c *Controller) ExportConfigs(key string) (*Configurations, error) {
  297. c.lock.RLock()
  298. defer c.lock.RUnlock()
  299. configs := new(Configurations)
  300. activeConfigs := c.getActiveConfigs()
  301. if key != "" {
  302. conf, ok := activeConfigs[key]
  303. if !ok {
  304. return nil, fmt.Errorf("Config with key %s does not exist or is inactive", key)
  305. }
  306. sanitizedConfig := conf.Sanitize()
  307. err := configs.Insert(sanitizedConfig)
  308. if err != nil {
  309. return nil, fmt.Errorf("failed to insert config: %w", err)
  310. }
  311. return configs, nil
  312. }
  313. for _, conf := range activeConfigs {
  314. sanitizedConfig := conf.Sanitize()
  315. err := configs.Insert(sanitizedConfig)
  316. if err != nil {
  317. return nil, fmt.Errorf("failed to insert config: %w", err)
  318. }
  319. }
  320. return configs, nil
  321. }
  322. func (c *Controller) getActiveConfigs() map[string]cloud.KeyedConfig {
  323. activeConfigs := make(map[string]cloud.KeyedConfig)
  324. statuses, err := c.load()
  325. if err != nil {
  326. log.Errorf("GetStatus: failed to load cloud statuses")
  327. }
  328. for _, cs := range statuses.List() {
  329. if cs.Active {
  330. activeConfigs[cs.Key] = cs.Config
  331. }
  332. }
  333. return activeConfigs
  334. }
  335. // broadcastRemoveConfig ask observers to remove and stop all processes related to a configuration with a given key
  336. func (c *Controller) broadcastRemoveConfig(key string) {
  337. var wg sync.WaitGroup
  338. for _, obs := range c.observers {
  339. observer := obs
  340. wg.Add(1)
  341. go func() {
  342. defer wg.Done()
  343. observer.DeleteConfig(key)
  344. }()
  345. }
  346. wg.Wait()
  347. }
  348. // broadcastAddConfig gives observers a new config to handle
  349. func (c *Controller) broadcastAddConfig(conf cloud.KeyedConfig) {
  350. var wg sync.WaitGroup
  351. for _, obs := range c.observers {
  352. observer := obs
  353. wg.Add(1)
  354. go func() {
  355. defer wg.Done()
  356. observer.PutConfig(conf)
  357. }()
  358. }
  359. wg.Wait()
  360. }
  361. // RegisterObserver gives out the current active list configs and adds the observer to the push list
  362. func (c *Controller) RegisterObserver(obs Observer) {
  363. c.lock.Lock()
  364. defer c.lock.Unlock()
  365. obs.SetConfigs(c.getActiveConfigs())
  366. c.observers = append(c.observers, obs)
  367. }
  368. func (c *Controller) GetStatus() []Status {
  369. c.lock.RLock()
  370. defer c.lock.RUnlock()
  371. var status []Status
  372. statuses, err := c.load()
  373. if err != nil {
  374. log.Errorf("GetStatus: failed to load cloud statuses")
  375. }
  376. for _, intStat := range statuses.List() {
  377. status = append(status, *intStat)
  378. }
  379. return status
  380. }