reloader.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package common
  20. import (
  21. "hash/crc64"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "sync"
  26. )
  27. // Reloader represents a read-only, in-memory reloadable data object. For example,
  28. // a JSON data file that is loaded into memory and accessed for read-only lookups;
  29. // and from time to time may be reloaded from the same file, updating the memory
  30. // copy.
  31. type Reloader interface {
  32. // Reload reloads the data object. Reload returns a flag indicating if the
  33. // reloadable target has changed and reloaded or remains unchanged. By
  34. // convention, when reloading fails the Reloader should revert to its previous
  35. // in-memory state.
  36. Reload() (bool, error)
  37. // WillReload indicates if the data object is capable of reloading.
  38. WillReload() bool
  39. // LogDescription returns a description to be used for logging
  40. // events related to the Reloader.
  41. LogDescription() string
  42. }
  43. // ReloadableFile is a file-backed Reloader. This type is intended to be embedded
  44. // in other types that add the actual reloadable data structures.
  45. //
  46. // ReloadableFile has a multi-reader mutex for synchronization. Its Reload() function
  47. // will obtain a write lock before reloading the data structures. The actual reloading
  48. // action is to be provided via the reloadAction callback, which receives the content
  49. // of reloaded files and must process the new data (for example, unmarshall the contents
  50. // into data structures). All read access to the data structures should be guarded by
  51. // RLocks on the ReloadableFile mutex.
  52. //
  53. // reloadAction must ensure that data structures revert to their previous state when
  54. // a reload fails.
  55. //
  56. type ReloadableFile struct {
  57. sync.RWMutex
  58. filename string
  59. loadFileContent bool
  60. checksum uint64
  61. reloadAction func([]byte) error
  62. }
  63. // NewReloadableFile initializes a new ReloadableFile.
  64. //
  65. // When loadFileContent is true, the file content is loaded and passed to
  66. // reloadAction; otherwise, reloadAction receives a nil argument and is
  67. // responsible for loading the file. The latter option allows for cases where
  68. // the file contents must be streamed, memory mapped, etc.
  69. func NewReloadableFile(
  70. filename string,
  71. loadFileContent bool,
  72. reloadAction func([]byte) error) ReloadableFile {
  73. return ReloadableFile{
  74. filename: filename,
  75. loadFileContent: loadFileContent,
  76. reloadAction: reloadAction,
  77. }
  78. }
  79. // WillReload indicates whether the ReloadableFile is capable
  80. // of reloading.
  81. func (reloadable *ReloadableFile) WillReload() bool {
  82. return reloadable.filename != ""
  83. }
  84. var crc64table = crc64.MakeTable(crc64.ISO)
  85. // Reload checks if the underlying file has changed and, when changed, invokes
  86. // the reloadAction callback which should reload the in-memory data structures.
  87. //
  88. // In some case (e.g., traffic rules and OSL), there are penalties associated
  89. // with proceeding with reload, so care is taken to not invoke the reload action
  90. // unless the contents have changed.
  91. //
  92. // The file content is loaded and a checksum is taken to determine whether it
  93. // has changed. Neither file size (may not change when content changes) nor
  94. // modified date (may change when identical file is repaved) is a sufficient
  95. // indicator.
  96. //
  97. // All data structure readers should be blocked by the ReloadableFile mutex.
  98. //
  99. // Reload must not be called from multiple concurrent goroutines.
  100. func (reloadable *ReloadableFile) Reload() (bool, error) {
  101. if !reloadable.WillReload() {
  102. return false, nil
  103. }
  104. // Check whether the file has changed _before_ blocking readers
  105. reloadable.RLock()
  106. filename := reloadable.filename
  107. previousChecksum := reloadable.checksum
  108. reloadable.RUnlock()
  109. file, err := os.Open(filename)
  110. if err != nil {
  111. return false, ContextError(err)
  112. }
  113. defer file.Close()
  114. hash := crc64.New(crc64table)
  115. _, err = io.Copy(hash, file)
  116. if err != nil {
  117. return false, ContextError(err)
  118. }
  119. checksum := hash.Sum64()
  120. if checksum == previousChecksum {
  121. return false, nil
  122. }
  123. // It's possible for the file content to revert to its previous value
  124. // between the checksum operation and subsequent content load. We accept
  125. // the false positive in this unlikely case.
  126. var content []byte
  127. if reloadable.loadFileContent {
  128. _, err = file.Seek(0, 0)
  129. if err != nil {
  130. return false, ContextError(err)
  131. }
  132. content, err = ioutil.ReadAll(file)
  133. if err != nil {
  134. return false, ContextError(err)
  135. }
  136. }
  137. // Don't keep file open during reloadAction call.
  138. file.Close()
  139. // ...now block readers and reload
  140. reloadable.Lock()
  141. defer reloadable.Unlock()
  142. err = reloadable.reloadAction(content)
  143. if err != nil {
  144. return false, ContextError(err)
  145. }
  146. reloadable.checksum = checksum
  147. return true, nil
  148. }
  149. func (reloadable *ReloadableFile) LogDescription() string {
  150. return reloadable.filename
  151. }