configfile.go 10 KB

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