config.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. /*
  10. Package fileutil contains file based utilities and helper functions.
  11. */
  12. package fileutil
  13. import (
  14. "crypto/sha256"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "strings"
  22. "sync"
  23. "time"
  24. "devt.de/krotik/common/stringutil"
  25. )
  26. /*
  27. LoadConfig loads or creates a JSON based configuration file. Missing settings
  28. from the config file will be filled with default settings. This function provides
  29. a simple mechanism for programs to handle user-defined configuration files which
  30. should be loaded at start time.
  31. */
  32. func LoadConfig(filename string, defaultConfig map[string]interface{}) (map[string]interface{}, error) {
  33. var mdata []byte
  34. var data map[string]interface{}
  35. var err error
  36. var ok bool
  37. if ok, err = PathExists(filename); err != nil {
  38. return nil, err
  39. } else if ok {
  40. // Load config
  41. mdata, err = ioutil.ReadFile(filename)
  42. if err == nil {
  43. err = json.Unmarshal(mdata, &data)
  44. if err == nil {
  45. // Make sure all required configuration values are set
  46. for k, v := range defaultConfig {
  47. if dv, ok := data[k]; !ok || dv == nil {
  48. data[k] = v
  49. }
  50. }
  51. }
  52. }
  53. } else if err == nil {
  54. // Write config
  55. data = defaultConfig
  56. mdata, err = json.MarshalIndent(data, "", " ")
  57. if err == nil {
  58. err = ioutil.WriteFile(filename, mdata, 0644)
  59. }
  60. }
  61. if err != nil {
  62. return nil, err
  63. }
  64. return data, nil
  65. }
  66. /*
  67. ConfStr reads a config value as a string value.
  68. */
  69. func ConfStr(config map[string]interface{}, key string) string {
  70. return fmt.Sprint(config[key])
  71. }
  72. /*
  73. ConfBool reads a config value as a boolean value.
  74. */
  75. func ConfBool(config map[string]interface{}, key string) bool {
  76. return strings.ToLower(fmt.Sprint(config[key])) == "true"
  77. }
  78. // Watched Config
  79. // ==============
  80. /*
  81. WatchedConfigErrRetries is the number of times the code will try to
  82. read the disk configuration before overwriting it with the current
  83. (working) configuration. Set to -1 if it should never attempt to overwrite.
  84. */
  85. var WatchedConfigErrRetries = 10
  86. /*
  87. watchSleep is the sleep which is used by the watch thread
  88. */
  89. var watchSleep = time.Sleep
  90. /*
  91. Defined error codes for WatchedConfig
  92. */
  93. var (
  94. ErrClosed = errors.New("Config file was closed")
  95. )
  96. /*
  97. WatchedConfig is a helper object which continuously watches a given config file.
  98. The file and the memory config are kept in sync.
  99. */
  100. type WatchedConfig struct {
  101. config map[string]interface{} // Internal in memory config
  102. configLock *sync.RWMutex // Lock for config
  103. interval time.Duration // Interval with which the file should be watched
  104. filename string // File which stores the config
  105. SyncError error // Synchronization errors
  106. shutdown chan bool // Signal channel for thread shutdown
  107. }
  108. /*
  109. NewWatchedConfig returns a new watcher object for a given config file.
  110. */
  111. func NewWatchedConfig(filename string, defaultConfig map[string]interface{},
  112. interval time.Duration) (*WatchedConfig, error) {
  113. var ret *WatchedConfig
  114. config, err := LoadConfig(filename, defaultConfig)
  115. if err == nil {
  116. wc := &WatchedConfig{config, &sync.RWMutex{}, interval, filename, nil, nil}
  117. err = wc.start()
  118. if err == nil {
  119. ret = wc
  120. }
  121. }
  122. return ret, err
  123. }
  124. /*
  125. GetValue returns a single config value.
  126. */
  127. func (wc *WatchedConfig) GetValue(k string) (interface{}, bool, error) {
  128. wc.configLock.Lock()
  129. defer wc.configLock.Unlock()
  130. if wc.SyncError != nil {
  131. return nil, false, wc.SyncError
  132. }
  133. val, ok := wc.config[k]
  134. return val, ok, nil
  135. }
  136. /*
  137. GetConfig returns the current config.
  138. */
  139. func (wc *WatchedConfig) GetConfig() (map[string]interface{}, error) {
  140. wc.configLock.Lock()
  141. defer wc.configLock.Unlock()
  142. if wc.SyncError != nil {
  143. return nil, wc.SyncError
  144. }
  145. cconfig := make(map[string]interface{})
  146. for k, v := range wc.config {
  147. cconfig[k] = v
  148. }
  149. return cconfig, nil
  150. }
  151. /*
  152. start kicks off the file watcher background thread.
  153. */
  154. func (wc *WatchedConfig) start() error {
  155. // Sync from file - if the file exists. No need to hold a lock since
  156. // we are in the startup
  157. err := wc.sync(true)
  158. if err == nil {
  159. // Kick off watcher
  160. wc.shutdown = make(chan bool)
  161. go wc.watch()
  162. }
  163. return err
  164. }
  165. /*
  166. watch is the internal file watch goroutine function.
  167. */
  168. func (wc *WatchedConfig) watch() {
  169. err := wc.SyncError
  170. errCnt := 0
  171. defer func() {
  172. wc.shutdown <- true
  173. }()
  174. for wc.SyncError != ErrClosed {
  175. // Wakeup every interval
  176. watchSleep(wc.interval)
  177. // Run the sync
  178. wc.configLock.Lock()
  179. // Sync from file
  180. if err = wc.sync(true); err != nil && wc.SyncError != ErrClosed {
  181. // Increase the error count
  182. err = fmt.Errorf("Could not sync config from disk: %v",
  183. err.Error())
  184. errCnt++
  185. } else {
  186. // Reset the error count
  187. errCnt = 0
  188. }
  189. // Update the sync error
  190. if wc.SyncError != ErrClosed {
  191. wc.SyncError = err
  192. }
  193. if errCnt == WatchedConfigErrRetries {
  194. // We can't read the disk configuration after
  195. // WatchedConfigErrRetries attempts - try to overwrite
  196. // it with the working memory configuration
  197. wc.sync(false)
  198. }
  199. wc.configLock.Unlock()
  200. }
  201. }
  202. /*
  203. Close closes this config watcher.
  204. */
  205. func (wc *WatchedConfig) Close() error {
  206. var err error
  207. wc.configLock.Lock()
  208. if wc.SyncError != nil {
  209. // Preserve any old error
  210. err = wc.SyncError
  211. }
  212. // Set the table into the closed state
  213. wc.SyncError = ErrClosed
  214. wc.configLock.Unlock()
  215. // Wait for watcher shutdown if it was started
  216. if wc.shutdown != nil {
  217. <-wc.shutdown
  218. wc.shutdown = nil
  219. }
  220. return err
  221. }
  222. /*
  223. Attempt to synchronize the memory config with the file. Depending on the
  224. checkFile flag either the file (true) or the memory config (false) is
  225. regarded as up-to-date.
  226. It is assumed that the configLock (write) is held before calling this
  227. function.
  228. The table is in an undefined state if an error is returned.
  229. */
  230. func (wc *WatchedConfig) sync(checkFile bool) error {
  231. var checksumFile, checksumMemory string
  232. stringMemoryTable := func() ([]byte, error) {
  233. return json.MarshalIndent(wc.config, "", " ")
  234. }
  235. writeMemoryTable := func() error {
  236. res, err := stringMemoryTable()
  237. if err == nil {
  238. err = ioutil.WriteFile(wc.filename, res, 0644)
  239. }
  240. return err
  241. }
  242. readMemoryTable := func() (map[string]interface{}, error) {
  243. var conf map[string]interface{}
  244. res, err := ioutil.ReadFile(wc.filename)
  245. if err == nil {
  246. err = json.Unmarshal(stringutil.StripCStyleComments(res), &conf)
  247. }
  248. return conf, err
  249. }
  250. // Check if the file can be opened
  251. file, err := os.OpenFile(wc.filename, os.O_RDONLY, 0660)
  252. if err != nil {
  253. if os.IsNotExist(err) {
  254. // Just ignore not found errors
  255. err = nil
  256. }
  257. // File does not exist - no checksum
  258. checksumFile = ""
  259. } else {
  260. hashFactory := sha256.New()
  261. if _, err = io.Copy(hashFactory, file); err == nil {
  262. // Create the checksum of the present file
  263. checksumFile = fmt.Sprintf("%x", hashFactory.Sum(nil))
  264. }
  265. file.Close()
  266. }
  267. if err == nil {
  268. // At this point we know everything about the file now check
  269. // the memory table
  270. var cString []byte
  271. if cString, err = stringMemoryTable(); err == nil {
  272. hashFactory := sha256.New()
  273. hashFactory.Write(cString)
  274. checksumMemory = fmt.Sprintf("%x", hashFactory.Sum(nil))
  275. }
  276. }
  277. if err == nil {
  278. // At this point we also know everything about the memory table
  279. if checkFile {
  280. // File is up-to-date - we should build the memory table
  281. if checksumFile != checksumMemory {
  282. var conf map[string]interface{}
  283. if conf, err = readMemoryTable(); err == nil {
  284. wc.config = conf
  285. }
  286. }
  287. } else {
  288. // Memory is up-to-date - we should write a new file
  289. if checksumFile != checksumMemory {
  290. err = writeMemoryTable()
  291. }
  292. }
  293. }
  294. return err
  295. }