configfile.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package config
  2. import (
  3. "errors"
  4. "os"
  5. "sort"
  6. "sync"
  7. "time"
  8. "github.com/google/uuid"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/storage"
  11. "github.com/opencost/opencost/core/pkg/util/atomic"
  12. )
  13. // HandlerID is a unique identifier assigned to a provided ConfigChangedHandler. This is used to remove a handler
  14. // from the ConfigFile when it is no longer needed.
  15. type HandlerID string
  16. //--------------------------------------------------------------------------
  17. // ChangeType
  18. //--------------------------------------------------------------------------
  19. // ChangeType is used to specifically categorize the change that was made on a ConfigFile
  20. type ChangeType string
  21. // ChangeType constants contain the different types of updates passed through the ConfigChangedHandler
  22. const (
  23. ChangeTypeCreated ChangeType = "created"
  24. ChangeTypeModified ChangeType = "modified"
  25. ChangeTypeDeleted ChangeType = "deleted"
  26. )
  27. //--------------------------------------------------------------------------
  28. // ConfigChangedHandler
  29. //--------------------------------------------------------------------------
  30. // ConfigChangedHandler is the func handler used to receive change updates about the
  31. // config file. Both ChangeTypeCreated and ChangeTypeModified yield a valid []byte, while
  32. // ChangeTypeDeleted yields a nil []byte.
  33. type ConfigChangedHandler func(ChangeType, []byte)
  34. //--------------------------------------------------------------------------
  35. // ConfigFile
  36. //--------------------------------------------------------------------------
  37. // DefaultHandlerPriority is used as the priority for any handlers added via AddChangeHandler
  38. const DefaultHandlerPriority int = 1000
  39. // NoBackingStore error is used when the config file's backing storage is missing
  40. var NoBackingStore error = errors.New("Backing storage does not exist.")
  41. // ConfigFile is representation of a configuration file that can be written to, read, and watched
  42. // for updates
  43. type ConfigFile struct {
  44. store storage.Storage
  45. file string
  46. dataLock sync.Mutex
  47. data []byte
  48. watchLock sync.Mutex
  49. watchers []*pHandler
  50. runState atomic.AtomicRunState
  51. lastChange time.Time
  52. }
  53. // NewConfigFile creates a new ConfigFile instance using a specific storage.Storage and path relative
  54. // to the storage.
  55. func NewConfigFile(store storage.Storage, file string) *ConfigFile {
  56. return &ConfigFile{
  57. store: store,
  58. file: file,
  59. data: nil,
  60. }
  61. }
  62. // Path returns the fully qualified path of the config file.
  63. func (cf *ConfigFile) Path() string {
  64. if cf.store == nil {
  65. return cf.file
  66. }
  67. return cf.store.FullPath(cf.file)
  68. }
  69. // Write will write the binary data to the file.
  70. func (cf *ConfigFile) Write(data []byte) error {
  71. if cf.store == nil {
  72. return NoBackingStore
  73. }
  74. e := cf.store.Write(cf.file, data)
  75. // update cache on successful write
  76. if e == nil {
  77. cf.dataLock.Lock()
  78. cf.data = data
  79. cf.dataLock.Unlock()
  80. }
  81. return e
  82. }
  83. // Read will read the binary data from the file and return it. If an error is returned,
  84. // the byte array will be nil.
  85. func (cf *ConfigFile) Read() ([]byte, error) {
  86. return cf.internalRead(false)
  87. }
  88. // internalRead is used to allow a forced override of data cache to refresh data
  89. func (cf *ConfigFile) internalRead(force bool) ([]byte, error) {
  90. if cf.store == nil {
  91. return nil, NoBackingStore
  92. }
  93. cf.dataLock.Lock()
  94. defer cf.dataLock.Unlock()
  95. if !force {
  96. if cf.data != nil {
  97. return cf.data, nil
  98. }
  99. }
  100. d, e := cf.store.Read(cf.file)
  101. if e != nil {
  102. return nil, e
  103. }
  104. cf.data = d
  105. return cf.data, nil
  106. }
  107. // Stat returns the StorageStats for the file.
  108. func (cf *ConfigFile) Stat() (*storage.StorageInfo, error) {
  109. if cf.store == nil {
  110. return nil, NoBackingStore
  111. }
  112. return cf.store.Stat(cf.file)
  113. }
  114. // Exists returns true if the file exist. If an error other than a NotExist error is returned,
  115. // the result will be false with the provided error.
  116. func (cf *ConfigFile) Exists() (bool, error) {
  117. if cf.store == nil {
  118. return false, NoBackingStore
  119. }
  120. return cf.store.Exists(cf.file)
  121. }
  122. // Delete removes the file from storage permanently.
  123. func (cf *ConfigFile) Delete() error {
  124. if cf.store == nil {
  125. return NoBackingStore
  126. }
  127. e := cf.store.Remove(cf.file)
  128. // on removal, clear data cache
  129. if e == nil {
  130. cf.dataLock.Lock()
  131. cf.data = nil
  132. cf.dataLock.Unlock()
  133. }
  134. return e
  135. }
  136. // Refresh allows external callers to force reload the config file from internal storage. This is
  137. // particularly useful when there exist no change listeners on the config, which would prevent the
  138. // data cache from automatically updating on change
  139. func (cf *ConfigFile) Refresh() ([]byte, error) {
  140. return cf.internalRead(true)
  141. }
  142. // AddChangeHandler accepts a ConfigChangedHandler function which will be called whenever the implementation
  143. // detects that a change has been made. A unique HandlerID is returned that can be used to remove the handler
  144. // if necessary.
  145. func (cf *ConfigFile) AddChangeHandler(handler ConfigChangedHandler) HandlerID {
  146. return cf.AddPriorityChangeHandler(handler, DefaultHandlerPriority)
  147. }
  148. // AddPriorityChangeHandler allows adding a config change handler with a specific priority. By default,
  149. // any handlers added via AddChangeHandler have a default priority of 1000. The lower the priority, the
  150. // sooner in the handler execution it will be called.
  151. func (cf *ConfigFile) AddPriorityChangeHandler(handler ConfigChangedHandler, priority int) HandlerID {
  152. cf.watchLock.Lock()
  153. defer cf.watchLock.Unlock()
  154. h := &pHandler{
  155. id: HandlerID(uuid.NewString()),
  156. handler: handler,
  157. priority: priority,
  158. }
  159. cf.watchers = append(cf.watchers, h)
  160. // create the actual file watcher once we have at least one active watcher func registered
  161. if len(cf.watchers) == 1 {
  162. cf.runWatcher()
  163. }
  164. return h.id
  165. }
  166. // RemoveChangeHandler removes the change handler with the provided identifier if it exists. True
  167. // is returned if the handler was removed (it existed), false otherwise.
  168. func (cf *ConfigFile) RemoveChangeHandler(id HandlerID) bool {
  169. cf.watchLock.Lock()
  170. defer cf.watchLock.Unlock()
  171. for i := range cf.watchers {
  172. if cf.watchers[i] != nil && cf.watchers[i].id == id {
  173. copy(cf.watchers[i:], cf.watchers[i+1:])
  174. cf.watchers[len(cf.watchers)-1] = nil
  175. cf.watchers = cf.watchers[:len(cf.watchers)-1]
  176. // stop watching the file for changes if there are no more external watchers
  177. if len(cf.watchers) == 0 {
  178. cf.stopWatcher()
  179. }
  180. return true
  181. }
  182. }
  183. return false
  184. }
  185. // RemoveAllHandlers removes all added handlers
  186. func (cf *ConfigFile) RemoveAllHandlers() {
  187. cf.watchLock.Lock()
  188. defer cf.watchLock.Unlock()
  189. cf.watchers = nil
  190. cf.stopWatcher()
  191. }
  192. // runWatcher creates a go routine which will poll the stat of a storage target on a specific
  193. // interval and dispatch created, modified, and deleted events for that file.
  194. func (cf *ConfigFile) runWatcher() {
  195. // we wait for a reset on the run state prior to starting, which
  196. // will only block iff the run state is in the process of stopping
  197. cf.runState.WaitForReset()
  198. // if start fails after waiting for a reset, it means that another thread
  199. // beat this thread to the start
  200. if !cf.runState.Start() {
  201. log.Warnf("Run watcher already running for file: %s", cf.file)
  202. return
  203. }
  204. go func() {
  205. first := true
  206. var last time.Time
  207. var exists bool
  208. for {
  209. // Each iteration, check for the stop trigger, or wait 10 seconds
  210. select {
  211. case <-cf.runState.OnStop():
  212. cf.runState.Reset()
  213. return
  214. case <-time.After(10 * time.Second):
  215. }
  216. // Query stat on the file, on errors other than exists,
  217. // we'll need to log the error, and perhaps limit the retries
  218. st, err := cf.Stat()
  219. if err != nil && !os.IsNotExist(err) {
  220. log.Errorf("Storage Stat Error: %s", err)
  221. continue
  222. }
  223. // On first iteration, set exists and last modification time (if applicable)
  224. // and flip flag
  225. if first {
  226. exists = !os.IsNotExist(err)
  227. if exists {
  228. last = st.ModTime
  229. }
  230. first = false
  231. continue
  232. }
  233. // File does not exist in storage, need to check to see if that is different
  234. // from last state check
  235. if os.IsNotExist(err) {
  236. // check to see if the file has gone from exists to !exists
  237. if exists {
  238. exists = false
  239. cf.onFileChange(ChangeTypeDeleted, nil)
  240. }
  241. continue
  242. }
  243. // check to see if the file has gone from !exists to exists
  244. if !exists {
  245. data, err := cf.internalRead(true)
  246. if err != nil {
  247. log.Warnf("Read() Error: %s\n", err)
  248. continue
  249. }
  250. exists = true
  251. last = st.ModTime
  252. cf.onFileChange(ChangeTypeCreated, data)
  253. continue
  254. }
  255. mtime := st.ModTime
  256. if mtime != last {
  257. last = mtime
  258. data, err := cf.internalRead(true)
  259. if err != nil {
  260. log.Errorf("Read() Error: %s\n", err)
  261. continue
  262. }
  263. cf.onFileChange(ChangeTypeModified, data)
  264. }
  265. }
  266. }()
  267. }
  268. // stopWatcher closes the stop channel, returning from the runWatcher go routine. Allows us
  269. // to remove any polling stat checks on files when there are no change handlers.
  270. func (cf *ConfigFile) stopWatcher() {
  271. cf.runState.Stop()
  272. }
  273. // onFileChange is internally called when the core watcher recognizes a change in the ConfigFile. This
  274. // method dispatches that change to all added watchers
  275. func (cf *ConfigFile) onFileChange(changeType ChangeType, newData []byte) {
  276. // On change, we copy out the handlers to a separate slice for processing for a few reasons:
  277. // 1. We don't want to lock while executing the handlers
  278. // 2. Handlers may want to operate on the ConfigFile instance, which would result in a deadlock
  279. // 3. Allows us to implement priority sorting outside of the lock as well
  280. cf.watchLock.Lock()
  281. if len(cf.watchers) == 0 {
  282. cf.watchLock.Unlock()
  283. return
  284. }
  285. toNotify := make([]*pHandler, len(cf.watchers))
  286. copy(toNotify, cf.watchers)
  287. cf.watchLock.Unlock()
  288. sort.SliceStable(toNotify, func(i, j int) bool {
  289. return toNotify[i].priority < toNotify[j].priority
  290. })
  291. for _, handler := range toNotify {
  292. handler.handler(changeType, newData)
  293. }
  294. }
  295. //--------------------------------------------------------------------------
  296. // pHandler
  297. //--------------------------------------------------------------------------
  298. // pHandler is a wrapper type used to assign a ConfigChangedHandler a unique identifier and priority.
  299. type pHandler struct {
  300. id HandlerID
  301. handler ConfigChangedHandler
  302. priority int
  303. }