configfile.go 9.8 KB

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